If nothing of that work, close Android Studio. Go on app/src/main, open the file AndroidManifest.xml in a text editor (like sublime), remove/replace the erros lines, save and reopen android studio.
font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family
You can save excel
as unicode
text, it is tab-delimited.
#navigation .navigationLevel2 li
{
color: #f00;
}
I faced this issue because my selector was depend on id
meanwhile I did not set id for my element
my selector
was
$("#EmployeeName")
but my HTML element
<input type="text" name="EmployeeName">
so just make sure that your selector criteria are valid
Just to create a separate answer. The answer is actually found in a comment for the accepted answer.
Try changing the version of your artefact to end with -SNAPSHOT
.
You can try MailKit MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. You can use easily in your application.You can download from here.
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(fromName, [email protected]));
mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("[email protected]", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Import in Java does not work at all, as it is evaluated at compile time only. (Treat it as shortcuts so you do not have to write fully qualified class names). At runtime there is no import at all, just FQCNs.
At runtime it is necessary that all classes you have referenced can be found by classloaders. (classloader infrastructure is sometimes dark magic and highly dependent on environment.) In case of an applet you will have to rig up your HTML tag properly and also provide necessary JAR archives on your server.
PS: Matching at runtime is done via qualified class names - class found under this name is not necessarily the same or compatible with class you have compiled against.
Firstly, it's necessary to know what is a jar file.
From Oracle,
JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time.
As you can see,
Assuming you're targeting browsers that aren't IE8,
this would work as well:
function checkIfArrayIsUnique(myArray)
{
for (var i = 0; i < myArray.length; i++)
{
if (myArray.indexOf(myArray[i]) !== myArray.lastIndexOf(myArray[i])) {
return false;
}
}
return true; // this means not unique
}
Call the TreeView.OnAfterSelect()
protected method after you programatically select the node.
There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.
In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):
ps aux | grep python | grep -v "grep python" | awk '{print $2}' | xargs kill -9
To break this down, this is how it works. The first bit, ps aux | grep python | grep -v "grep python"
, gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn't also included in the output. Next, we use awk to get the second column of the output, which has the process ID's. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9
.
Try this for check null
if (text == nil)
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
I would do something like this but i bet there is a simpler way. i think the sql from linqtosql would use a select from person Where NOT EXIST(select from your exclusion list)
static class Program
{
public class Person
{
public string Key { get; set; }
public Person(string key)
{
Key = key;
}
}
public class NotPerson
{
public string Key { get; set; }
public NotPerson(string key)
{
Key = key;
}
}
static void Main()
{
List<Person> persons = new List<Person>()
{
new Person ("1"),
new Person ("2"),
new Person ("3"),
new Person ("4")
};
List<NotPerson> notpersons = new List<NotPerson>()
{
new NotPerson ("3"),
new NotPerson ("4")
};
var filteredResults = from n in persons
where !notpersons.Any(y => n.Key == y.Key)
select n;
foreach (var item in filteredResults)
{
Console.WriteLine(item.Key);
}
}
}
I had a problem with sending a request with multiple parameters.
I've solved it by sending a class, with the old parameters as properties.
<form action="http://localhost:12345/api/controller/method" method="post">
<input type="hidden" name="name1" value="value1" />
<input type="hidden" name="name2" value="value2" />
<input type="submit" name="submit" value="Submit" />
</form>
Model class:
public class Model {
public string Name1 { get; set; }
public string Name2 { get; set; }
}
Controller:
public void method(Model m) {
string name = m.Name1;
}
export PATH=/usr/local/bin:$PATH
brew update
brew install vim && brew install macvim
brew link macvim
You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade
every once in a while to upgrade them.
This includes the installation of the CLI mvim
and the mac application (which both point to the same thing).
I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
Based on ?eurobur?, test an sub-class case
class Foo: NSObject {
func test() {
print("1")
objc_sync_enter(self)
defer {
objc_sync_exit(self)
print("3")
}
print("2")
}
}
class Foo2: Foo {
override func test() {
super.test()
print("11")
objc_sync_enter(self)
defer {
print("33")
objc_sync_exit(self)
}
print("22")
}
}
let test = Foo2()
test.test()
1
2
3
11
22
33
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
Your problem is that you are NOT testing the length of the array until it is too late.
But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.
The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.
The code seems working to me. I think the same with @Iothar.
Check to see if you include the required headers, to compile. If it is compiled, check to see if there is such a file, and everything, names etc, matches, and also check to see that you have a right to read the file.
To make a cross check, check if you can open it with fopen..
FILE *f = fopen("C:/Demo.txt", "r");
if (f)
printf("fopen success\n");
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]'));
You're thinking too complicated. It's actually just $('#'+openaddress)
.
If you`re not using jQuery then please make sure:
var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
And for the php receiving end:
$_POST['json_name']
If you repository supports tokens (for example GitLab) then generate a token for your user then navigate to the file you will download and click on RAW output to get the URL. To download the file use:
curl --silent --request GET --header 'PRIVATE-TOKEN: replace_with_your_token' \
'http://git.example.com/foo/bar.sql' --output /tmp/bar.sql
Use strtotime()
on your first date then date('Y-m-d')
to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash /
and hyphen -
in the strtotime()
function. To quote from php.net:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
You need to import FormsModule in your @NgModule Decorator, @NgModule is present in your moduleName.module.ts file.
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
Use insert method from range, for example
Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
try this:
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);
or
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);
A C++ program to check if two given line segments intersect
#include <iostream>
using namespace std;
struct Point
{
int x;
int y;
};
// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
return true;
return false;
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
// See 10th slides from following link for derivation of the formula
// http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4)
return true;
// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) return true;
// p1, q1 and p2 are colinear and q2 lies on segment p1q1
if (o2 == 0 && onSegment(p1, q2, q1)) return true;
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && onSegment(p2, p1, q2)) return true;
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 && onSegment(p2, q1, q2)) return true;
return false; // Doesn't fall in any of the above cases
}
// Driver program to test above functions
int main()
{
struct Point p1 = {1, 1}, q1 = {10, 1};
struct Point p2 = {1, 2}, q2 = {10, 2};
doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
p1 = {10, 0}, q1 = {0, 10};
p2 = {0, 0}, q2 = {10, 10};
doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
p1 = {-5, -5}, q1 = {0, 0};
p2 = {1, 1}, q2 = {10, 10};
doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";
return 0;
}
$articles =DB::table('articles')
->join('categories','articles.id', '=', 'categories.id')
->join('user', 'articles.user_id', '=', 'user.id')
->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
->get();
return view('myarticlesview',['articles'=>$articles]);
You need to consider the way the datediff command rounds.
SELECT CASE WHEN dateadd(year, datediff (year, DOB, getdate()), DOB) > getdate()
THEN datediff(year, DOB, getdate()) - 1
ELSE datediff(year, DOB, getdate())
END as Age
FROM <table>
Which I adapted from here.
Note that it will consider 28th February as the birthday of a leapling for non-leap years e.g. a person born on 29 Feb 2020 will be considered 1 year old on 28 Feb 2021 instead of 01 Mar 2021.
ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.
I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.
The Android Developer Guide has a section called Building Custom Components. Unfortunately, the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:
values\attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="android:text"/>
<attr name="android:textColor"/>
<attr name="extraInformation" format="string" />
</declare-styleable>
</resources>
Notice the use of an unqualified name in the declare-styleable
tag. Non-standard android attributes like extraInformation
need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.
Since there are two constructors that use an AttributeSet
for initialisation, it is convenient to create a separate initialisation method for the constructors to call.
private void init(AttributeSet attrs) {
TypedArray a=getContext().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView);
//Use a
Log.i("test",a.getString(
R.styleable.MyCustomView_android_text));
Log.i("test",""+a.getColor(
R.styleable.MyCustomView_android_textColor, Color.BLACK));
Log.i("test",a.getString(
R.styleable.MyCustomView_extraInformation));
//Don't forget this
a.recycle();
}
R.styleable.MyCustomView
is an autogenerated int[]
resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, R.styleable.MyCustomView_android_text
contains the android_text
attribute for MyCustomView
. Attributes can then be retrieved from the TypedArray
using various get
functions. If the attribute is not defined in the defined in the XML, then null
is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.
If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr
, while attributes for this project are in R.attr
.
int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};
Please note that you should not use anything in android.R.styleable
, as per this thread it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.
layout\main.xml
Include the namespace declaration xmlns:app="http://schemas.android.com/apk/res-auto"
in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see this article for more info). The URL is simply a manner of uniquely identifying schemas - nothing actually needs to be hosted at that URL. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.
<com.mycompany.projectname.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:text="Test text"
android:textColor="#FFFFFF"
app:extraInformation="My extra information"
/>
Reference the custom view using the fully qualified name.
If you want a complete example, look at the android label view sample.
TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
CharSequences=a.getString(R.styleable.LabelView_text);
<declare-styleable name="LabelView">
<attr name="text"format="string"/>
<attr name="textColor"format="color"/>
<attr name="textSize"format="dimension"/>
</declare-styleable>
<com.example.android.apis.view.LabelView
android:background="@drawable/blue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
app:text="Blue" app:textSize="20dp"/>
This is contained in a LinearLayout
with a namespace attribute: xmlns:app="http://schemas.android.com/apk/res-auto"
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
String
's init(format:_:)
initializerFoundation
provides Swift String
a init(format:_:)
initializer. init(format:_:)
has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:_:)
:
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
String
's init(format:arguments:)
initializerFoundation
provides Swift String
a init(format:arguments:)
initializer. init(format:arguments:)
has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:arguments:)
:
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
NumberFormatter
Foundation provides NumberFormatter
. Apple states about it:
Instances of
NSNumberFormatter
format the textual representation of cells that containNSNumber
objects and convert textual representations of numeric values intoNSNumber
objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter
that returns String?
from a Int
with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
My recommendation is to use top location 33% or 25% from remaining space,
and not 50% as other examples posted here,
mainly because of the window header,
which look better and more comfort to the user,
complete code:
<script language="javascript" type="text/javascript">
function OpenPopupCenter(pageURL, title, w, h) {
var left = (screen.width - w) / 2;
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3
var targetWin = window.open(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}
</script>
</head>
<body>
<button onclick="OpenPopupCenter('http://www.google.com', 'TEST!?', 800, 600);">click on me</button>
</body>
</html>
check out this line:
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3
Add a column to your existing data to get rid of the hour:minute:second time stamp on each row:
=DATE(YEAR(A1), MONTH(A1), DAY(A1))
Extend this down the length of your data. Even easier: quit collecting the hh:mm:ss data if you don't need it. Assuming your date/time was in column A, and your value was in column B, you'd put the above formula in column C, and auto-extend it for all your data.
Now, in another column (let's say E), create a series of dates corresponding to each day of the specific month you're interested in. Just type the first date, (for example, 10/7/2016 in E1), and auto-extend. Then, in the cell next to the first date, F1, enter:
=SUMIF(C:C, E1, B:B )
autoextend the formula to cover every date in the month, and you're done. Begin at 1/1/2016, and auto-extend for the whole year if you like.
For GVIM, hit v
to go into visual mode; select text and hit Ctrl+Insert
to copy selection into global clipboard.
From the menu you can see that the shortcut key is "+y
i.e. hold Shift key, then press "
, then +
and then release Shift and press y
(cumbersome in comparison to Shift+Insert).
Update:
This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.
<a href="#" onclick="FB.logout();">Logout</a>
I have used the following in my project. you can try too.
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
if (ajax.status) {
if (ajax.status == 200 && (ajax.readyState == 4)){
//To do tasks if any, when upload is completed
}
}
}
ajax.upload.addEventListener("progress", function (event) {
var percent = (event.loaded / event.total) * 100;
//**percent** variable can be used for modifying the length of your progress bar.
console.log(percent);
});
ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
Hopefully it helps someone: I ran into this error and the cause was wrong permission on the log folder for phpfpm, after changing it so phpfpm could write to it, everything was fine.
Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.
public interface Mammal {
void move();
boolean possessIntelligence();
}
public interface Animal extends Mammal {
void liveInJungle();
}
public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
void liveInCivilization();
}
public interface Carnivore {
void eatMeat();
}
public interface Herbivore {
void eatPlant();
}
public interface Omnivore extends Carnivore, Herbivore {
void eatBothMeatAndPlant();
}
public interface FourLeggedMammal {
void moveWithFourLegs();
}
public interface TwoLeggedMammal {
void moveWithTwoLegs();
}
public interface Hunter {
void huntForFood();
}
public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
@Override
public void liveInJungle() {
System.out.println("I live in Outback country");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public void moveWithTwoLegs() {
System.out.println("I like to jump");
}
@Override
public void eat() {
eatPlant();
}
@Override
public void eatPlant() {
System.out.println("I like this grass");
}
@Override
public boolean possessIntelligence() {
return false;
}
}
public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
@Override
public void liveInJungle() {
System.out.println("I am king of the jungle!");
}
@Override
public void move() {
moveWithFourLegs();
}
@Override
public void moveWithFourLegs() {
System.out.println("I like to run sometimes.");
}
@Override
public void eat() {
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like deer meat");
}
@Override
public boolean possessIntelligence() {
return false;
}
@Override
public void huntForFood() {
System.out.println("My females hunt often");
}
}
public class Teacher implements Human {
@Override
public void liveInCivilization() {
System.out.println("I live in an apartment");
}
@Override
public void moveWithTwoLegs() {
System.out.println("I wear shoes and walk with two legs one in front of the other");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public boolean possessIntelligence() {
return true;
}
@Override
public void huntForFood() {
System.out.println("My ancestors used to but now I mostly rely on cattle");
}
@Override
public void eat() {
eatBothMeatAndPlant();
}
@Override
public void eatBothMeatAndPlant() {
eatPlant();
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like this bacon");
}
@Override
public void eatPlant() {
System.out.println("I like this broccoli");
}
}
Install pod sudo gem install cocoapods
Navigate inside platforms/ios cd platforms/ios
Run pod install
this worked nicely for me:
from csv import DictReader
f = requests.get('https://somedomain.com/file').content.decode('utf-8')
reader = DictReader(f.split('\n'))
csv_dict_list = list(reader)
var array3 = array1 === array2
That will compare whether array1 and array2 are the same array object in memory, which is not what you want.
In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.
Assuming your array is filled with primitives—numbers and or strings—something like this should do
function arraysAreIdentical(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++){
if (arr1[i] !== arr2[i]){
return false;
}
}
return true;
}
While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.
/* Set your parent color for the inherit property */
.sidebar {
color: green;
}
/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
color: inherit
}
.list-item a:hover {
color: inherit
}
/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
color: inherit !important;
}
Then your markup will be somewhat like:
<nav class="sidebar">
<ul>
<li class="list-item">
<a
href="/foo"
class="dynamic-hover-color"
style="color: #{{category.color}};"
>
Category
</a>
</li>
</ul>
</nav>
I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)
Android Studio can now show this. Go to Build
> Analyze APK...
and select your apk. Then you can see the content of the AndroidManifset file.
If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
Another option besides those above is:
df = df.groupby(df.columns, axis = 1).transform(lambda x: x.fillna(x.mean()))
It's less elegant than previous responses for mean, but it could be shorter if you desire to replace nulls by some other column function.
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
You can show float numbers
i.e.
$myNonFormatedFloat = 5678.9
$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90
$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90
Note that, the
1st argument is the float number you would like to format
2nd argument is the number of decimals
3rd argument is the character used to visually separate the decimals
4th argument is the character used to visually separate thousands
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
$_SERVER['HTTP_REFERER']
will give you incomplete url.
If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php
, $_SERVER['HTTP_REFERER']
will give you http://bawse.3owl.com/
only.
There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:
SELECT
t1.previous
,t1.present
,(t1.present - t1.previous) as difference
FROM #TEMP1 t1
Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx
There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
you should do it the other way round:
Load the mainform
first and in its onload
event show your loginform
with showdialog()
which will prevent mainform
from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform
(which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
In your CSS Style tag put this:
body {
background: url('yourgif.gif') no-repeat center center fixed;
background-size: cover;
}
Here is my other simple answer to accept only numbers in the text box using Regular Expressions.
onChanged(text){
this.setState({
myNumber: text.replace(/[^0-9]/g, '')
});
}
Here is an ES6 method chain using .map()
and .includes()
:
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
cat | git log --author="authorName" > author_commits_details.txt
This gives your commits in text format.
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
for those who land here, up to now FirebaseInstanceIdService
is deprecated now, use instead:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String token) {
Log.d("MY_TOKEN", "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
// sendRegistrationToServer(token);
}
}
and declare in AndroidManifest
<application... >
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
curl -u <username>:<password> https://$your_registry/v2/$image_name/tags/list -s -o - | \
tr -d '{' | tr -d '}' | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | \
awk -F: '{print $3}' | sed -e 's/,/\n/g'
You can use it if your env has no 'jq', = )
You can use this:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
A thing worth noting is that setting .State = EntityState.Deleted
does not trigger automatically detected change. (archive)
How i resolved this stage ?
just like that :
setTimeout((function(_deepFunction ,_deepData){
var _deepResultFunction = function _deepResultFunction(){
_deepFunction(_deepData);
};
return _deepResultFunction;
})(fromOuterFunction, fromOuterData ) , 1000 );
setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !
Maybe you can improve this part :
_deepFunction(_deepData);
// change to something like :
_deepFunction.apply(contextFromParams , args);
I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.
a sample test :
myDelay_function = function(fn , params , ctxt , _time){
setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
var _deepResultFunction = function _deepResultFunction(){
//_deepFunction(_deepData);
_deepFunction.call( _deepCtxt , _deepData);
};
return _deepResultFunction;
})(fn , params , ctxt)
, _time)
};
// the function to be used :
myFunc = function(param){ console.log(param + this.name) }
// note that we call this.name
// a context object :
myObjet = {
id : "myId" ,
name : "myName"
}
// setting a parmeter
myParamter = "I am the outer parameter : ";
//and now let's make the call :
myDelay_function(myFunc , myParamter , myObjet , 1000)
// this will produce this result on the console line :
// I am the outer parameter : myName
Maybe you can change the signature to make it more complient :
myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
var _deepResultFunction = function _deepResultFunction(){
//_deepFunction(_deepData);
_deepFunction.apply( _deepCtxt , _deepData);
};
return _deepResultFunction;
})(fn , params , ctxt)
, _time)
};
// and try again :
for(var i=0; i<10; i++){
myNass_setTimeOut(console.log ,1000 , [i] , console)
}
And finaly to answer the original question :
myNass_setTimeOut( postinsql, 4000, topicId );
Hope it can help !
ps : sorry but english it's not my mother tongue !
psql databasename < data_base_dump
That's the command you are looking for.
Beware: databasename
must be created before importing.
Have a look at the PostgreSQL Docs Chapter 23. Backup and Restore.
For people who use Bootstrap, textarea.form-control can lead to textarea sizing issues as well. Chrome and Firefox appear to use different heights with the following Bootstrap CSS:
textarea.form-conrtol{
height:auto;
}
You can specify how many times you want the previous item to match by using {min,max}
.
{[0-9]{1,3}:[0-9]{1,3}}
Also, you can use \d
for digits instead of [0-9]
for most regex flavors:
{\d{1,3}:\d{1,3}}
You may also want to consider escaping the outer {
and }
, just to make it clear that they are not part of a repetition definition.
Compatibility Supports Says that
Under compatibility level 110, the default style for CAST and CONVERT
operations on time
and datetime2
data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.
That means by default datetime2
is CAST as varchar
to 121 format
. For ex; col1
and col2
formats (below) are same (other than the 0s at the end)
SELECT CONVERT(varchar, GETDATE(), 121) col1,
CAST(convert(datetime2,GETDATE()) as varchar) col2,
CAST(GETDATE() as varchar) col3
--Results
COL1 | COL2 | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000 | Feb 8 2013 9:53AM
FYI, if you use CONVERT
instead of CAST
you can use a third parameter to specify certain formats as listed here on MSDN
All the primitive wrapper objects are immutable.
I'm maybe late to the question but I want to add and clarify that when you do playerID++
, what really happens is something like this:
playerID = Integer.valueOf( playerID.intValue() + 1);
Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.
Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for any name you ask from it; a List of the classes that implement that interface would then be infinite in length.
In practice, the most common case is an URLClassLoader
that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the URLClassLoader
, then iterate through those directories and archives, and for each class file you find in them, request the corresponding Class
object and look through the return of its getInterfaces()
method.
This works for me when I run into it:
sudo -u username psql
Have you considered using something like Quartz Scheduler? This library has a mechanism for scheduling tasks to run at a set period of time every day using a cron like expression (take a look at CronScheduleBuilder
).
Some example code (not tested):
public class GetDatabaseJob implements InterruptableJob
{
public void execute(JobExecutionContext arg0) throws JobExecutionException
{
getFromDatabase();
}
}
public class Example
{
public static void main(String[] args)
{
JobDetails job = JobBuilder.newJob(GetDatabaseJob.class);
// Schedule to run at 5 AM every day
ScheduleBuilder scheduleBuilder =
CronScheduleBuilder.cronSchedule("0 0 5 * * ?");
Trigger trigger = TriggerBuilder.newTrigger().
withSchedule(scheduleBuilder).build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(job, trigger);
scheduler.start();
}
}
There's a bit more work upfront, and you may need to rewrite your job execution code, but it should give you more control over how you want you job to run. Also it would be easier to change the schedule should you need to.
In order to select an element by attribute having a specific characteristic you may create a new selector like in the following snippet using a regex pattern. The usage of regex is intended to make flexible the new selector as much as possible:
jQuery.extend(jQuery.expr[':'], {
nameMatch: function (ele, idx, selector) {
var rpStr = (selector[3] || '').replace(/^\/(.*)\/$/, '$1');
return (new RegExp(rpStr)).test(ele.name);
}
});
//
// use of selector
//
$('input:nameMatch(/^pages_title\\[\\d\\]$/)').each(function(idx, ele) {
console.log(ele.outerHTML);
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
_x000D_
Another solution can be based on:
[name^=”value”]: selects elements that have the specified attribute with a value beginning exactly with a given string.
.filter(): reduce the set of matched elements to those that match the selector or pass the function's test.
var selectedEle = $(':input[name^="pages_title"]').filter(function(idx, ele) {
//
// test if the name attribute matches the pattern.....
//
return /^pages_title\[\d\]$/.test(ele.name);
});
selectedEle.each(function(idx, ele) {
console.log(ele.outerHTML);
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
_x000D_
If there are no performance gains using a join, then I prefer Common Table Expressions (CTEs) for readability:
WITH subquery AS (
SELECT address_id, customer, address, partn
FROM /* big hairy SQL */ ...
)
UPDATE dummy
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE dummy.address_id = subquery.address_id;
IMHO a bit more modern.
I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.
In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.
Copy your Fonts on the following directory JDK_HOME\jre\lib\fonts
Below code runs correctly.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
}
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
Here's a cleaned-up, non-eval-using version of Ram-swaroop's "works in all browsers" variety--works in all browsers!
function onReady(yourMethod) {
var readyStateCheckInterval = setInterval(function() {
if (document && document.readyState === 'complete') { // Or 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
// use like
onReady(function() { alert('hello'); } );
It does wait an extra 10 ms to run, however, so here's a more complicated way that shouldn't:
function onReady(yourMethod) {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
setTimeout(yourMethod, 1); // Schedule to run immediately
}
else {
readyStateCheckInterval = setInterval(function() {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
}
// Use like
onReady(function() { alert('hello'); } );
// Or
onReady(functionName);
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
I would advise against restricting the SecurityProtocol to TLS 1.1.
The recommended solution is to use
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls
Another option is add the following Registry key:
Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.
You don't need to set name , just giving an id is enough.
<input type="hidden" id="testId" />
and than with jquery you can use 'val()' method like below:
$('#testId').val("work");
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
Objective-C:
[label setFont: [label.font fontWithSize: sizeYouWant]];
Swift:
label.font = label.font.fontWithSize(sizeYouWant)
just changes font size of a UILabel.
The accepted answer didn't work for me for two reasons:
BackColor
set so setting AutoSize = false
and Dock = Fill
causes the background color to fill the whole formAutoSize
set to false anyway because my label text was dynamicInstead, I simply used the form's width and the width of the label to calculate the left offset:
MyLabel.Left = (this.Width - MyLabel.Width) / 2;
I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.
If your XML is in a string variable called txt
and looks like this:
<address>
<street>Roble Ave</street>
<mtfcc>S1400</mtfcc>
<streetNumber>649</streetNumber>
<lat>37.45127</lat>
<lng>-122.18032</lng>
<distance>0.04</distance>
<postalcode>94025</postalcode>
<placename>Menlo Park</placename>
<adminCode2>081</adminCode2>
<adminName2>San Mateo</adminName2>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<countryCode>US</countryCode>
</address>
Then you can parse the XML with Javascript DOM like this:
if (window.DOMParser)
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
And get specific values from the nodes like this:
//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;
//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;
//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:
NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
<s:street>Roble Ave</s:street>_x000D_
<sn:streetNumber>649</sn:streetNumber>_x000D_
<p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
parser = new DOMParser();_x000D_
xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
xmlDoc.async = false;_x000D_
xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.
The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.
HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.
UFH tags look similar to HF tags but have a read range of several feet.
Also HF tags come single read and multi read. UFH is exclusviely multi read.
Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.
But this is a function of the size of the antenna and how much power you can push through the reader.
As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.
The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.
Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.
You shouldn't need to know the index in most circumstances. You can do this:
my @arr = (1, 2, 3);
foreach (@arr) {
$_++;
}
print join(", ", @arr);
In this case, the output would be 2, 3, 4 as foreach sets an alias to the actual element, not just a copy.
Quick example using company1
from your question, with python3.
import pickle
# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))
However, as this answer noted, pickle often fails. So you should really use dill
.
import dill
# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))
The shortest in terms of lines of code i can think of is for the first question.
>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7],
[3, 4, 8],
[5, 6, 9]])
And the for the second question
p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0, 1, 3, 4],
[ 5, 6, 8, 9],
[15, 16, 18, 19]])
Select the commit you would like to roll back to and reverse the changes by clicking Reverse File
, Reverse Hunk
or Reverse Selected Lines
. Do this for all the commits after the commit you would like to roll back to also.
Right click on the commit and click on Reset current branch to this commit
.
the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.
in this example:
then you can add filters and orderby in the ng-reapet
!! list and datalist id must have the same name !!
<input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
<option ng-repeat="Ids in ctrl.dataList value={{Ids}} >
</datalist>
UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your input type="submit"
to input type="button"
and add data-toggle="modal" data-target="#confirm-submit"
so that the modal gets triggered when you click on it:
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
Next, the modal dialog:
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
Lastly, a little bit of jQuery:
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
You haven't specified what the function validateForm()
does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button #submitBtn
click and then load the modal after the validations have been checked.
Its not a good idea to pass Context
objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity
or Fragment
, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context
objects.
The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.
Example: We have a database table called User
with three columns – Name
, Age
and Address
. Assume that the User
table has thousands of rows.
Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:
SELECT * FROM User
WHERE Name = 'John'
The database software would literally have to look at every single row in the User
table to see if the Name
for that row is ‘John’. This will take a long time.
This is where index
helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.
How to create an index:
CREATE INDEX name_index
ON User (Name)
An index
consists of column values(Eg: John) from one table, and those values are stored in a data structure.
So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!
Solving in underscore
data = [];
_.times( highEnd, function( n ){ data.push( lowEnd ++ ) } );
Here is another possible solution, using the resolve
attribute of the $stateProvider
or the $routeProvider
. Example with $stateProvider
:
.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("forbidden", {
/* ... */
})
.state("signIn", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.isAnonymous(); }],
}
})
.state("home", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.isAuthenticated(); }],
}
})
.state("admin", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
}
});
}])
Access
resolves or rejects a promise depending on the current user rights:
.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {
var Access = {
OK: 200,
// "we don't know who you are, so we can't say if you're authorized to access
// this resource or not yet, please sign in first"
UNAUTHORIZED: 401,
// "we know who you are, and your profile does not allow you to access this resource"
FORBIDDEN: 403,
hasRole: function (role) {
return UserProfile.then(function (userProfile) {
if (userProfile.$hasRole(role)) {
return Access.OK;
} else if (userProfile.$isAnonymous()) {
return $q.reject(Access.UNAUTHORIZED);
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
hasAnyRole: function (roles) {
return UserProfile.then(function (userProfile) {
if (userProfile.$hasAnyRole(roles)) {
return Access.OK;
} else if (userProfile.$isAnonymous()) {
return $q.reject(Access.UNAUTHORIZED);
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
isAnonymous: function () {
return UserProfile.then(function (userProfile) {
if (userProfile.$isAnonymous()) {
return Access.OK;
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
isAuthenticated: function () {
return UserProfile.then(function (userProfile) {
if (userProfile.$isAuthenticated()) {
return Access.OK;
} else {
return $q.reject(Access.UNAUTHORIZED);
}
});
}
};
return Access;
}])
UserProfile
copies the current user properties, and implement the $hasRole
, $hasAnyRole
, $isAnonymous
and $isAuthenticated
methods logic (plus a $refresh
method, explained later):
.factory("UserProfile", ["Auth", function (Auth) {
var userProfile = {};
var clearUserProfile = function () {
for (var prop in userProfile) {
if (userProfile.hasOwnProperty(prop)) {
delete userProfile[prop];
}
}
};
var fetchUserProfile = function () {
return Auth.getProfile().then(function (response) {
clearUserProfile();
return angular.extend(userProfile, response.data, {
$refresh: fetchUserProfile,
$hasRole: function (role) {
return userProfile.roles.indexOf(role) >= 0;
},
$hasAnyRole: function (roles) {
return !!userProfile.roles.filter(function (role) {
return roles.indexOf(role) >= 0;
}).length;
},
$isAnonymous: function () {
return userProfile.anonymous;
},
$isAuthenticated: function () {
return !userProfile.anonymous;
}
});
});
};
return fetchUserProfile();
}])
Auth
is in charge of requesting the server, to know the user profile (linked to an access token attached to the request for example):
.service("Auth", ["$http", function ($http) {
this.getProfile = function () {
return $http.get("api/auth");
};
}])
The server is expected to return such a JSON object when requesting GET api/auth
:
{
"name": "John Doe", // plus any other user information
"roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
"anonymous": false // or true
}
Finally, when Access
rejects a promise, if using ui.router
, the $stateChangeError
event will be fired:
.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
switch (error) {
case Access.UNAUTHORIZED:
$state.go("signIn");
break;
case Access.FORBIDDEN:
$state.go("forbidden");
break;
default:
$log.warn("$stateChangeError event catched");
break;
}
});
}])
If using ngRoute
, the $routeChangeError
event will be fired:
.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
switch (rejection) {
case Access.UNAUTHORIZED:
$location.path("/signin");
break;
case Access.FORBIDDEN:
$location.path("/forbidden");
break;
default:
$log.warn("$stateChangeError event catched");
break;
}
});
}])
The user profile can also be accessed in the controllers:
.state("home", {
/* ... */
controller: "HomeController",
resolve: {
userProfile: "UserProfile"
}
})
UserProfile
then contains the properties returned by the server when requesting GET api/auth
:
.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {
$scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example
}])
UserProfile
needs to be refreshed when a user signs in or out, so that Access
can handle the routes with the new user profile. You can either reload the whole page, or call UserProfile.$refresh()
. Example when signing in:
.service("Auth", ["$http", function ($http) {
/* ... */
this.signIn = function (credentials) {
return $http.post("api/auth", credentials).then(function (response) {
// authentication succeeded, store the response access token somewhere (if any)
});
};
}])
.state("signIn", {
/* ... */
controller: "SignInController",
resolve: {
/* ... */
userProfile: "UserProfile"
}
})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {
$scope.signIn = function () {
Auth.signIn($scope.credentials).then(function () {
// user successfully authenticated, refresh UserProfile
return userProfile.$refresh();
}).then(function () {
// UserProfile is refreshed, redirect user somewhere
$state.go("home");
});
};
}])
Use stringi
package and stri_length
function
> stri_length(c("ala ma kota","ABC",NA))
[1] 11 3 NA
Why? Because it is the FASTEST among presented solutions :)
require(microbenchmark)
require(stringi)
require(stringr)
x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
microbenchmark(nchar(x),str_length(x),stri_length(x))
Unit: microseconds
expr min lq median uq max neval
nchar(x) 11.868 12.776 13.1590 13.6475 41.815 100
str_length(x) 30.715 33.159 33.6825 34.1360 173.400 100
stri_length(x) 2.653 3.281 4.0495 4.5380 19.966 100
and also works fine with NA's
nchar(NA)
## [1] 2
stri_length(NA)
## [1] NA
From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.
Expression. print()
behaves like a function in that you can do:
$ret = print "Hello World"
; And $ret
will be 1
. That means that print
can be used as part of a more complex expression where echo cannot. An
example from the PHP Manual:
$b ? print "true" : print "false";
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though. Only ,
AND
OR
XOR
are lower.
echo expression [, expression[,
expression] ... ]
But echo ( expression, expression )
is not valid.
This would be valid: echo ("howdy"),("partner")
; the same as: echo
"howdy","partner"
; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)So, echo without parentheses can take multiple parameters, which get concatenated:
echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
print()
can only take one parameter:
print ("and a 123");
print "and a 123";
Here is an example to add 8px Margin on left, top, right, bottom.
ImageView imageView = new ImageView(getApplicationContext());
ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
ViewGroup.MarginLayoutParams.MATCH_PARENT,
ViewGroup.MarginLayoutParams.WRAP_CONTENT
);
marginLayoutParams.setMargins(8, 8, 8, 8);
imageView.setLayoutParams(marginLayoutParams);
Here is the simplest thing i could think of. Note that this program uses second command line argument (argv[1])
as a line to delete whitespaces from.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*The function itself with debug printing to help you trace through it.*/
char* trim(const char* str)
{
char* res = malloc(sizeof(str) + 1);
char* copy = malloc(sizeof(str) + 1);
copy = strncpy(copy, str, strlen(str) + 1);
int index = 0;
for (int i = 0; i < strlen(copy) + 1; i++) {
if (copy[i] != ' ')
{
res[index] = copy[i];
index++;
}
printf("End of iteration %d\n", i);
printf("Here is the initial line: %s\n", copy);
printf("Here is the resulting line: %s\n", res);
printf("\n");
}
return res;
}
int main(int argc, char* argv[])
{
//trim function test
const char* line = argv[1];
printf("Here is the line: %s\n", line);
char* res = malloc(sizeof(line) + 1);
res = trim(line);
printf("\nAnd here is the formatted line: %s\n", res);
return 0;
}
Objects and arrays has a lot of built-in methods that can help you with processing data.
Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this
value lexically.
Object.keys()
, Object.values()
(ES 2017) and Object.entries()
(ES 2017)Object.keys()
returns an array of object's keys, Object.values()
returns an array of object's values, and Object.entries()
returns an array of object's keys and corresponding values in a format [key, value]
.
const obj = {_x000D_
a: 1_x000D_
,b: 2_x000D_
,c: 3_x000D_
}_x000D_
_x000D_
console.log(Object.keys(obj)) // ['a', 'b', 'c']_x000D_
console.log(Object.values(obj)) // [1, 2, 3]_x000D_
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
_x000D_
Object.entries()
with a for-of loop and destructuring assignmentconst obj = {_x000D_
a: 1_x000D_
,b: 2_x000D_
,c: 3_x000D_
}_x000D_
_x000D_
for (const [key, value] of Object.entries(obj)) {_x000D_
console.log(`key: ${key}, value: ${value}`)_x000D_
}
_x000D_
It's very convenient to iterate the result of Object.entries()
with a for-of loop and destructuring assignment.
For-of loop lets you iterate array elements. The syntax is for (const element of array)
(we can replace const
with var
or let
, but it's better to use const
if we don't intend to modify element
).
Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value]
means that instead of assigning the [key, value]
array to element
, we assign the first element of that array to key
and the second element to value
. It is equivalent to this:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
As you can see, destructuring makes this a lot simpler.
Array.prototype.every()
and Array.prototype.some()
The every()
method returns true
if the specified callback function returns true
for every element of the array. The some()
method returns true
if the specified callback function returns true
for some (at least one) element.
const arr = [1, 2, 3]_x000D_
_x000D_
// true, because every element is greater than 0_x000D_
console.log(arr.every(x => x > 0))_x000D_
// false, because 3^2 is greater than 5_x000D_
console.log(arr.every(x => Math.pow(x, 2) < 5))_x000D_
// true, because 2 is even (the remainder from dividing by 2 is 0)_x000D_
console.log(arr.some(x => x % 2 === 0))_x000D_
// false, because none of the elements is equal to 5_x000D_
console.log(arr.some(x => x === 5))
_x000D_
Array.prototype.find()
and Array.prototype.filter()
The find()
methods returns the first element which satisfies the provided callback function. The filter()
method returns an array of all elements which satisfies the provided callback function.
const arr = [1, 2, 3]_x000D_
_x000D_
// 2, because 2^2 !== 2_x000D_
console.log(arr.find(x => x !== Math.pow(x, 2)))_x000D_
// 1, because it's the first element_x000D_
console.log(arr.find(x => true))_x000D_
// undefined, because none of the elements equals 7_x000D_
console.log(arr.find(x => x === 7))_x000D_
_x000D_
// [2, 3], because these elements are greater than 1_x000D_
console.log(arr.filter(x => x > 1))_x000D_
// [1, 2, 3], because the function returns true for all elements_x000D_
console.log(arr.filter(x => true))_x000D_
// [], because none of the elements equals neither 6 nor 7_x000D_
console.log(arr.filter(x => x === 6 || x === 7))
_x000D_
Array.prototype.map()
The map()
method returns an array with the results of calling a provided callback function on the array elements.
const arr = [1, 2, 3]_x000D_
_x000D_
console.log(arr.map(x => x + 1)) // [2, 3, 4]_x000D_
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']_x000D_
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)_x000D_
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]_x000D_
console.log(arr.map(String)) // ['1', '2', '3']
_x000D_
Array.prototype.reduce()
The reduce()
method reduces an array to a single value by calling the provided callback function with two elements.
const arr = [1, 2, 3]_x000D_
_x000D_
// Sum of array elements._x000D_
console.log(arr.reduce((a, b) => a + b)) // 6_x000D_
// The largest number in the array._x000D_
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
_x000D_
The reduce()
method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce()
can has zero or one elements. For example, if we wanted to create a function sum()
which takes an array as an argument and returns the sum of all elements, we could write it like that:
const sum = arr => arr.reduce((a, b) => a + b, 0)_x000D_
_x000D_
console.log(sum([])) // 0_x000D_
console.log(sum([4])) // 4_x000D_
console.log(sum([2, 5])) // 7
_x000D_
-XX:MaxPermSize=size
Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize
option.
-XX:PermSize=size
Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize
option.
In addition to the other answers using HTML (either in Markdown or using the %%HTML
magic:
If you need to specify the image height, this will not work:
<img src="image.png" height=50> <-- will not work
That is because the CSS styling in Jupyter uses height: auto
per default for the img
tags, which overrides the HTML height attribute. You need need to overwrite the CSS height
attribute instead:
<img src="image.png" style="height:50px"> <-- works
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
Try using setAttribute
instead:
document.getElementById('img')
.setAttribute(
'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);
Real answer: (And make sure you remove the line-breaks in the base64.)
In Bootstrap 4 the correct answer is to use the text-xs-right
class.
This works because xs
denotes the smallest viewport size in BS. If you wanted to, you could apply the alignment only when the viewport is medium or larger by using text-md-right
.
In the latest alpha, text-xs-right
has been simplified to text-right
.
<div class="row">
<div class="col-md-6">Total cost</div>
<div class="col-md-6 text-right">$42</div>
</div>
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
This solved it for me: I supplied a third argument being an object.
in app.js
(working with laravel and webpack):
Vue.component('news-item', require('./components/NewsItem.vue'), {
name: 'news-item'
});
There's a special function n()
in dplyr to count rows (potentially within groups):
library(dplyr)
mtcars %>%
group_by(cyl, gear) %>%
summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
But dplyr also offers a handy count
function which does exactly the same with less typing:
count(mtcars, cyl, gear) # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
You specify the escape character. Documentation here:
http://msdn.microsoft.com/en-us/library/ms179859.aspx
The numpy_indexed package (disclaimer: I am its author) contains functionality to efficiently perform operations of this type:
import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))
This is essentially the same solution as the one I posted earlier; but now wrapped in a nice interface, with tests and all :)
For me, I would write an extension method like this:
public static string[] GetFieldNames(this SqlDataReader reader)
{
return Enumerable.Range(0, reader.FieldCount).Select(x => reader.GetName(x)).ToArray();
}
$('#txtConfirmPassword').keyup(function(){
if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
alert('confirm password not match');
}
});
Yes, you can:
l = L[1::2]
And this is all. The result will contain the elements placed on the following positions (0
-based, so first element is at position 0
, second at 1
etc.):
1, 3, 5
so the result (actual numbers) will be:
2, 4, 6
The [1::2]
at the end is just a notation for list slicing. Usually it is in the following form:
some_list[start:stop:step]
If we omitted start
, the default (0
) would be used. So the first element (at position 0
, because the indexes are 0
-based) would be selected. In this case the second element will be selected.
Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated from the second element to the end.
We also provided third argument (step
) which is 2
. Which means that one element will be selected, the next will be skipped, and so on...
So, to sum up, in this case [1::2]
means:
step=2
, so we are skipping one, as a contrary to step=1
which is default),EDIT: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: Explain Python's slice notation
enumerate()
In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using enumerate()
:
for count, i in enumerate(L):
if count % 2 == 1:
l.append(i)
The above serves exactly the same purpose as the code you were using:
count = 0
for i in L:
if count % 2 == 1:
l.append(i)
count += 1
More on emulating for
loops with counter in Python: Accessing the index in Python 'for' loops
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
Take attention with the parentheses !
Filter using wildcards:
Get-ChildItem -Filter CopyForBuild* -Include *.bat,*.cmd -Exclude *.old.cmd,*.old.bat -Recurse
Filtering using a regular expression:
Get-ChildItem -Path "V:\Myfolder" -Recurse
| Where-Object { $_.Name -match '\ACopyForBuild\.[(bat)|(cmd)]\Z' }
In my case, it was an accidental double escaping.
this works:
SelectedPath = @"C:\Program Files\My Company\My product";
this doesn't:
SelectedPath = @"C:\\Program Files\\My Company\\My product";
I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.
protected void Page_Load(object sender, EventArgs e)
Calendar1.SelectedDate = DateTime.Today;
}
the previous code did NOT highlight the selection, although it set the SelectedDate to today.
However, to select and highlight the following code will work properly.
protected void Page_Load(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
Calendar1.TodaysDate = today;
Calendar1.SelectedDate = Calendar1.TodaysDate;
}
check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Good news everyone, there's an isBetween
function!
Update your library ;)
I had the same problem some time ago and was disappointed because I couldn't find any solution that suites my needs so I wrote my own class. Honestly, I did found some code back then, but even that wasn't what I was searching for so I adapted it and now I'm sharing it, just like the author of that piece of code did.
EDIT: This is the original (although slightly different) code: CircularArrayList for java
I don't have the link of the source because it was time ago, but here's the code:
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
public class CircularArrayList<E> extends AbstractList<E> implements RandomAccess {
private final int n; // buffer length
private final List<E> buf; // a List implementing RandomAccess
private int leader = 0;
private int size = 0;
public CircularArrayList(int capacity) {
n = capacity + 1;
buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}
public int capacity() {
return n - 1;
}
private int wrapIndex(int i) {
int m = i % n;
if (m < 0) { // modulus can be negative
m += n;
}
return m;
}
@Override
public int size() {
return this.size;
}
@Override
public E get(int i) {
if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException();
if(i > size()) throw new NullPointerException("Index is greater than size.");
return buf.get(wrapIndex(leader + i));
}
@Override
public E set(int i, E e) {
if (i < 0 || i >= n-1) {
throw new IndexOutOfBoundsException();
}
if(i == size()) // assume leader's position as invalid (should use insert(e))
throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i
+". Please use insert(e) method to fill the list.");
return buf.set(wrapIndex(leader - size + i), e);
}
public void insert(E e)
{
int s = size();
buf.set(wrapIndex(leader), e);
leader = wrapIndex(++leader);
buf.set(leader, null);
if(s == n-1)
return; // we have replaced the eldest element.
this.size++;
}
@Override
public void clear()
{
int cnt = wrapIndex(leader-size());
for(; cnt != leader; cnt = wrapIndex(++cnt))
this.buf.set(cnt, null);
this.size = 0;
}
public E removeOldest() {
int i = wrapIndex(leader+1);
for(;;i = wrapIndex(++i)) {
if(buf.get(i) != null) break;
if(i == leader)
throw new IllegalStateException("Cannot remove element."
+ " CircularArrayList is empty.");
}
this.size--;
return buf.set(i, null);
}
@Override
public String toString()
{
int i = wrapIndex(leader - size());
StringBuilder str = new StringBuilder(size());
for(; i != leader; i = wrapIndex(++i)){
str.append(buf.get(i));
}
return str.toString();
}
public E getOldest(){
int i = wrapIndex(leader+1);
for(;;i = wrapIndex(++i)) {
if(buf.get(i) != null) break;
if(i == leader)
throw new IllegalStateException("Cannot remove element."
+ " CircularArrayList is empty.");
}
return buf.get(i);
}
public E getNewest(){
int i = wrapIndex(leader-1);
if(buf.get(i) == null)
throw new IndexOutOfBoundsException("Error while retrieving the newest element. The Circular Array list is empty.");
return buf.get(i);
}
}
You need to add the port number to every address you type in your browser when you have changed the default port from port 80.
For example: localhost:8000/cc .
A little edition here is that it should be 8080 in place of 8000. For example - http://localhost:8080/phpmyadmin/
x^y
is not "x
to the power of y
". It's "x
XOR y
".
Add this dependency:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.28</version>
</dependency>
cf. https://stackoverflow.com/a/44536542/1070215
Make sure not to mix your Jersey dependency versions. This answer says version "2.28", but use whatever version your other Jersey dependency versions are.
here is the best way:
on this way you have only one css with all shared code and an html page. by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
in Mono Android you can use filter like this:
your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = findViewById(R.id.button);
spinner = findViewById(R.id.sp_item);
setInfo();
spinnerAdapter = new SpinnerAdapter(this, arrayList);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//first, we have to retrieve the item position as a string
// then, we can change string value into integer
String item_position = String.valueOf(position);
int positonInt = Integer.valueOf(item_position);
Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
note: the position of items is counted from 0.
http://en.wikipedia.org/wiki/Euclidean_distance
If you have the coordinates, use the formula to calculate the distance:
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
If your platform supports the **
operator, you can instead use that:
const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
This statement will remove and update the field content of your database
To remove whitespaces in the left side of the field value
UPDATE table SET field1 = LTRIM(field1);
ex. UPDATE member SET firstName = LTRIM(firstName);
To remove whitespaces in the right side of the field value
UPDATE table SETfield1 = RTRIM(field1);
ex. UPDATE member SET firstName = RTRIM(firstName);
At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
System.out.println(inputStr); // display the original file for debugging
// logic to replace lines in the string (could use regex here to be generic)
if (type.equals("0")) {
inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");
} else if (type.equals("1")) {
inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
}
// display the new file for debugging
System.out.println("----------------------------------\n" + inputStr);
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then call it:
public static void main(String[] args) {
replaceSelected("Do the dishes", "1");
}
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1
New text file content:
Do the dishes1
Feed the dog0
Cleaned my room1
And as a note, if the text file was:
Do the dishes1
Feed the dog0
Cleaned my room1
and you used the method replaceSelected("Do the dishes", "1");
,
it would just not change the file.
Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).
// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
try {
// input the (modified) file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = ... // replace the line here
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Reloading the NIB is expensive. Better to load it once, then instantiate the objects when you need a cell. Note that you can add UIImageViews etc to the nib, even multiple cells, using this method (Apple's "registerNIB" iOS5 allows only one top level object - Bug 10580062 "iOS5 tableView registerNib: overly restrictive"
So my code is below - you read in the NIB once (in initialize like I did or in viewDidload - whatever. From then on, you instantiate the nib into objects then pick the one you need. This is much more efficient than loading the nib over and over.
static UINib *cellNib;
+ (void)initialize
{
if(self == [ImageManager class]) {
cellNib = [UINib nibWithNibName:@"ImageManagerCell" bundle:nil];
assert(cellNib);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"TheCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if(cell == nil) {
NSArray *topLevelItems = [cellNib instantiateWithOwner:nil options:nil];
NSUInteger idx = [topLevelItems indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
{
UITableViewCell *cell = (UITableViewCell *)obj;
return [cell isKindOfClass:[UITableViewCell class]] && [cell.reuseIdentifier isEqualToString:cellID];
} ];
assert(idx != NSNotFound);
cell = [topLevelItems objectAtIndex:idx];
}
cell.textLabel.text = [NSString stringWithFormat:@"Howdie %d", indexPath.row];
return cell;
}
Try the following:
=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)
To get the latest images use docker-compose build --pull
I use below command which is really 3 in 1
docker-compose down && docker-compose build --pull && docker-compose up -d
This command will stop the services, pulls the latest image and then starts the services.
The CSS specification requires that position:fixed
be anchored to the viewport, not the containing positioned element.
If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.
ALTERNATIVE: Some browsers have sticky
CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:
sticky
... constrains an element to be positioned inside the intersection of its container box, and the viewport.A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.
Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky
still needs a -webkit
prefix in Safari.
See caniuse for up-to-date stats on browser support.
an alternative answer is the judicious use of tables and rowspan. by setting all table cells on the preceeding line (except the main content one) to be rowspan="2" you will always get a one cell hole at the bottom of your main table cell that you can always put valign="bottom".
You can also set its height to be the minimum you need for one line. Thus you will always get your favourite line of text at the bottom regardless of how much space the rest of the text takes up.
I tried all the div answers, I was unable to get them to do what I needed.
<table>
<tr>
<td valign="top">
this is just some random text
<br> that should be a couple of lines long and
<br> is at the top of where we need the bottom tag line
</td>
<td rowspan="2">
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
this<br/>
is really<br/>
tall
</td>
</tr>
<tr>
<td valign="bottom">
now this is the tagline we need on the bottom
</td>
</tr>
</table>
You can also keep adding strings to an existing string like so:
var myString = "Hello ";
myString += "World";
myString += "!";
the result would be -> Hello World!
You can use gnu objdump. objdump -p your.dll
. Then pan to the .edata
section contents and you'll find the exported functions under [Ordinal/Name Pointer] Table
.
ArrayList is a Collection of elements (in the form of list), primitive are stored as wrapper class object but at the same time i can store objects of String class as well. SUM will not make sense in that. BTW why are so afraid to use for loop (enhanced or through iterator) anyways?
If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.
if you want to compute differences between two known dates, use total_seconds
like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0
#note that seconds doesn't give you what you want:
(b-a).seconds
0
The file extension .img
does not say anything about its content.
Most commonly .img files are a floppy/CD/DVD/ISO image, a filesystem image, a disk image, or even just (custom) binary data.
In case it is an CD/DVD image or a specific filesystem image (like fat, ntfs, ...) you can open these files with 7-Zip.
On *nix based systems also the file
tool or (libmagic) could help you find out what it is.
You could also put: (load_essentials.js:)
document.getElementById("myHead").innerHTML =_x000D_
"<span id='headerText'>Title</span>"_x000D_
+ "<span id='headerSubtext'>Subtitle</span>";_x000D_
document.getElementById("myNav").innerHTML =_x000D_
"<ul id='navLinks'>"_x000D_
+ "<li><a href='index.html'>Home</a></li>"_x000D_
+ "<li><a href='about.html'>About</a>"_x000D_
+ "<li><a href='donate.html'>Donate</a></li>"_x000D_
+ "</ul>";_x000D_
document.getElementById("myFooter").innerHTML =_x000D_
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"_x000D_
+ " rights reserved.</p>"_x000D_
+ "<p id='credits'>Layout by You</p>"_x000D_
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "_x000D_
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";
_x000D_
<!--HTML-->_x000D_
<header id="myHead"></header>_x000D_
<nav id="myNav"></nav>_x000D_
Content_x000D_
<footer id="myFooter"></footer>_x000D_
_x000D_
<script src="load_essentials.js"></script>
_x000D_
public void TryThreeTimes(Action action)
{
var tries = 3;
while (true) {
try {
action();
break; // success!
} catch {
if (--tries == 0)
throw;
Thread.Sleep(1000);
}
}
}
Then you would call:
TryThreeTimes(DoSomething);
...or alternatively...
TryThreeTimes(() => DoSomethingElse(withLocalVariable));
A more flexible option:
public void DoWithRetry(Action action, TimeSpan sleepPeriod, int tryCount = 3)
{
if (tryCount <= 0)
throw new ArgumentOutOfRangeException(nameof(tryCount));
while (true) {
try {
action();
break; // success!
} catch {
if (--tryCount == 0)
throw;
Thread.Sleep(sleepPeriod);
}
}
}
To be used as:
DoWithRetry(DoSomething, TimeSpan.FromSeconds(2), tryCount: 10);
A more modern version with support for async/await:
public async Task DoWithRetryAsync(Func<Task> action, TimeSpan sleepPeriod, int tryCount = 3)
{
if (tryCount <= 0)
throw new ArgumentOutOfRangeException(nameof(tryCount));
while (true) {
try {
await action();
return; // success!
} catch {
if (--tryCount == 0)
throw;
await Task.Delay(sleepPeriod);
}
}
}
To be used as:
await DoWithRetryAsync(DoSomethingAsync, TimeSpan.FromSeconds(2), tryCount: 10);
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
Pre-append your commands with sudo
.
For example, Instead of vim textfile.txt
, used sudo vim textfile.txt
. This will resolve the issue.
If you are using RichTextBox control. You can simply define the ToolTip object and show the tool-tip as the text is selected by moving the mouse inside the RichTextBox control.
ToolTip m_ttInput = new ToolTip(); // define as member variable
private void rtbInput_SelectionChanged(object sender, EventArgs e)
{
if (rtbInput.SelectedText.Length > 0)
{
m_ttInput.Show(rtbInput.SelectedText.Length.ToString(), rtbInput, 1000);
}
}
Although it's not listed on the API doc page anymore, I found a thread that mentions that you can use self
in place of user-id
for the users/{user-id}
endpoint and it'll return the currently authenticated user's info.
So, users/self
is the same as an explicit call to users/{some-user-id}
and contains the user's id as part of the payload. Once you're authenticated, just make a call to users/self
and the result will include the currently authenticated user's id, like so:
{
"data": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://snoopdogg.com",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}
This is much simple way to do it.
Have a private int selectedPos = RecyclerView.NO_POSITION;
in the RecyclerView Adapter class, and under onBindViewHolder method try:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.itemView.setSelected(selectedPos == position);
}
And in your OnClick event modify:
@Override
public void onClick(View view) {
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
Works like a charm for Navigtional Drawer and other RecyclerView Item Adapters.
Note: Be sure to use a background color in your layout using a selector like colabug clarified:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/pressed_color" android:state_pressed="true"/>
<item android:drawable="@color/selected_color" android:state_selected="true"/>
<item android:drawable="@color/focused_color" android:state_focused="true"/>
</selector>
Otherwise setSelected(..) will do nothing, rendering this solution useless.
If the database are in the same server use [DatabaseName].[Owner].[TableName]
format when accessing a table that resides in a different database.
Eg: [DB1].[dbo].[TableName]
If databases in different server look at on Creating Linked Servers (SQL Server Database Engine)
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:
CATALINA_OPTS='-Xms512m -Xmx1024m'
My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.
Just do String str = System.out.printf("%.2f", val).replace(",", ".");
if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion like float f = Float.parseFloat(str);
Split your date into year, month, and day components then use Date:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Date will take care of fixing the year.
What you can do is select everything into a new instance of Course, and afterwards convert them to a List.
var qry = from a in obj.tbCourses
select new Course() {
Course.Property = a.Property
...
};
qry.toList<Course>();
sys_guid() is a poor option, as other answers have mentioned. One way to generate UUIDs and avoid sequential values is to generate random hex strings yourself:
select regexp_replace(
to_char(
DBMS_RANDOM.value(0, power(2, 128)-1),
'FM0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'),
'([a-f0-9]{8})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{12})',
'\1-\2-\3-\4-\5') from DUAL;
I'm up to the latest as of today and found the best way to resolve this is to do nothing...no typeRoots
no types
no exclude
no include
all the defaults seem to be working just fine. Actually it didn't work right for me until I removed them all. I had:
"exclude": [
"node_modules"
]
but that's in the defaults so I removed that.
I had:
"types": [
"node"
]
to get past some compiler warning. But now I removed that too.
The warning that shouldn't be is:
error TS2304: Cannot find name 'AsyncIterable'.
from node_modules\@types\graphql\subscription\subscribe.d.ts
which is very obnoxious so I did this in tsconfig so that it loads it:
"compilerOptions": {
"target": "esnext",
}
since it's in the esnext set. I'm not using it directly so no worries here about compatibility just yet. Hope that doesn't burn me later.
Use the PHP nl2br to get the newlines in a text string..
$text = "Manu is a good boy.(Enter)He can code well.
echo nl2br($text);
Result.
Manu is a good boy.
He can code well.
You need to encode your parameter's values before concatenating them to URL.
Backslash \
is special character which have to be escaped as %5C
Escaping example:
String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);
The result is http://host.com?param=param%5Cwith%5Cbackslash
which is properly formatted url string.
WHERE
MyColumn LIKE '%,' + @search + ',%' --middle
OR
MyColumn LIKE @search + ',%' --start
OR
MyColumn LIKE '%,' + @search --end
OR
MyColumn = @search --single (good point by Cheran S in comment)
As @AlexanderN pointed out, you can now delete App IDs.
I had the same issue, and it turned out to be due to permission of the catalina.out
file not being correct. It was not writable by the tomcat user. Once I fixed the permissions, the issue got resolved. I got to know that it is a permissions issue from the logs in the tomcat8-initd.log
file:
/usr/sbin/tomcat8: line 40: /usr/share/tomcat8/logs/catalina.out: Permission denied
Answers given above are perfect but I suggest to use multiple smaller regex rather than a big one.
Splitting the long regex have some advantages:
Generally this approach keep code easily maintainable.
Having said that, I share a piece of code that I write in Swift as example:
struct RegExp {
/**
Check password complexity
- parameter password: password to test
- parameter length: password min length
- parameter patternsToEscape: patterns that password must not contains
- parameter caseSensitivty: specify if password must conforms case sensitivity or not
- parameter numericDigits: specify if password must conforms contains numeric digits or not
- returns: boolean that describes if password is valid or not
*/
static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
if (password.length < length) {
return false
}
if caseSensitivty {
let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
if !hasUpperCase {
return false
}
let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
if !hasLowerCase {
return false
}
}
if numericDigits {
let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
if !hasNumbers {
return false
}
}
if patternsToEscape.count > 0 {
let passwordLowerCase = password.lowercaseString
for pattern in patternsToEscape {
let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
if hasMatchesWithPattern {
return false
}
}
}
return true
}
static func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
To inspect files, run docker run -it <image> /bin/sh
to get an interactive terminal. The list of images can be obtained by docker images
. In contrary to docker exec
this solution works also in case when an image doesn't start (or quits immediately after running).
One another way is just to duplicate only the "Eclipse.app" file instead of making multiple copies of entire eclipse directory. Right-Click on the "Eclipse.app" file and click the duplicate option to create a duplicate.
Please refer JPA : How to convert a native query result set to POJO class collection
For Postgres 9.4
,
List<String> list = em.createNativeQuery("select cast(row_to_json(u) as text) from myschema.USER_ u WHERE ID = ?")
.setParameter(1, id).getResultList();
User map = new ObjectMapper().readValue(list.get(0), User.class);
You must specify the full path of the resource file as the name of 'image within the resources of your application, see example below.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = My.Resources.Chrysanthemum
End Sub
In the path assigned to the Image property after MyResources specify the name of the resource.
But before you do whatever you have to import in the resource section of your application from an image file exists or it can create your own.
Bye
You need to close the XML with </web-app>
, not with <web-app>
.
Add this line with your EditText tag.
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Your EditText tag should look like:
<EditText
android:id="@+id/editText1"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
If you have a custom.css
file, in there, just do something like:
font-family: "Oswald", Helvetica, Arial, sans-serif!important;
If you want to use something other than a shell script, try CLOC:
cloc counts blank lines, comment lines, and physical lines of source code in many programming languages. It is written entirely in Perl with no dependencies outside the standard distribution of Perl v5.6 and higher (code from some external modules is embedded within cloc) and so is quite portable.
If you're looking for the current and the latest versions of all your installed packages, you can also use:
npm outdated
Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
padding: 2em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
background: none;_x000D_
border: 4px solid #fff;_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
left: 4px;_x000D_
right: 4px;_x000D_
bottom: 4px;_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow
declarations (separated by commas) to do so:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
box-shadow:_x000D_
inset 0 0 0 4px #eee,_x000D_
inset 0 0 0 8px #ddd,_x000D_
inset 0 0 0 12px #ccc,_x000D_
inset 0 0 0 16px #bbb,_x000D_
inset 0 0 0 20px #aaa,_x000D_
inset 0 0 0 20px #999,_x000D_
inset 0 0 0 20px #888;_x000D_
/* And so on and so forth, if you want border-ception */_x000D_
margin: 0 auto;_x000D_
padding: 3em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
You have to give the dictionary a type
// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()
If the compiler can infer the type, you can use the shorter syntax
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
Besides using one of the default formats you can specify any size you want in the unit you specify.
For example:
// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);
The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).
Your 1st parameter (landscape
or portrait
) determines what becomes the width and the height.
In the sourcecode on GitHub you can see the supported units (relative proportions to pt
), and you can also see the default page formats (with their sizes in pt
).
"I need to install it to the folder of my C program." Why?
Include usb.h:
#include <usb.h>
and remember to add -lusb to gcc:
gcc -o example example.c -lusb
This work fine for me.
If you want to grant remote access of your database from any IP address, run the mysql command and after that run the following command.
GRANT ALL PRIVILEGES ON *.*
TO 'root'@'%'
IDENTIFIED BY 'password'
WITH GRANT OPTION;
For each series in the dataframe, you could use between
and quantile
to remove outliers.
x = pd.Series(np.random.normal(size=200)) # with outliers
x = x[x.between(x.quantile(.25), x.quantile(.75))] # without outliers
We can achieve it as below, it will skip even numbers
local len = 5
for i = 1, len do
repeat
if i%2 == 0 then break end
print(" i = "..i)
break
until true
end
O/P:
i = 1
i = 3
i = 5
Use this, but it's a complete solution:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
If you're using .NET 4.5 and want to use async then you can use HttpClient
in System.Net.Http
:
using (var httpClient = new HttpClient())
{
var json = await httpClient.GetStringAsync("url");
// Now parse with JSON.Net
}
if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile
require 'pull_tempfile'
PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
CSV.foreach(tmp_file.path) do |row|
# ....
end
end
If you do <form action="identification" >
for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post">
and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........
const log = chrome.extension.getBackgroundPage().console.log;
log('something')
Open log: