Simple:
if ( $name eq 'tom' && $password eq '123!'
|| $name eq 'frank' && $password eq '321!'
) {
(use the high-precedence &&
and ||
in expressions, reserving and
and or
for flow control, to avoid common precedence errors)
Better:
my %password = (
'tom' => '123!',
'frank' => '321!',
);
if ( exists $password{$name} && $password eq $password{$name} ) {
The reason I like Rcpp so much is that I don't always get how R Core thinks, and with Rcpp, more often than not, I don't have to.
Speaking philosophically, you're in a state of sin with regards to the functional paradigm, which tries to ensure that every value appears independent of every other value; changing one value should never cause a visible change in another value, the way you get with pointers sharing representation in C.
The problems arise when functional programming signals the small craft to move out of the way, and the small craft replies "I'm a lighthouse". Making a long series of small changes to a large object which you want to process on in the meantime puts you square into lighthouse territory.
In the C++ STL, push_back()
is a way of life. It doesn't try to be functional, but it does try to accommodate common programming idioms efficiently.
With some cleverness behind the scenes, you can sometimes arrange to have one foot in each world. Snapshot based file systems are a good example (which evolved from concepts such as union mounts, which also ply both sides).
If R Core wanted to do this, underlying vector storage could function like a union mount. One reference to the vector storage might be valid for subscripts 1:N
, while another reference to the same storage is valid for subscripts 1:(N+1)
. There could be reserved storage not yet validly referenced by anything but convenient for a quick push_back()
. You don't violate the functional concept when appending outside the range that any existing reference considers valid.
Eventually appending rows incrementally, you run out of reserved storage. You'll need to create new copies of everything, with the storage multiplied by some increment. The STL implementations I've use tend to multiply storage by 2 when extending allocation. I thought I read in R Internals that there is a memory structure where the storage increments by 20%. Either way, growth operations occur with logarithmic frequency relative to the total number of elements appended. On an amortized basis, this is usually acceptable.
As tricks behind the scenes go, I've seen worse. Every time you push_back()
a new row onto the dataframe, a top level index structure would need to be copied. The new row could append onto shared representation without impacting any old functional values. I don't even think it would complicate the garbage collector much; since I'm not proposing push_front()
all references are prefix references to the front of the allocated vector storage.
Personally, for me, the best solution for a similar issue was:
HTML
<input type="radio" name="selectAll" value="true" />
<input type="radio" name="selectAll" value="false" />
JQuery
var $selectAll = $( "input:radio[name=selectAll]" );
$selectAll.on( "change", function() {
console.log( "selectAll: " + $(this).val() );
// or
alert( "selectAll: " + $(this).val() );
});
*The event "click" can work in place of "change" as well.
Hope this helps!
pop'n'fresh
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>
I was struggling with that until i found this...
Also, if you open the Properties window you may find some magical "Connection elapsed time" that may give you some execution time... Hope it helps...
"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".
So, try to change the code to:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws Exception {
String startDateString = "06/27/2007";
// This object can interpret strings representing dates in the format MM/dd/yyyy
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Convert from String to Date
Date startDate = df.parse(startDateString);
// Print the date, with the default formatting.
// Here, the important thing to note is that the parts of the date
// were correctly interpreted, such as day, month, year etc.
System.out.println("Date, with the default formatting: " + startDate);
// Once converted to a Date object, you can convert
// back to a String using any desired format.
String startDateString1 = df.format(startDate);
System.out.println("Date in format MM/dd/yyyy: " + startDateString1);
// Converting to String again, using an alternative format
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String startDateString2 = df2.format(startDate);
System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
}
}
Output:
Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007
One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL
statement:
UDF Example:
CREATE FUNCTION hello (s CHAR(20))
RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)
CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');
SELECT hello(name) FROM names;
+--------------+
| hello(name) |
+--------------+
| Hello, Bob! |
| Hello, John! |
| Hello, Paul! |
+--------------+
3 rows in set (0.00 sec)
Sproc Example:
delimiter //
CREATE PROCEDURE simpleproc (IN s CHAR(100))
BEGIN
SELECT CONCAT('Hello, ', s, '!');
END//
Query OK, 0 rows affected (0.00 sec)
delimiter ;
CALL simpleproc('World');
+---------------------------+
| CONCAT('Hello, ', s, '!') |
+---------------------------+
| Hello, World! |
+---------------------------+
1 row in set (0.00 sec)
Personally, I've found Apache's HttpClient to be more than capable of everything I've needed to do with regards to this. Here is a great tutorial on using HttpClient
Slightly unrelated to your problem, so here's one for Google.
If you didn't mysqldump the SQL, it might be that your SQL is broken.
I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.
That's a fantastic error message to get for a runaway string, thanks for that MySQL!
You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.
A data frame is a list. When you subset a data frame using the name of a column and [
, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[
, or somewhat confusingly (to me) you could do aframe[,2]
which returns a vector, not a sublist.
So try running this sequence and maybe things will be clearer:
avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
You can simply fetch the remote repo with:
git fetch <repo>
where,
<repo>
can be a remote repo name (e.g. origin
) or even a remote repo URL (e.g. https://git.foo.com/myrepo.git
)for example:
git fetch https://git.foo.com/myrepo.git
after you fetched the repos you may merge the commits that you want (since the question is about retrieve one commit, instead merge you may use cherry-pick to pick just one commit):
git merge <commit>
<commit>
can be the SHA1 commitfor example:
git cherry-pick 0a071603d87e0b89738599c160583a19a6d95545
or
git merge 0a071603d87e0b89738599c160583a19a6d95545
if is the latest commit that you want to merge, you also may use FETCH_HEAD variable :
git cherry-pick (or merge) FETCH_HEAD
For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):
export class MyComponent implements OnInit {
constructor(private el: ElementRef) {}
ngOnInit() {
//This is the important line you can use in your function in the code
//--------------------------------------------------------------------------
let offset = this.el.nativeElement.getBoundingClientRect().top;
//--------------------------------------------------------------------------
console.log(offset);
}
}
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub
If you handle the draw.dt event after page.dt, you can detect exactly after moving the page. After work, draw.dt must be unbind
$(document).on("page.dt", () => {
$(document).on("draw.dt", changePage);
});
const changePage = () => {
// TODO
$(document).unbind("draw.dt", changePage);
}
Each commit has a unique hash. Other than that there are no revision numbers in git. You'll have to tag commits yourself if you want more user-friendliness.
Try to use transparent attribute value for making transparent background color.
backgroundColor: 'transparent'
There are multiple ways of doing that you can use either place
or grid
or even the pack
method.
Sample code:
from tkinter import *
root = Tk()
l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.
To place a widget to on basis of columns and rows , use the grid method:
but = Button(root, text="hello" )
but.grid(row=0, column=1)
One approach not yet given is to use a parser generator to create a parser in XSLT which parses JSON and produces an XML output.
One option that gets mentioned a lot at the XML conferences is the ReX parser generator (http://www.bottlecaps.de/rex/) - although totally undocumented on the site, recipes are available on searching.
4 suggested ways to open apk files:
1.open apk file by Android Studio (For Photo,java code and analyze size) the best way
2.open by applications winRar,7zip,etc (Just to see photos and ...)
3.use website javadecompilers (For Photo and java code)
4.use APK Tools (For Photo and java code)
I noticed a posting that say that it does not matter if you call a __stdcall
from a __cdecl
or visa versa. It does.
The reason: with __cdecl
the arguments that are passed to the called functions are removed form the stack by the calling function, in __stdcall
, the arguments are removed from the stack by the called function. If you call a __cdecl
function with a __stdcall
, the stack is not cleaned up at all, so eventually when the __cdecl
uses a stacked based reference for arguments or return address will use the old data at the current stack pointer. If you call a __stdcall
function from a __cdecl
, the __stdcall
function cleans up the arguments on the stack, and then the __cdecl
function does it again, possibly removing the calling functions return information.
The Microsoft convention for C tries to circumvent this by mangling the names. A __cdecl
function is prefixed with an underscore. A __stdcall
function prefixes with an underscore and suffixed with an at sign “@” and the number of bytes to be removed. Eg __cdecl
f(x) is linked as _f
, __stdcall f(int x)
is linked as _f@4
where sizeof(int)
is 4 bytes)
If you manage to get past the linker, enjoy the debugging mess.
Open visual studio command prompt and type below command and run
aspnet_regiis -ga machinename\ASPNET
After running the above command Reset the IIS
and test the application that resolve your issue.
If above command doesn’t resolve your problem then try to run below command in visual studio command prompt:-
aspnet_regiis -i
Alternatively we can run above command from our windows command prompt also
Go to the Start menu and open Run and enter and click OK
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –I
After that Reset the IIS and test the application that resolves your issue
tightVNC 2.5.X and even pre 2.5 supports multi monitor. When you connect, you get a huge virtual monitor. However, this is also has disadvantages. UltaVNC (Tho when I tried it, was buggy in this area) allows you to connect to one huge virtual monitor or just to 1 screen at a time. (With a button to cycle through them) TightVNC also plan to support such a feature.. (When , no idea) This feature is important as if you have large multi monitors and connecting over a reasonably slow link.. The screen updates are just to slow.. Cutting down to one monitor to focus on is desirable.
I like tightVNC, but UltraVNC seems to have a few more features right now..
I have found tightVNC more solid. And that is why I have stuck with it.
I would try both. They both work well, but I imagine one would suite slightly more then the other.
Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.
Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/
Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html
In some cases it's desirable to replace consecutive occurrences of every whitespace character with a single instance of that character. You'd use a regular expression with backreferences to do that.
(\s)\1{1,}
matches any whitespace character, followed by one or more occurrences of that character. Now, all you need to do is specify the first group (\1
) as the replacement for the match.
Wrapping this in a function:
import re
def normalize_whitespace(string):
return re.sub(r'(\s)\1{1,}', r'\1', string)
>>> normalize_whitespace('The fox jumped over the log.')
'The fox jumped over the log.'
>>> normalize_whitespace('First line\t\t\t \n\n\nSecond line')
'First line\t \nSecond line'
in my case i am add in manifest file `
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
application tag of course, It will work
See this thread concerning uninitialized bools, but it should answer your question.
Local variables are not initialized unless you call their constructors (new) or assign them a value.
Here is another way to express the object property.
foreach ($obj as $key=>$value) {
echo "$key => $obj[$key]\n";
}
The combination of both answers. Also prints a method name:
Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);
fmt.Println("%+v", structure variable)
A better way to do this would be to create a global constant for the string "%+v" in a package called "commons"(maybe) and use it everywhere in your code
//In commons package
const STRUCTURE_DATA_FMT = "%+v"
//In your code everywhere
fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
to chnage line endings from LF to CRLF:
open Sublime and follow the steps:-
1 press Ctrl+shift+p then install package name line unify endings
then again press Ctrl+shift+p
2 in the blank input box type "Line unify ending "
3 Hit enter twice
Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava
is very useful library, it also provides lots of features which related to Collections
, Caches
, Functional idioms
, Concurrency
, Strings
, Primitives
, Ranges
, IO
, Hashing
, EventBus
, etc
Ref: GuavaExplained
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute()
it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
When you create your Sequelize object, pass false
to the logging
parameter:
var sequelize = new Sequelize('database', 'username', 'password', {
// disable logging; default: console.log
logging: false
});
For more options, check the docs.
Just download and install the latest version of Virtual box, run it then run the emulator and viola, it will be up and running. This one worked for me.
One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user@debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
system.in.read() method reads a byte and returns as an integer but if you enter a no between 1 to 9 ,it will return 48+ values because in ascii code table ,ascii values of 1-9 are 48-57 . hope , it will help.
I had to stopPropigation
and preventDefault
in order to prevent a button expanding an accordion item that it sat above.
So...
@Component({
template: `
<button (click)="doSomething($event); false">Test</button>
`
})
export class MyComponent {
doSomething(e) {
e.stopPropagation();
// do other stuff...
}
}
You don't directly read a value. You can set it with .setValue()
, but there is no .getValue() on the reference object.
You have to use a listener. If you just want to read the value once, you use ref.addListenerForSingleValueEvent()
.
Example:
Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = (String) dataSnapshot.getValue();
// do your stuff here with value
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Source: https://www.firebase.com/docs/android/guide/retrieving-data.html#section-reading-once
You need to add -L/opt/lib
to tell ld
to look there for shared objects.
I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.
I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:
String storageState = Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
_photoFile = new File(path);
try {
if(_photoFile.exists() == false) {
_photoFile.getParentFile().mkdirs();
_photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
_fileUri = Uri.fromFile(_photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(MainActivity.this)
.setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
.setCancelable(true).create().show();
}
I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.
Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg
There is no need to copy the file in the "onActivityResult" as posted above.
Assuming code.cpp
is the source code, the following will not throw errors:
make code
./code
Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++
keyword in this case.
I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.
You need to transform the object you are getting back into an array in the format that jQueryUI expects.
You can use $.map
to transform the dealers
object into that array.
$('#dealerName').autocomplete({
source: function (request, response) {
$.getJSON("/example/location/example.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label
and value
properties that $.map
's callback function return.
Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:
label
property, a value
property, or both, orIn other words, if you can format the data like this:
[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
or this:
["dealer 5", "dealer 6"]
Then your JavaScript becomes much simpler:
$('#dealerName').autocomplete({
source: "/example/location/example.json"
});
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
In real life, if you are using a ORM like LINQ-to-SQL
In both cases if you don't call a ToList()
or ToArray()
then query will be executed each time it is used, so, say, you have an IQueryable<T>
and you fill 4 list boxes from it, then the query will be run against the database 4 times.
Also if you extent your query:
q.Where(x.name = "a").ToList()
Then with a IQueryable the generated SQL will contains “where name = “a”, but with a IEnumerable many more roles will be pulled back from the database, then the x.name = “a” check will be done by .NET.
You've got a few things going on there. One, why a class? Do you actually have multiple of these on the page? The CSS suggests you can't. If not you should use an ID - it's faster to select both in CSS and jQuery:
<div id=bottomMenu>You read it all.</div>
Second you've got a few crazy things going on in that CSS - in particular the z-index is supposed to just be a number, not measured in pixels. It specifies what layer this tag is on, where each higher number is closer to the user (or put another way, on top of/occluding tags with lower z-indexes).
The animation you're trying to do is basically .fadeIn(), so just set the div to display: none; initially and use .fadeIn() to animate it:
$('#bottomMenu').fadeIn(2000);
.fadeIn() works by first doing display: (whatever the proper display property is for the tag), opacity: 0, then gradually ratcheting up the opacity.
Full working example:
http://jsfiddle.net/b9chris/sMyfT/
CSS:
#bottomMenu {
display: none;
position: fixed;
left: 0; bottom: 0;
width: 100%; height: 60px;
border-top: 1px solid #000;
background: #fff;
z-index: 1;
}
JS:
var $win = $(window);
function checkScroll() {
if ($win.scrollTop() > 100) {
$win.off('scroll', checkScroll);
$('#bottomMenu').fadeIn(2000);
}
}
$win.scroll(checkScroll);
First Rename your AndroidManifest.xml file
android:label="Your App Name"
Second
Rename Your Application Name in Pubspec.yaml file
name: Your Application Name
Third Change Your Application logo
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/path/your Application logo.formate"
Fourth Run
flutter pub pub run flutter_launcher_icons:main
Using MPMoviePlayerController :
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var streamPlayer : MPMoviePlayerController = MPMoviePlayerController(contentURL: NSURL(string:"video url here"))
override func viewDidLoad() {
super.viewDidLoad()
streamPlayer.view.frame = self.view.bounds
self.view.addSubview(streamPlayer.view)
streamPlayer.fullscreen = true
// Play the movie!
streamPlayer.play()
}
}
Using AVPlayer :
import AVFoundation
var playerItem:AVPlayerItem?
var player:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "url of the audio or video")
playerItem = AVPlayerItem(URL: url!)
player=AVPlayer(playerItem: playerItem!)
let playerLayer=AVPlayerLayer(player: player!)
playerLayer.frame=CGRectMake(0, 0, 300, 50)
self.view.layer.addSublayer(playerLayer)
}
I have a play button to handle button tap.
playButton.addTarget(self, action: "playButtonTapped:", forControlEvents: .TouchUpInside)
func playButtonTapped(sender: AnyObject) {
if player?.rate == 0
{
player!.play()
playButton.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal)
} else {
player!.pause()
playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)
}
}
I have added an observer listening for AVPlayerItemDidPlayToEndTimeNotification.
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
When video/audio play is finished, reset button image and notification
func finishedPlaying(myNotification:NSNotification) {
playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)
let stopedPlayerItem: AVPlayerItem = myNotification.object as! AVPlayerItem
stopedPlayerItem.seekToTime(kCMTimeZero)
}
I was trying to call setErrors()
inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout()
:
template:
<input type="password" [(ngModel)]="user.password" class="form-control"
id="password" name="password" required (ngModelChange)="checkPasswords()">
<input type="password" [(ngModel)]="pwConfirm" class="form-control"
id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
#pwConfirmModel="ngModel">
<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
Passwords do not match
</div>
component:
@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;
checkPasswords() {
if (this.pwConfirm.length >= this.user.password.length &&
this.pwConfirm !== this.user.password) {
console.log('passwords do not match');
// setErrors() must be called after change detection runs
setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
} else {
// to clear the error, we don't have to wait
this.pwConfirmModel.control.setErrors(null);
}
}
Gotchas like this are making me prefer reactive forms.
There are several options and none of them are the official correct way and none of them are really incorrect, though they can convey different information to the computer and to others reading your code.
For the given example I think the clearest option would be to supply an identity default value, in this case do something like:
fooBar <- function(x, y=0) {
x + y
}
This is the shortest of the options shown so far and shortness can help readability (and sometimes even speed in execution). It is clear that what is being returned is the sum of x and y and you can see that y is not given a value that it will be 0 which when added to x will just result in x. Obviously if something more complicated than addition is used then a different identity value will be needed (if one exists).
One thing I really like about this approach is that it is clear what the default value is when using the args
function, or even looking at the help file (you don't need to scroll down to the details, it is right there in the usage).
The drawback to this method is when the default value is complex (requiring multiple lines of code), then it would probably reduce readability to try to put all that into the default value and the missing
or NULL
approaches become much more reasonable.
Some of the other differences between the methods will appear when the parameter is being passed down to another function, or when using the match.call
or sys.call
functions.
So I guess the "correct" method depends on what you plan to do with that particular argument and what information you want to convey to readers of your code.
I have struggled with this issue a lot and the solution is much simpler than i though.
I first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more.
I found that if I add the:
this.visible=false;
/* to the InitializeComponent() code just before the */
this.Load += new System.EventHandler(this.DebugOnOff_Load);
It is working just fine. but I wanted a more simple solution and it turn out that if you add the:
this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}
A transaction isn't needed here, this should suffice:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
Found a strange behaviour about this hidden value () and we can't make it to work.
After playing around we found the best way is just defined the value in controller itself after the form scope.
.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {
$scope.routineForm = {};
$scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";
$scope.sendData = function {
// JSON http post action to API
}
}])
[open git settings (TortoiseGit ? Settings ? Git)][1]
[In GIt: click to edit global .gitconfig][2]
=v= The "I" prefix is also used in the Wicket framework, where I got used to it quickly. In general, I welcome any convention that shortens cumbersome Java classnames. It is a hassle, though, that everything is alphabetized under "I" in the directories and in the Javadoc.
Wicket coding practice is similar to Swing, in that many control/widget instances are constructed as anonymous inner classes with inline method declarations. Annoyingly, it differs 180° from Swing in that Swing uses a prefix ("J") for the implementing classes.
The "Impl" suffix is a mangly abbreviation and doesn't internationalize well. If only we'd at least gone with "Imp" it would be cuter (and shorter). "Impl" is used for IOC, especially Spring, so we're sort of stuck with it for now. It gets a bit schizo following 3 different conventions in three different parts of one codebase, though.
I know this has been answered, but this issue confused me so many times I've put up a small reference website to help me remember: https://nitaym.github.io/ourstheirs/
Here are the basics:
$ git checkout master
$ git merge feature
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
$ git checkout feature
$ git rebase master
If you want to select the version in master
:
$ git checkout --ours codefile.js
If you want to select the version in feature
:
$ git checkout --theirs codefile.js
(This is for complete files, of course)
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
I'm using this and works fine
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%%'
I went to a bunch of SQL Server 2008 talks in PASS 2008, the only 'killer feature' from my point of view is extended events.
There are lots of great improvements, but that was the only one that got close to being a game changer for me. Table value parameters and merge were probably my next favourite. Day-to-day, IntelliSense is a huge win.. But this isn't really specific to SQL Server 2008, just the SQL Server 2008 toolset (other tools can give you similar IntelliSense against SQL Server 2005, 2000, etc.).
Only this sample working without problem:
var crop = new Rectangle(0, y, bitmap.Width, h);
var bmp = new Bitmap(bitmap.Width, h);
var tempfile = Application.StartupPath+"\\"+"TEMP"+"\\"+Path.GetRandomFileName();
using (var gr = Graphics.FromImage(bmp))
{
try
{
var dest = new Rectangle(0, 0, bitmap.Width, h);
gr.DrawImage(image,dest , crop, GraphicsUnit.Point);
bmp.Save(tempfile,ImageFormat.Jpeg);
bmp.Dispose();
}
catch (Exception)
{
}
}
$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');
$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));
It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:
google.loader.ClientLocation.address.city
What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.
Building on the :before
:after
technique by web_designer, here is something that comes closer to your look:
First, make your text the color of the inner shadow (black-ish in the case of the OP).
Now, use an :after psuedo class to create a transparent duplicate of the original text, placed directly on top of it. Assign a regular text shadow to it with no offset. Assign the original text color to the shadow, and adjust alpha as needed.
http://dabblet.com/gist/2499892
You don't get complete control over spread, etc. of the shadow like you do in PS, but for smaller blur values it is quite passable. The shadow goes past the bounds of the text, so if you are working in an environment with a high contrast background-foreground, it will be obvious. For lower contrast items, especially ones with the same hue, it's not too noticeable. For example, I've been able to make very nice looking etched text in metal backgrounds using this technique.
For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)
local pano_array=()
i=0
for line in $(grep "filename" "$file")
do
url=$(extract_url_from_xml $line)
pano_array[i]="$url"
i=$((i+1))
done
To add the second column, I define the size of the first column and calculate the values in an offset variable
array_len="${#pano_array[@]}"
i=0
while [[ $i -lt $array_len ]]
do
url="${pano_array[$i]}"
offset=$(($array_len+i))
found_file=$(get_file $url)
pano_array[$offset]=$found_file
i=$((i+1))
done
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.
On macos, configure python 3.8.1 with the command below will solve the problem, i think it would also work on Linux.
./configure --enable-optimizations --with-openssl=/usr/local/opt/[email protected]/
change the dir parameter based on your system.
I ended up writing a convenience method for our test-utils library
/**
* Utility method to test for a specific error class and message in Jest
* @param {fn, expectedErrorClass, expectedErrorMessage }
* @example failTest({
fn: () => {
return new MyObject({
param: 'stuff'
})
},
expectedErrorClass: MyError,
expectedErrorMessage: 'stuff not yet implemented'
})
*/
failTest: ({ fn, expectedErrorClass, expectedErrorMessage }) => {
try {
fn()
expect(true).toBeFalsy()
} catch (err) {
let isExpectedErr = err instanceof expectedErrorClass
expect(isExpectedErr).toBeTruthy()
expect(err.message).toBe(expectedErrorMessage)
}
}
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}
You can do it like this.
Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
Console.Write(item.Key);
Console.Write(item.Value.name);
Console.Write(item.Value.age);
}
The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
You should be able to access it from the function inside your controller.
Edit: Adding functional example of the full TestModels
implementation.
Your TestModels
class should look something like this.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You probably want to read up on the dynamic keyword as well.
Many times the problem comes because php
does not support short open tags in php.ini
file, i.e:
<?
phpinfo();
?>
You must use:
<?php
phpinfo();
?>
If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{ $1=""; print $0}')
;;
esac
It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like
root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript
Just an FYI
Refer This Link http://khurramitdeveloper.blogspot.in/2013/06/start-activity-or-service-on-boot.html Step by Step procedure to use boot on Service
The answer is not efficiency. Non-reentrant mutexes lead to better code.
Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.
Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.
The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.
If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.
One way - split you image into N rotating it slightly every time. I'd say 5 is enough. then create something like this in drawable
<animation-list android:id="@+id/handimation" android:oneshot="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/progress1" android:duration="150" />
<item android:drawable="@drawable/progress2" android:duration="150" />
<item android:drawable="@drawable/progress3" android:duration="150" />
</animation-list>
code start
progress.setVisibility(View.VISIBLE);
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.setCallback(progress);
frameAnimation.setVisible(true, true);
code stop
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.stop();
frameAnimation.setCallback(null);
frameAnimation = null;
progress.setVisibility(View.GONE);
more here
A simple solution for empty floated divs is to add:
this way you can keep the float functionality and force it to fill space when empty.
I use this technique in page layout columns, to keep every column in its position even if the other columns are empty.
Example:
.left-column
{
width: 200px;
min-height: 1px;
float: left;
}
.right-column
{
width: 500px;
min-height: 1px;
float: left;
}
In my case the key was:
AllowOverride All
in vhost definition. I hope it helps someone.
WPF has built-in converters for certain types. If you bind the Image's Source
property to a string
or Uri
value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource
.
So
<Image Source="{Binding ImageSource}"/>
would work if the ImageSource property was a string representation of a valid URI to an image.
You can of course roll your own Binding converter:
public class ImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
and use it like this:
<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
Yes, the 3rd template parameter on map
specifies the comparator, which is a binary predicate. Example:
struct ByLength : public std::binary_function<string, string, bool>
{
bool operator()(const string& lhs, const string& rhs) const
{
return lhs.length() < rhs.length();
}
};
int main()
{
typedef map<string, string, ByLength> lenmap;
lenmap mymap;
mymap["one"] = "one";
mymap["a"] = "a";
mymap["fewbahr"] = "foobar";
for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
cout << it->first << "\n";
}
I would just like to add that Step.js library helps you handle exceptions by always passing it to the next step function. Therefore you can have as a last step a function that check for any errors in any of the previous steps. This approach can greatly simplify your error handling.
Below is a quote from the github page:
any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down.
Furthermore, you can use Step to control execution of scripts to have a clean up section as the last step. For example if you want to write a build script in Node and report how long it took to write, the last step can do that (rather than trying to dig out the last callback).
You should do something like this:
1) create directory object what would point to server-side accessible folder
CREATE DIRECTORY image_files AS '/data/images'
/
2) Place your file into OS folder directory object points to
3) Give required access privileges to Oracle schema what will load data from file into table:
GRANT READ ON DIRECTORY image_files TO scott
/
4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:
DECLARE
l_blob BLOB;
v_src_loc BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
v_amount INTEGER;
BEGIN
INSERT INTO esignatures
VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob;
DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
DBMS_LOB.CLOSE(v_src_loc);
COMMIT;
END;
/
After this you get the content of your file in BLOB column and can get it back using Java for example.
edit: One letter left missing: it should be LOADFROMFILE.
c# 7.0 lets you do this:
var tupleList = new List<(int, string)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
If you don't need a List
, but just an array, you can do:
var tupleList = new(int, string)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
And if you don't like "Item1" and "Item2", you can do:
var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
or for an array:
var tupleList = new (int Index, string Name)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
which lets you do: tupleList[0].Index
and tupleList[0].Name
Framework 4.6.2 and below
You must install System.ValueTuple
from the Nuget Package Manager.
Framework 4.7 and above
It is built into the framework. Do not install System.ValueTuple
. In fact, remove it and delete it from the bin directory.
note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.
One way is to use pcntl_fork()
in a recursive function.
function networkCall(){
$data = processGETandPOST();
$response = makeNetworkCall($data);
processNetworkResponse($response);
return true;
}
function runAsync($times){
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
$times -= 1;
if($times>0)
runAsync($times);
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
networkCall();
posix_kill(getmypid(), SIGKILL);
}
}
runAsync(3);
One thing about pcntl_fork()
is that when running the script by way of Apache, it doesn't work (it's not supported by Apache). So, one way to resolve that issue is to run the script using the php cli, like: exec('php fork.php',$output);
from another file. To do this you'll have two files: one that's loaded by Apache and one that's run with exec()
from inside the file loaded by Apache like this:
apacheLoadedFile.php
exec('php fork.php',$output);
fork.php
function networkCall(){
$data = processGETandPOST();
$response = makeNetworkCall($data);
processNetworkResponse($response);
return true;
}
function runAsync($times){
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
$times -= 1;
if($times>0)
runAsync($times);
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
networkCall();
posix_kill(getmypid(), SIGKILL);
}
}
runAsync(3);
you will need to do it like this...
<a type="button" href="http://www.facebook.com/" value="facebook" target="_blank" class="button"></a>
and add the basic css if you want it to look like a btn.. like this
.button {
width:100px;
height:50px;
-moz-box-shadow:inset 0 1px 0 0 #fff;
-webkit-box-shadow:inset 0 1px 0 0 #fff;
box-shadow:inset 0 1px 0 0 #fff;
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #d1d1d1) );
background:-moz-linear-gradient( center top, #ffffff 5%, #d1d1d1 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d1d1d1');
background-color:#fff;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
color:#777;
font-family:Helvetica;
font-size:15px;
font-weight:700;
padding:6px 24px;
text-decoration:none;
text-shadow:1px 1px 0 #fff
}
.button:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #d1d1d1), color-stop(1, #ffffff) );
background:-moz-linear-gradient( center top, #d1d1d1 5%, #ffffff 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d1d1d1', endColorstr='#ffffff');
background-color:#d1d1d1
}
.button:active {
position:relative;
top:1px
}
target works only with href tags..
Only this one worked for me:
<script type="text/javascript">
var frames = document.getElementsByTagName("iframe");
for (var i = 0; i < frames.length; i++) {
src = frames[i].src;
if (src.indexOf('embed') != -1) {
if (src.indexOf('?') != -1) {
frames[i].src += "&wmode=transparent";
} else {
frames[i].src += "?wmode=transparent";
}
}
}
</script>
I load it in the footer.php Wordpress file. Code found in comment here (thanks Gerson)
if
statement is not vectorized. For vectorized if statements you should use ifelse
. In your case it is sufficient to write
w <- function(a){
if (any(a>0)){
a/sum(a)
}
else 1
}
or a short vectorised version
ifelse(a > 0, a/sum(a), 1)
It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse
gives output vector of length equal to length of a
.
Here is a flexible approach, it can be used in all cases, in particular:
dataframe
has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).First, un-factorize a string using the as.character
function, and, then, re-factorize with the as.factor
(or simply factor
) function:
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
Edit your AndroidManifest.xml
to add RECEIVE_BOOT_COMPLETED
permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Edit your AndroidManifest.xml
application-part for below Permission
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Now write below in Activity.
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
If you decide to dispatch to FileServlet
then you will also need allowLinking="true"
in context.xml
in order to allow FileServlet
to traverse the symlinks.
See http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
Here's a possible solution.
HTML
<img id="source" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
<div id="crop">
<img id="overlay" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>
CSS
#crop {
overflow: hidden;
position: absolute;
left: 100px;
top: 100px;
width: 450px;
height: 150px;
}
#overlay {
-webkit-filter:blur(4px);
filter:blur(4px);
width: 450px;
}
#source {
height: 300px;
width: auto;
position: absolute;
left: 100px;
top: 100px;
}
I know the CSS can be simplified and you probably should get rid of the ids. The idea here is to use a div as a cropping container and then apply blur on duplicate of the image. Fiddle
To make this work in Firefox, you would have to use SVG hack.
You could close your Android Application by calling System.exit(0).
I've been a big fan of REST in the past and it has many advantages over RPC on paper. You can present the client with different Content-Types, Caching, reuse of HTTP status codes, you can guide the client through the API and you can embed documentation in the API if it isn't mostly self-explaining anyway.
But my experience has been that in practice this doesn't hold up and instead you do a lot of unnecessary work to get everything right. Also the HTTP status codes often don't map to your domain logic exactly and using them in your context often feels a bit forced. But the worst thing about REST in my opinion is that you spend a lot of time to design your resources and the interactions they allow. And whenever you do some major additions to your API you hope you find a good solution to add the new functionality and you didn't design yourself into a corner already.
This often feels like a waste of time to me because most of the time I already have a perfectly fine and obvious idea about how to model an API as a set of remote procedure calls. And if I have gone through all this effort to model my problem inside the constraints of REST the next problem is how to call it from the client? Our programs are based on calling procedures so building a good RPC client library is easy, building a good REST client library not so much and in most cases you will just map back from your REST API on the server to a set of procedures in your client library.
Because of this, RPC feels a lot simpler and more natural to me today. What I really miss though is a consistent framework that makes it easy to write RPC services that are self-describing and interoperable. Therefore I created my own project to experiment with new ways to make RPC easier for myself and maybe somebody else finds it useful, too: https://github.com/aheck/reflectrpc
I tried roomaroo's WMI method to shutdown Windows 2003 Server, but it would not work until I added `[STAThread]' (i.e. "Single Threaded Apartment" threading model) to the Main() declaration:
[STAThread]
public static void Main(string[] args) {
Shutdown();
}
I then tried to shutdown from a thread, and to get that to work I had to set the "Apartment State" of the thread to STA as well:
using System.Management;
using System.Threading;
public static class Program {
[STAThread]
public static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(Program.Shutdown));
t.SetApartmentState(ApartmentState.STA);
t.Start();
...
}
public static void Shutdown() {
// roomaroo's code
}
}
I'm a C# noob, so I'm not entirely sure of the significance of STA threads in terms of shutting down the system (even after reading the link I posted above). Perhaps someone else can elaborate...?
If you are using Eloquent the best solution is:
public function getFormattedPriceAttribute()
{
return number_format($this->attributes['price'], 2);
}
So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.
SQL Server 2019 will finally return more meaningful error message.
Binary or string data would be truncated => error message enhancments
if you have that error (in production), it's not obvious to see which column or row this error comes from, and how to locate it exactly.
To enable new behavior you need to use DBCC TRACEON(460)
. New error text from sys.messages
:
SELECT * FROM sys.messages WHERE message_id = 2628
2628 – String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.
String or Binary data would be truncated: replacing the infamous error 8152
This new message is also backported to SQL Server 2017 CU12 (and in an upcoming SQL Server 2016 SP2 CU), but not by default. You need to enable trace flag 460 to replace message ID 8152 with 2628, either at the session or server level.
Note that for now, even in SQL Server 2019 CTP 2.0 the same trace flag 460 needs to be enabled. In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.
SQL Server 2017 CU12 also supports this feature.
This SQL Server 2017 update introduces an optional message that contains the following additional context information.
Msg 2628, Level 16, State 6, Procedure ProcedureName, Line Linenumber String or binary data would be truncated in table '%.*ls', column '%.*ls'. Truncated value: '%.*ls'.
The new message ID is 2628. This message replaces message 8152 in any error output if trace flag 460 is enabled.
ALTER DATABASE SCOPED CONFIGURATION
VERBOSE_TRUNCATION_WARNINGS = { ON | OFF }
APPLIES TO: SQL Server (Starting with SQL Server 2019 (15.x)) and Azure SQL Database
Allows you to enable or disable the new String or binary data would be truncated error message. SQL Server 2019 (15.x) introduces a new, more specific error message (2628) for this scenario:
String or binary data would be truncated in table '%.*ls', column'%.*ls'. Truncated value: '%.*ls'.
When set to ON under database compatibility level 150, truncation errors raise the new error message 2628 to provide more context and simplify the troubleshooting process.
When set to OFF under database compatibility level 150, truncation errors raise the previous error message 8152.
For database compatibility level 140 or lower, error message 2628 remains an opt-in error message that requires trace flag 460 to be enabled, and this database scoped configuration has no effect.
If your text contains only one individual:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def roplo(file_name,what):
patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
with open(file_name,'rb+') as f:
ch = f.read()
f.seek(0)
f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')
# after treatment
with open('pers.txt','rb') as h:
print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If your text contains several individuals:
import re
# creation
with open('pers.txt','wb') as g:
g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim \n dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')
with open('pers.txt','rb') as h:
print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt before treatment:\n',h.read()
# treatment
def ripli(file_name,who,what):
with open(file_name,'rb+') as f:
ch = f.read()
x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
f.seek(x)
f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')
# after treatment
with open('pers.txt','rb') as h:
print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
print '\nrU-display of pers.txt after treatment:\n',h.read()
If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.
But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:
from cPickle import dump, load
with open('cards','wb') as f:
dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)
with open('cards','rb') as g:
id_cards = load(g)
print 'id_cards before change==',id_cards
id_cards['Jim'][0] = 'Wizard'
with open('cards','w') as h:
dump(id_cards,h)
with open('cards') as e:
id_cards = load(e)
print '\nid_cards after change==',id_cards
You can also use template reference variables
<form (submit)="onSubmit(player.value)">
<input #player placeholder="player name">
</form>
onSubmit(playerName: string) {
console.log(playerName)
}
An abstract class can be used instead of an interface (in C# 7.3).
// Like interface
abstract class IIO
{
public virtual async Task<string> DoOperation(string Name)
{
throw new NotImplementedException(); // throwing exception
// return await Task.Run(() => { return ""; }); // or empty do
}
}
// Implementation
class IOImplementation : IIO
{
public override async Task<string> DoOperation(string Name)
{
return await await Task.Run(() =>
{
if(Name == "Spiderman")
return "ok";
return "cancel";
});
}
}
I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.
However, it does not cover the addHitRegion
API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla
I had this error, because i scrolled bottom. Datepicker had wrong top position in fixed. I just use it now like:
$('#myModal').on('show.bs.modal', function (e) {
$(document).scrollTop(0);
});
and its working fine now.
\
does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.
Consider this command:
mysql -uroot \ -hlocalhost
If there is a space after \
, the line continuation will not work. The reason is that \
removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \
in this example.
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.
// template
<your-input [readonly]="!childmessage"></your-input>
// component value
childmessage = false;
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
If you're searching for hits within a larger text, you don't want to use ^
and $
as some other responders have said; those match the beginning and end of the text. Try this instead:
\bdbo\.\w+_fn\b
\b
is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:
dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)
...but not in this one:
foodbo.functionName_fnbar
\w+
matches one or more "word characters" (letters, digits, or _
). If you need something more inclusive, you can try \S+
(one or more non-whitespace characters) or .+?
(one or more of any characters except linefeeds, non-greedily). The non-greedy +?
prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn
as if it were just one hit.
Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).
EDIT: Java 8 has something very similar and is worth checking out.
e.g.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.
In your Fragments onCreateView(...)
you can remove a view by calling container.removeView(view);
.
So if you want to remove the fragment, then view
should be the return value of onCreateView
,
for example
public View onCreateView(...){
final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
//Do something
finishButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
container.removeView(view);
}
});
return view;
}
if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int)
if you want your dataset to be unchangeable.
Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs
module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export
// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()
I have solved a similar problem like that:
plan = (FcsRequestPlan) session.load(plan.getClass(), plan.getUUID());
while (plan instanceof HibernateProxy)
plan = (FcsRequestPlan) ((HibernateProxy) plan).getHibernateLazyInitializer().getImplementation();
I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Let's say you have input
and textarea
and like to apply the same validation logic:
const Input = (props) => (
<input type="text"
style={props.style}
onChange={props.onChange} />
)
const TextArea = (props) => (
<textarea rows="3"
style={props.style}
onChange={props.onChange} >
</textarea>
)
Then write a HOC that does validate and style wrapped component:
function withValidator(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props)
this.validateAndStyle = this.validateAndStyle.bind(this)
this.state = {
style: {}
}
}
validateAndStyle(e) {
const value = e.target.value
const valid = value && value.length > 3 // shared logic here
const style = valid ? {} : { border: '2px solid red' }
console.log(value, valid)
this.setState({
style: style
})
}
render() {
return <WrappedComponent
onChange={this.validateAndStyle}
style={this.state.style}
{...this.props} />
}
}
}
Now those HOCs share the same validating behavior:
const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)
render((
<div>
<InputWithValidator />
<TextAreaWithValidator />
</div>
), document.getElementById('root'));
I created a simple demo.
Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOC
s like:
<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />
Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.
const Input = (props) => {
const inputValidation = useInputValidation()
return (
<input type="text"
{...inputValidation} />
)
}
function useInputValidation() {
const [value, setValue] = useState('')
const [style, setStyle] = useState({})
function handleChange(e) {
const value = e.target.value
setValue(value)
const valid = value && value.length > 3 // shared logic here
const style = valid ? {} : { border: '2px solid red' }
console.log(value, valid)
setStyle(style)
}
return {
value,
style,
onChange: handleChange
}
}
https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js
There is a operator < between lists e.g.:
[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]
will give
False
Try this:
$('#id').change();
Works for me.
On one line together with setting the value:
$('#id').val(16).change();
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
For Microsoft Visual Studio Community 2017 use Ctrl+Alt+A
Alternatively from command panel view -> Other Windows -> Command Window
https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.
Usage looks like:
$ ls test
a d d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye
Assuming that you have a DHCP server running at your router I would use:
# /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
After changing the file issue (as root):
/etc/init.d/networking restart
Apparently you can subtract the number of days you want from a datetime.
SELECT GETDATE() - 1
2016-12-25 15:24:50.403
You did everything correctly!
You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.
A Python solution:
python -c "import sys; print('\n'.join(' '.join(c) for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip()))))" < input > output
The above is based on the following:
import sys
for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip())):
print(' '.join(c))
This code does assume that every line has the same number of columns (no padding is performed).
At the command line paste the following
export QUERY_STRING="param1=abc¶m2=xyz" ;
POST_STRING="name=John&lastname=Doe" ; php -e -r
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"],
$_POST); include "index.php";'
do not turn off firewall, Go Control Panel\System and Security\Windows Firewall then Advanced settings then Inbound Rules->From right pan choose New Rule-> Port-> TCP and type in port number 80 then give a name in next window, that's it.
Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)
The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.
Here's what I did instead:
Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.
Right click on the project in the Package Explorer, select Properties to open the properties for your project.
(Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:
Click on the Android category and remove the reference to the google-play-services project.
Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.
Click on the Java Build Path category, then the Libraries tab.
Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.
Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.
Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.
Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.
Click OK to save your project properties.
Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.
These two packages need to be installed separately and usually can't be installed using pip
...Therefore, for FreeBSD:
Download a compressed snapshot of the Ports Collection into /var/db/portsnap:
# portsnap fetch
When running Portsnap for the first time, extract the snapshot into /usr/ports:
# portsnap extract
After the first use of Portsnap has been completed as shown above, /usr/ports can be updated as needed by running:
# portsnap fetch
# portsnap update
Now Install:
cd /usr/ports/textproc/libxml2
make install clean
cd /usr/ports/textproc/libxslt
make install clean
You should be good to go...
could be that you're missing the certificate on your device.
try looking at this answer: How to install trusted CA certificate on Android device? to see how to install the CA on your own device.
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
Late answer, but I think it adds something new to this topic.
None of the previous answers has answered the original question. Some have attempted to justify the lack of a constant, while others have showed ways in which we can deal with the lack of the constant. But no one has provided a compelling justification for the benefit of the constant, so its lack is still not properly explained.
A constant would be useful because it would prevent certain code errors from going unnoticed.
Say that you have a large code base with hundreds of references to "". Someone modifies one of these while scrolling through the code and changes it to " ". Such a change would have a high chance of going unnoticed into production, at which point it might cause some issue whose source will be tricky to detect.
OTOH, a library constant named EMPTY, if subject to the same error, would generate a compiler error for something like EM PTY.
Defining your own constant is still better. Someone could still alter its initialization by mistake, but because of its wide use, the impact of such an error would be much harder to go unnoticed than an error in a single use case.
This is one of the general benefits that you get from using constants instead of literal values. People usually recognize that using a constant for a value used in dozens of places allows you to easily update that value in just one place. What is less often acknowledged is that this also prevents that value from being accidentally modified, because such a change would show everywhere. So, yes, "" is shorter than EMPTY, but EMPTY is safer to use than "".
So, coming back to the original question, we can only speculate that the language designers were probably not aware of this benefit of providing constants for literal values that are frequently used. Hopefully, we'll one day see string constants added in Java.
If you use cv2
, correct method is to use .copy()
method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.
eg:
In [1]: import numpy as np
In [2]: x = np.arange(10*10).reshape((10,10))
In [4]: y = x[3:7,3:7].copy()
In [6]: y[2,2] = 1000
In [8]: 1000 in x
Out[8]: False # see, 1000 in y doesn't change values in x, parent array.
If you are using the codeigniter framework and are testing the project on a localhost, open the main Index.php file of your project folder and find this code:
define('ENVIRONMENT', 'production');
Change it to
define ('ENVIRONMENT', 'development');
Because same this ENVIRONMENT is in your database.php file under config folder. like this:
'db_debug' => (ENVIRONMENT! == 'development')
So the environment should be the same in both places and problem will be solved.
In your doSomething()
function, pass in the event e
and use e.preventDefault()
.
doSomething = function (e) {
alert('it works!');
e.preventDefault();
}
You're getting that because VARCHAR
is not a valid type to cast into. According to the MySQL docs (http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast) you can only cast to:
I think your best-bet is to use CHAR
.
Perhaps something that's not been mentioned is that of locality.
A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work to sort numbers closer-together than those distributed randomly (UUID4) (see here).
A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not explicitly stored (this is obviously in conflict with the privacy issue mentioned by the OP).
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
I heard which
is not recommended, so change Best rated answer to this.
$('#formid').on('keyup keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
return false;
}
});
ref. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
I realize this is a little old, but, yes it can be done. Some javascript to get you started:
viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');
Just change the parts you need and Mobile Safari will respect the new settings.
Update:
If you don't already have the meta viewport tag in the source, you can append it directly with something like this:
var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);
Or if you're using jQuery:
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');
This will give you what you want:
eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]
The error in your second attempt is because you forgot the ,
In general, for convenience, the specification object[index]
subsets columns for a 2d object
. If you want to subset rows and keep all columns you have to use the specification
object[index_rows, index_columns]
, while index_cols
can be left blank, which will use all columns by default.
However, you still need to include the ,
to indicate that you want to get a subset of rows instead of a subset of columns.
You can install the package gcolor2
for this:
sudo apt-get install gcolor2
Then:
Applications -> Graphics -> GColor2
I had the same problem and found out that you have to escape spaces in the extra:
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb"
So instead of "test from adb" it should be "test\ from\ adb"
A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).
Fully documented and simple to use, I hope someone finds it useful!
public class TimeTrialManager
{
private long expiryTime=0;
private string softwareName = "";
private string userPath="";
private bool useSeconds = false;
public TimeTrialManager(string softwareName) {
this.softwareName = softwareName;
// Create folder in Windows Application Data folder for persistence:
userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
userPath += "expiryinfo.txt";
}
// Use this method to check if the expiry has already been created. If
// it has, you don't need to call the setExpiryDate() method ever again.
public bool expiryHasBeenStored(){
return File.Exists(userPath);
}
// Use this to set expiry as the number of days from the current time.
// This should be called just once in the program's lifetime for that user.
public void setExpiryDate(double days) {
DateTime time = DateTime.Now.AddDays(days);
expiryTime = time.ToFileTimeUtc();
storeExpiry(expiryTime.ToString() );
useSeconds = false;
}
// Like above, but set the number of seconds. This should be just used for testing
// as no sensible time trial would allow the user seconds to test the trial out:
public void setExpiryTime(double seconds) {
DateTime time = DateTime.Now.AddSeconds(seconds);
expiryTime = time.ToFileTimeUtc();
storeExpiry(expiryTime.ToString());
useSeconds = true;
}
// Check for this in a background timer or whenever else you wish to check if the time has run out
public bool trialHasExpired() {
if(!File.Exists(userPath)) return false;
if (expiryTime == 0) expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
}
// This method is optional and isn't required to use the core functionality of the class
// Perhaps use it to tell the user how long he has left to trial the software
public string expiryAsHumanReadableString(bool remaining=false) {
DateTime dt = new DateTime();
dt = DateTime.FromFileTimeUtc(expiryTime);
if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
else {
if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
}
}
// This method is private to the class, so no need to worry about it
private void storeExpiry(string value) {
try { File.WriteAllText(userPath, value); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
}
Here is a typical usage of the above class. Couldn't be simpler!
TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
ttm = new TimeTrialManager("TestTime");
if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}
private void timer1_Tick(object sender, EventArgs e)
{
if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}
I did quite a bit of investigation on that topic recently since I was not satisfied with the many libraries I found out there.
I ended up developing a library to address this, it is named valid8. As explained in the documentation, it is for value validation mostly (although it comes bundled with simple type validation functions too), and you might wish to associate it with a PEP484-based type checker such as enforce or pytypes.
This is how you would perform validation with valid8
alone (and mini_lambda
actually, to define the validation logic - but it is not mandatory) in your case:
# for type validation
from numbers import Integral
from valid8 import instance_of
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@validate_arg('a', instance_of(Integral))
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', instance_of(str), Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # InputValidationError for 'a' HasWrongType: Value should be an instance of <class 'numbers.Integral'>. Wrong value: [0.2].
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # InputValidationError for 'c' Successes: [] / Failures: {"instance_of_<class 'str'>": "HasWrongType: Value should be an instance of <class 'str'>. Wrong value: [0]", 'len(s) > 0': "TypeError: object of type 'int' has no len()"}.
my_function(0, 1, '') # InputValidationError for 'c' Successes: ["instance_of_<class 'str'>"] / Failures: {'len(s) > 0': 'False'}
And this is the same example leveraging PEP484 type hints and delegating type checking to enforce
:
# for type validation
from numbers import Integral
from enforce import runtime_validation, config
config(dict(mode='covariant')) # type validation will accept subclasses too
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@runtime_validation
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # RuntimeTypeError 'a' was not of type <class 'numbers.Integral'>
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # RuntimeTypeError 'c' was not of type <class 'str'>
my_function(0, 1, '') # InputValidationError for 'c' [len(s) > 0] returned [False].
Instead of modifying the HTML itself, you should just set the value you want from the relative option element:
$(function() {
$("#country").val("ID");
});
In this case "ID" is the value of the option "Indonesia"
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
If you are targeting iOS7 and already have the image split into frames you can use animatedImageNamed:duration:
.
Let's say you are animating a spinner. Copy all of your frames into the project and name them as follows:
spinner-1.png
spinner-2.png
spinner-3.png
Then create the image via:
[UIImage animatedImageNamed:@"spinner-" duration:1.0f];
This method loads a series of files by appending a series of numbers to the base file name provided in the name parameter. For example, if the name parameter had ‘image’ as its contents, this method would attempt to load images from files with the names ‘image0’, ‘image1’ and so on all the way up to ‘image1024’. All images included in the animated image should share the same size and scale.
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
More info: https://developers.google.com/analytics/devguides/collection/gajs/
In new version they used '//' so browser can automatically add protocol:
'//www.google-analytics.com/analytics.js'
So if Google prefers document.location to window.location
when they need protocol in JS, I guess they have some reasons for that.
OVERALL: I personally believe that document.location
and window.location
are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.
I am using texmaker as the editor. you have to compile it in terminal as following:
but sometimes, when you use \citep{}
, the names of the references don't show up. In this case, I had to open the references.bib
file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.
I had trouble passing parameters to the Commands.AddScript method.
C:\Foo1.PS1 Hello World Hunger
C:\Foo2.PS1 Hello World
scriptFile = "C:\Foo1.PS1"
parameters = "parm1 parm2 parm3" ... variable length of params
I Resolved this by passing null
as the name and the param as value into a collection of CommandParameters
Here is my function:
private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(scriptFile);
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (string scriptParameter in scriptParameters.Split(' '))
{
CommandParameter commandParm = new CommandParameter(null, scriptParameter);
commandParameters.Add(commandParm);
scriptCommand.Parameters.Add(commandParm);
}
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
}
contains
method uses equals
internally. So you need to override the equals
method for your class as per your need.
Btw this does not look syntatically correct:
new Object().setName("John")
The delete
operator allows you to remove a property from an object.
The following examples all do the same thing.
// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
If you're interested, read Understanding Delete for an in-depth explanation.
A nuanced explanation from the GitHub documentation on Duplicating a Repository:
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository.
Use ngModelChange
by breaking up the [(x)]
syntax into its two pieces, i.e., property databinding and event binding:
<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
mymodel = newValue;
console.log(newValue)
}
It works for the backspace key too.
Sure, convert the file to ascii and blast all unicode characters away. It will probably work.... BUT...
Two more sugrical approaches to fixing the problem:
Regex search all unicode characters not part non-extended ascii. In notepad++ I can search up to FFFF, which hasn't failed me yet.
[\x{80}-\x{FFFF}]
80 is hex for 128, the first extended ascii character.
After hitting "find next" and highlighting what appears to be empty space, you can close your search dialog and press CTRL+C to copy to clipboard.
Then paste the character into a unicode search tool. I usually use an online one. http://unicode.scarfboy.com/
Example: I had a bullet point (•) in my code somehow. The unicode value is 2022 (hex), but when read as ascii by the compiler you get \342 \200 \242 (3 octal values). It's not as simple as converting each octal values to hex and smashing them together. So "E2 80 A2" is NOT the hex unicode point in your code.
app.use(express.static(__dirname + '/public'));
<link href="/css/style.css" rel="stylesheet" type="text/css">
So folder structure should be:
.
./app.js
./public
/css
/style.css
Try to use a
$(window).load
eventor
$(document).ready
because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.
The default scope is "default". It's weird--see these references for more info.
Microsoft: "Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.....If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute
attribute"
Microsoft: "Use application domains to isolate tasks that might bring down a process."
The program below will protect your main application/thread from unrecoverable failures without risks associated with use of HandleProcessCorruptedStateExceptions
and <legacyCorruptedStateExceptionsPolicy>
public class BoundaryLessExecHelper : MarshalByRefObject
{
public void DoSomething(MethodParams parms, Action action)
{
if (action != null)
action();
parms.BeenThere = true; // example of return value
}
}
public struct MethodParams
{
public bool BeenThere { get; set; }
}
class Program
{
static void InvokeCse()
{
IntPtr ptr = new IntPtr(123);
System.Runtime.InteropServices.Marshal.StructureToPtr(123, ptr, true);
}
private static void ExecInThisDomain()
{
try
{
var o = new BoundaryLessExecHelper();
var p = new MethodParams() { BeenThere = false };
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); //never stops here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
Console.ReadLine();
}
private static void ExecInAnotherDomain()
{
AppDomain dom = null;
try
{
dom = AppDomain.CreateDomain("newDomain");
var p = new MethodParams() { BeenThere = false };
var o = (BoundaryLessExecHelper)dom.CreateInstanceAndUnwrap(typeof(BoundaryLessExecHelper).Assembly.FullName, typeof(BoundaryLessExecHelper).FullName);
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); // never gets to here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
finally
{
AppDomain.Unload(dom);
}
Console.ReadLine();
}
static void Main(string[] args)
{
ExecInAnotherDomain(); // this will not break app
ExecInThisDomain(); // this will
}
}
Convert the excel file to .csv
file (comma separated value file) and now you can easily be able to read it.
Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.
Yes, otherwise it wouldn't be called "deprecated"
Unless stated otherwise in docs, it should be the same as before
No, but if there were problems in v1 they aren't about to fix them
I took aberke's solution and modified it to suit my taste.
My Code Pen
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('exampleController',_x000D_
function exampleController($scope) {_x000D_
$scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}};_x000D_
$scope.homePhonePrompt = "Home Phone";_x000D_
});_x000D_
_x000D_
myApp_x000D_
/*_x000D_
Intended use:_x000D_
<phone-number placeholder='prompt' model='someModel.phonenumber' />_x000D_
Where: _x000D_
someModel.phonenumber: {String} value which to bind formatted or unformatted phone number_x000D_
_x000D_
prompt: {String} text to keep in placeholder when no numeric input entered_x000D_
*/_x000D_
.directive('phoneNumber',_x000D_
['$filter',_x000D_
function ($filter) {_x000D_
function link(scope, element, attributes) {_x000D_
_x000D_
// scope.inputValue is the value of input element used in template_x000D_
scope.inputValue = scope.phoneNumberModel;_x000D_
_x000D_
scope.$watch('inputValue', function (value, oldValue) {_x000D_
_x000D_
value = String(value);_x000D_
var number = value.replace(/[^0-9]+/g, '');_x000D_
scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension);_x000D_
scope.phoneNumberModel = scope.inputValue;_x000D_
});_x000D_
}_x000D_
_x000D_
return {_x000D_
link: link,_x000D_
restrict: 'E',_x000D_
replace: true,_x000D_
scope: {_x000D_
phoneNumberPlaceholder: '@placeholder',_x000D_
phoneNumberModel: '=model',_x000D_
allowExtension: '=extension'_x000D_
},_x000D_
template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />'_x000D_
};_x000D_
}_x000D_
]_x000D_
)_x000D_
/* _x000D_
Format phonenumber as: (aaa) ppp-nnnnxeeeee_x000D_
or as close as possible if phonenumber length is not 10_x000D_
does not allow country code or extensions > 5 characters long_x000D_
*/_x000D_
.filter('phoneNumber', _x000D_
function() {_x000D_
return function(number, allowExtension) {_x000D_
/* _x000D_
@param {Number | String} number - Number that will be formatted as telephone number_x000D_
Returns formatted number: (###) ###-#### x #####_x000D_
if number.length < 4: ###_x000D_
else if number.length < 7: (###) ###_x000D_
removes country codes_x000D_
*/_x000D_
if (!number) {_x000D_
return '';_x000D_
}_x000D_
_x000D_
number = String(number);_x000D_
number = number.replace(/[^0-9]+/g, '');_x000D_
_x000D_
// Will return formattedNumber. _x000D_
// If phonenumber isn't longer than an area code, just show number_x000D_
var formattedNumber = number;_x000D_
_x000D_
// if the first character is '1', strip it out _x000D_
var c = (number[0] == '1') ? '1 ' : '';_x000D_
number = number[0] == '1' ? number.slice(1) : number;_x000D_
_x000D_
// (###) ###-#### as (areaCode) prefix-endxextension_x000D_
var areaCode = number.substring(0, 3);_x000D_
var prefix = number.substring(3, 6);_x000D_
var end = number.substring(6, 10);_x000D_
var extension = number.substring(10, 15);_x000D_
_x000D_
if (prefix) {_x000D_
//formattedNumber = (c + "(" + area + ") " + front);_x000D_
formattedNumber = ("(" + areaCode + ") " + prefix);_x000D_
}_x000D_
if (end) {_x000D_
formattedNumber += ("-" + end);_x000D_
}_x000D_
if (allowExtension && extension) {_x000D_
formattedNumber += ("x" + extension);_x000D_
}_x000D_
return formattedNumber;_x000D_
};_x000D_
}_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="exampleController">_x000D_
<p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p>_x000D_
<p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p>_x000D_
<phone-number id="homePhone"_x000D_
class="form-control" _x000D_
placeholder="Home Phone" _x000D_
model="user.profile.HomePhone"_x000D_
ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" />_x000D_
</div>
_x000D_
Yes. Have a look at Wikipedia and Cloanto Implementation of INI File Format (see bottom of page).
It's often mentioned that to list a complete list of attributes you should use dir()
. Note however that contrary to popular belief dir()
does not bring out all attributes. For example you might notice that __name__
might be missing from a class's dir()
listing even though you can access it from the class itself. From the doc on dir()
(Python 2, Python 3):
Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
A function like the following tends to be more complete, although there's no guarantee of completeness since the list returned by dir()
can be affected by many factors including implementing the __dir__()
method, or customizing __getattr__()
or __getattribute__()
on the class or one of its parents. See provided links for more details.
def dirmore(instance):
visible = dir(instance)
visible += [a for a in set(dir(type)).difference(visible)
if hasattr(instance, a)]
return sorted(visible)
I have used like this to show the soft keyboard programatically and this is worked for me to prevent the auto resize of the screen while launching the keyboard.
In manifest:
<activity android:name="XXXActivity" android:windowSoftInputMode="adjustPan">
</activity>
In XXXActvity:
EditText et = (EditText))findViewById(R.id.edit_text);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(et.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
}
};
timer.schedule(task, 200);
I assume this will save others time to search for this problem.
Both are data providers (API that your code will use to talk to a data source). Oledb which was introduced in 1998 was meant to be a replacement for ODBC (introduced in 1992)
$limit=5; // for exemple
$query = $this->getDoctrine()->getEntityManager()->createQuery(
'// your request')
->setMaxResults($limit);
$results = $query->getResult();
// Done
You can use this code in your java file
add this line before you set or load your view
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
On Windows, you can use Mac on a virtual machine (this probably also works on Linux but I haven't tested). A virtual machine is basically a program that you run on your computer that allows you to run one OS in a window inside another one. Make sure you have at least 60GB free space on your hard drive. The virtual hard drive that you will download takes up 10GB initially but when you've installed all the necessary programs for developing iOS apps its size can easily increase to 50GB (I recommend leaving a few GBs margin just in case).
Here are some detailed steps for how install a Mac virtual machine on Windows:
Install VirtualBox.
You have to enable virtualization in the BIOS. To open the BIOS on Windows 10, you need to start by holding down the Shift key while pressing the Restart button in the start menu. Then you will get a blue screen with some options. Choose "Troubleshoot", then "Advanced options", then "UEFI Firmware Settings", then "Restart". Then your computer will restart and open the BIOS directly. On older versions of Windows, shut down the computer normally, hold the F2 key down, start your computer again and don't release F2 until you're in the BIOS. On some computers you may have to hold down another key than F2.
Now that you're in the BIOS, you need to enable virtualization. Which setting you're supposed to change depends on which computer you're using. This may vary even between two computers with the same version of Windows. On my computer, you need to set Intel Virtual Technology
in the Configuration
tab to Enabled
. On other computers it may be in for example Security -> Virtualization
or in Advanced -> CPU Setup
. If you can't find any of these options, search Google for enable virtualization (the kind of computer you have)
. Don't change anything in the BIOS just like that at random because otherwise it could cause problems on your computer. When you've enabled virtualization, save the changes and exit the BIOS. This is usually done in the Exit
tab.
Download this file (I have no association with the person who uploaded it, but I've used it myself so I'm sure there are no viruses). If the link gets broken, post a comment to let me know and I will try to upload the file somewhere else. The password to open the 7Z file is stackoverflow.com
. This 7Z file contains a VMDK file which will act as the hard drive for the Mac virtual machine. Extract that VMDK file. If disk space is an issue for you, once you've extracted the VMDK file, you can delete the 7Z file and therefore save 7GB.
Open VirtualBox that you installed in step 1. In the toolbar, press the New button. Then choose a name for your virtual machine (the name is unimportant, I called it "Mac"). In "Type", select "Mac OS X" and in "Version" select "macOS 10.13 High Sierra (64 bit)" (the Mac version you will install on the virtual machine is actually Catalina, but VirtualBox doesn't have that option yet and it works just fine if VirtualBox thinks it's High Sierra).
It's also a good idea (though not required) to move the VMDK file you extracted in step 4 to the folder listed under "Machine Folder" (in the screenshot above that would be C:\Users\myname\VirtualBox VMs
).
Select the amount of memory that your virtual machine can use. Try to balance the amount because too little memory will result in the virtual machine having low performance and a too much memory will result making your host system (Windows) run out of memory which will cause the virtual machine and/or other programs that you're running on Windows to crash. On a computer with 4GB available memory, 2GB was a good amount. Don't worry if you select a bad amount, you will be able to change it whenever you want (except when the virtual machine is running).
In the Hard disk step, choose "Use an existing virtual hard disk file" and click on the little folder icon to the right of the drop list. That will open a new window. In that new window, click on the "Add" button on the top left, which will open a browse window. Select the VMDK file that you downloaded and extracted in step 4, then click "Choose".
When you're done with this, click "Create".
Select the virtual machine in the list on the left of the window and click on the Settings button in the toolbar. In System -> Processor, select 2 CPUs; and in Network -> Attached to, select Bridged Adapter. If you realize later that you selected an amount of memory in step 6 that causes problems, you can change it in System -> Motherboard. When you're done changing the settings, click OK.
Open the command prompt (C:\Windows\System32\cmd.exe
). Run the following commands in there, replacing "Your VM Name"
with whatever you called your virtual machine in step 5 (for example "Mac"
) (keep the quotation marks):
cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage.exe modifyvm "Your VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemSerial" C02L280HFMR7
Now everything is ready for you to use the virtual machine. In VirtualBox, click on the Start button and follow the installation instructions for Mac. Once you've installed Mac on the virtual machine, you can develop your iOS app just like if you had a real Mac.
Remark: If you want to save space on your hard disk, you can compress the VMDK file that you extracted in step 4 and used in step 7. To do this, right click on it, select Properties, click on the Advanced... button on the bottom right, and check the checkbox "Compress contents to save disk space". This will make this very large file take less disk space without making anything work less well. I did it and it reduced the disk size of the VMDK file from 50GB to 40GB without losing any data.
An Example for a Mac OS X 10.5+ with a German layout keyboard without NumPads:
This way you can be sure that those keys are not mapped (except if you assigned them before to another function)
Same think can be done using lambda function. Here I am reading the data from a xlsx file.
import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df
Output:
cluster Unnamed: 1 date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
Sum two columns into 3rd new one.
df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df
Output:
cluster Unnamed: 1 date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:
<style>
#container {
position: relative;
height: 100%;
}
#footer {
position: absolute;
bottom: 0;
}
</style>
</HEAD>
<BODY>
<div id="container">
<h1>Some heading</h1>
<p>Some text you have</p>
<br>
<br>
<div id="footer"><p>Rights reserved</p></div>
</div>
</BODY>
</HTML>
The trick is in <br>
where you break new line. So, when page is small you'll see footer at bottom of page, as you want.
BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.
Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview
Below are the descriptions of different keystores from the post:
JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.
JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.
PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.
You must create a MySQL database first. Then go to settings.py
file and edit the 'DATABASES'
dictionary with your MySQL credentials:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'YOUR_DATABASE_NAME',
'USER': 'YOUR_MYSQL_USER',
'PASSWORD': 'YOUR_MYSQL_PASS',
'HOST': 'localhost', # Or an IP that your DB is hosted on
'PORT': '3306',
}
}
Here is a complete installation guide for setting up Django to use MySQL on a virtualenv:
http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/
There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
As per my answer here, it is also possible to use a table head (which can be empty) and apply relative widths for each table head cell. The widths of all cells in the table body will conform to the width of their column head. Example:
HTML
<table>
<thead>
<tr>
<th width="5%"></th>
<th width="70%"></th>
<th width="15%"></th>
<th width="10%"></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Some text...</td>
<td>May 2018</td>
<td>Edit</td>
</tr>
<tr>
<td>2</td>
<td>Another text...</td>
<td>April 2018</td>
<td>Edit</td>
</tr>
</tbody>
</table>
CSS
table {
width: 600px;
border-collapse: collapse;
}
td {
border: 1px solid #999999;
}
Alternatively, use colgroup
as suggested in Hyathin's answer.
When you trying to call setDate you must provide valid javascript Date object.
queryDate = '2009-11-01';
var parsedDate = $.datepicker.parseDate('yy-mm-dd', queryDate);
$('#datePicker').datepicker('setDate', parsedDate);
This will allow you to use different formats for query date and string date representation in datepicker. This approach is very helpful when you create multilingual site. Another helpful function is formatDate, which formats javascript date object to string.
$.datepicker.formatDate( format, date, settings );
This is my first post which support only a single page http://www.techumber.com/html-to-pdf-conversion-using-javascript/
Now, the second one will support the multiple pages. http://www.techumber.com/how-to-convert-html-to-pdf-using-javascript-multipage/
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
I sometimes use getattr(..)
to lazily initialise attributes of secondary importance just before they are used in the code.
Compare the following:
class Graph(object):
def __init__(self):
self.n_calls_to_plot = 0
#...
#A lot of code here
#...
def plot(self):
self.n_calls_to_plot += 1
To this:
class Graph(object):
def plot(self):
self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)
The advantage of the second way is that n_calls_to_plot
only appears around the place in the code where it is used. This is good for readability, because (1) you can immediately see what value it starts with when reading how it's used, (2) it doesn't introduce a distraction into the __init__(..)
method, which ideally should be about the conceptual state of the class, rather than some utility counter that is only used by one of the function's methods for technical reasons, such as optimisation, and has nothing to do with the meaning of the object.
Approaches 1 and 2 obviously don't work, because you get java.sql.Date
objects, per JPA/Hibernate spec, and not java.util.Date
. From approaches 3 and 4, I would rather choose the latter one, because it's more declarative, and will work with both field and getter annotations.
You have already laid out the solution 4 in your referenced blog post, as @tscho was kind to point out. Maybe defaultForType (see below) should give you the centralized solution you were looking for. Of course will will still need to differentiate between date (without time) and timestamp fields.
For future reference I will leave the summary of using your own Hibernate UserType here:
To make Hibernate give you java.util.Date
instances, you can use the @Type and @TypeDef annotations to define a different mapping of your java.util.Date java types to and from the database.
See the examples in the core reference manual here.
TimestampAsJavaUtilDateType
Add a @TypeDef annotation on one entity or in a package-info.java - both will be available globally for the session factory (see manual link above). You can use defaultForType to apply the type conversion on all mapped fields of type java.util.Date
.
@TypeDef
name = "timestampAsJavaUtilDate",
defaultForType = java.util.Date.class, /* applied globally */
typeClass = TimestampAsJavaUtilDateType.class
)
Optionally, instead of defaultForType
, you can annotate your fields/getters with @Type individually:
@Entity
public class MyEntity {
[...]
@Type(type="timestampAsJavaUtilDate")
private java.util.Date myDate;
[...]
}
P.S. To suggest a totally different approach: we usually just don't compare Date objects using equals() anyway. Instead we use a utility class with methods to compare e.g. only the calendar date of two Date instances (or another resolution such as seconds), regardless of the exact implementation type. That as worked well for us.
Quick tip: !obj.blank? == obj.present?
Can be handy/easier on the eyes in some expressions
Subset is your safest and easiest answer.
subset(dataframe, A==B & E!=0)
Real data example with mtcars
subset(mtcars, cyl==6 & am!=0)
Sure! You can remove blue border also from all HTML elements using *
*{
outline-color: transparent;
outline-style: none;
}
And
*{
outline: none;
}
The _stats command provides ways to customize the results by specifying the metrics wished. To get the indices the query is as follows:
GET /_stats/indices
The general format of the _stats
query is:
/_stats
/_stats/{metric}
/_stats/{metric}/{indexMetric}
/{index}/_stats
/{index}/_stats/{metric}
Where the metrics are:
indices, docs, store, indexing, search, get, merge,
refresh, flush, warmer, filter_cache, id_cache,
percolate, segments, fielddata, completion
As an exercice to myself, I've written a small elasticsearch plugin providing the functionality to list elasticsearch indices without any other information. You can find it at the following url:
http://blog.iterativ.ch/2014/04/11/listindices-writing-your-first-elasticsearch-java-plugin/
DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = dateadd(mm, -1, getdate())
SET @StartDate = dateadd(dd, datepart(dd, getdate())*-1, @StartDate)
SET @EndDate = dateadd(mm, 1, @StartDate)
set @StartDate = DATEADD(dd, 1 , @StartDate)
You can use stepi
or nexti
(which can be abbreviated to si
or ni
) to step through your machine code.
Changing the property to an empty string appears to do the job:
$.css("background-color", "");
With Pylint 2.4 and above you can differentiate between the various missing-docstring
by using the three following sub-messages:
C0114
(missing-module-docstring
)C0115
(missing-class-docstring
)C0116
(missing-function-docstring
)So the following .pylintrc
file should work:
[MASTER]
disable=
C0114, # missing-module-docstring
I ended up using this:
$('.selectAll').toggle(function() {
$(this).select();
}, function() {
$(this).unselect();
});
If you find any ... let me know!
Seriously, as Josh Smith points out in this post, it's amazing there isn't a CodePlex community or something for this. Heck, it is amazing that there aren't more for purchase!
The only one that I have found (for sale) is reuxables. A little pricey, if you ask me, but you do get 9 themes/61 variations.
After I posted my answer, I thought, heck, I should go see if any CodePlex project exists for this already. I didn't find any specific project just for themes, but I did discover the WPF Contrib project ... which does have 1 theme that they never released.
Rudi Grobler (above) just created CodePlex community for this ... starting with converted themes he mentions above. See his blog post for more info. Way to go Rudi!
As another answer below has mentioned, since this question and my answer were written, the WPF Toolkit has incorporated some free themes, in particular, the themes from the Silverlight Toolkit. Rudi's project goes a little further and adds several more ... but depending on your situation, the WPF Toolkit might be all you need (and you might be installing it already).
You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.
The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException
.
This also works
String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
logFileName = "loggerFile_" + logFileName;
This is Daria
's suggestion (see comment on the question) which works starting from TypeScript 2.1 and basically clones each element from the array:
this.clonedArray = theArray.map(e => ({ ... e }));
Setting selected option is very simple in laravel form :
{{ Form::select('number', [0, 1, 2], 2) }}
Output will be :
<select name="number">
<option value="0">0</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
</select>