You can use sort.Slice()
plus sort.Search()
type Person struct {
Name string
}
func main() {
crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}
sort.Slice(crowd, func(i, j int) bool {
return crowd[i].Name <= crowd[j].Name
})
needle := "Benni"
idx := sort.Search(len(crowd), func(i int) bool {
return string(crowd[i].Name) >= needle
})
if crowd[idx].Name == needle {
fmt.Println("Found:", idx, crowd[idx])
} else {
fmt.Println("Found noting: ", idx)
}
}
A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection. An established connection is uniquely identified by the combination of client-side and server-side IP/Port pairs. Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.
On the client-side, it is common practice for new outbound connections to use a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.
SET UP THE REPOSITORY
For Ubuntu 14.04/16.04/16.10/17.04:
sudo add-apt-repository "deb [arch=amd64] \
https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
For Ubuntu 17.10:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"
Add Docker’s official GPG key:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
Then install
$ sudo apt-get update && sudo apt-get -y install docker-ce
Wildcards worked for me when the string I was searching for could be entered manually. However, I wanted to store this string in another cell and refer to it. I couldn't figure out how to do this with wildcards so I ended up doing the following:
A1 is the cell containing my search string. B and C are the columns within which I want to count the number of instances of A1, including within strings:
=COUNTIF(ARRAYFORMULA(ISNUMBER(SEARCH(A1, B:C))), TRUE)
http://neo4j.org/ is a graph database that contains many of graph algorithms and scales better than most in-memory libraries.
You might want to do one of the following:
Several libraries let you do that easily. Example below is written using my NoException library.
// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));
// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));
// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
Actually, they are different:
$('#GridName').data('kendoGrid').dataSource.read()
refreshes the uid
attributes of the table row
$('#GridName').data('kendoGrid').refresh()
leaves the same uid
#include <stdio.h>
#include <stdlib.h>
int func(char a, char b, char c) /* demonstration that char on stack is promoted to int !!!
note: this promotion is NOT integer promotion, but promotion during handling of the stack. don't confuse the two */
{
const char *p = &a;
printf("a=%d\n"
"b=%d\n"
"c=%d\n", *p, p[-(int)sizeof(int)], p[-(int)sizeof(int) * 2]); // don't do this. might probably work on x86 with gcc (but again: don't do this)
}
int main(void)
{
func(1, 2, 3);
//printf with %d treats its argument as int (argument must be int or smaller -> works because of conversion to int when on stack -- see demo above)
printf("%d, %d, %d\n", (long long) 1, 2, 3); // don't do this! Argument must be int or smaller type (like char... which is converted to int when on the stack -- see above)
// backslash followed by number is a oct VALUE
printf("%d\n", '\377'); /* prints -1 -> IF char is signed char: char literal has all bits set and is thus value -1.
-> char literal is then integer promoted to int. (this promotion has nothing to do with the stack. don't confuse the two!!!) */
/* prints 255 -> IF char is unsigned char: char literal has all bits set and is thus value 255.
-> char literal is then integer promoted to int */
// backslash followed by x is a hex VALUE
printf("%d\n", '\xff'); /* prints -1 -> IF char is signed char: char literal has all bits set and is thus value -1.
-> char literal is then integer promoted to int */
/* prints 255 -> IF char is unsigned char: char literal has all bits set and is thus value 255.
-> char literal is then integer promoted to int */
printf("%d\n", 255); // prints 255
printf("%d\n", (char)255); // prints -1 -> 255 is cast to char where it is -1
printf("%d\n", '\n'); // prints 10 -> Ascii newline has VALUE 10. The char 10 is integer promoted to int 10
printf("%d\n", sizeof('\n')); // prints 4 -> Ascii newline is char, but integer promoted to int. And sizeof(int) is 4 (on many architectures)
printf("%d\n", sizeof((char)'\n')); // prints 1 -> Switch off integer promotion via cast!
return 0;
}
for php7 you can do that:
sudo apt-get install php-gd php-xml php7.0-mbstring
after a few days of wondering, my solution was that I forgot to use @Test annotation before the @BeforeEach
Code:
private static void RegisterServices(IKernel kernel)
{
Mock<IProductRepository> mock=new Mock<IProductRepository>();
mock.Setup(x => x.Products).Returns(new List<Product>
{
new Product {Name = "Football", Price = 23},
new Product {Name = "Surf board", Price = 179},
new Product {Name = "Running shose", Price = 95}
});
kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}
but see exception.
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.
For example, if I have an array of objects I can do things like this:
# `sort!` modifies array in place, avoids duplicating if it's large...
# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }
# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }
# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }
# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
8 * (a.zip <=> b.zip) +
-4 * (a.age <=> b.age) +
2 * (a.last <=> b.last) +
(a.first <=> b.first)
end
This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.
Add PresentationCore.dll
to your references. This dll url in my pc - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\PresentationCore.dll
It says it all IsNullOrEmpty()
does not include white spacing while IsNullOrWhiteSpace()
does!
IsNullOrEmpty()
If string is:
-Null
-Empty
IsNullOrWhiteSpace()
If string is:
-Null
-Empty
-Contains White Spaces Only
Another solution is to use the config file without any settings. The first time you might have to include your mysql root login/password so it can install all its stuff but then remove it.
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysql';
Leaving it like that without any apache/lighhtpd aliases will just present to you a log in screen.
You can log in with root but it is advised to create other users and only allow root for local access. Also remember to use string passwords, even if short but with a capital, and number of special character. for example !34sy2rmbr!
aka "easy 2 remember"
-EDIT: A good password now a days is actually something like words that make no grammatical sense but you can remember because they funny. Or use keepass to generate strong randoms an have easy access to them
A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.
man -k <your search term>
What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)
That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:
man -k find | egrep '\(1\)'
or, if you also want to look for commands that require higher privilege levels, like this:
man -k find | egrep '\([18]\)'
This should do it:
for (var i = 0; i < bank_holidays.length; i++) {
if (bank_holidays[i] === '06/04/2012') {
alert('LOL');
}
}
elm.replaceChildren()
It's experimental without wide support, but when executed with no params will do what you're asking for, and it's more efficient than looping through each child and removing it. As mentioned already, replacing innerHTML with an empty string will require HTML parsing on the browser's part.
Documentation here.
"1" + "2" + "3"
or
["1", "2", "3"].join("")
The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string (""
).
parseInt("123")
Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)
123 + 100
(223).toString()
(parseInt("1" + "2" + "3") + 100).toString()
or
(parseInt(["1", "2", "3"].join("")) + 100).toString()
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.
For parsing command line arguments on posix systems, the standard is to use the getopt()
family of library routines to handle command line arguments.
A good reference is the GNU getopt manual
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations
(to the left of ) and going to the Edit Configurations
. A
gif provided for clarity.
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal
function if you are comparing values of type []byte
.
func testEq(a, b []Type) bool {
// If one is nil, the other must also be nil.
if (a == nil) != (b == nil) {
return false;
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
You can use ReactChildren
and ReactChild
:
import React, { ReactChildren, ReactChild } from 'react';
interface AuxProps {
children: ReactChild | ReactChildren;
}
const Aux = ({ children }: AuxProps) => (<div>{children}</div>);
export default Aux;
If you need to pass flat arrays of elements:
interface AuxProps {
children: ReactChild | ReactChild[] | ReactChildren | ReactChildren[];
}
If you are not using Proxy and still facing this issue, you should use below answer -
git config --global --unset http.proxy
Simply hit this command, and this will fix the issue.
Sync:
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('file', 'utf8'));
Async:
var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
You should use thenReturn
or doReturn
when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.
thenReturn(T value)
Sets a return value to be returned when the method is called.
@Test
public void test_return() throws Exception {
Dummy dummy = mock(Dummy.class);
int returnValue = 5;
// choose your preferred way
when(dummy.stringLength("dummy")).thenReturn(returnValue);
doReturn(returnValue).when(dummy).stringLength("dummy");
}
Answer
is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.
Use
doAnswer()
when you want to stub a void method with genericAnswer
.Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
@Test
public void test_answer() throws Exception {
Dummy dummy = mock(Dummy.class);
Answer<Integer> answer = new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
String string = invocation.getArgumentAt(0, String.class);
return string.length() * 2;
}
};
// choose your preferred way
when(dummy.stringLength("dummy")).thenAnswer(answer);
doAnswer(answer).when(dummy).stringLength("dummy");
}
You could use the Chr(int) function
REM setting current_schema is required as the 2nd query depends on the current user referred in the session
ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;
SELECT table_name,
TO_NUMBER (
EXTRACTVALUE (
xmltype (
DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
'/ROWSET/ROW/C'))
COUNT
FROM dba_tables
WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;
The size in bits of long
on Windows platforms is 32 bits (4 bytes).
You can check this using sizeof(long)
.
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
This is the reply I received from Github when I asked them to delete a pull request:
"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."
You could use the :first-child and :last-child pseudo-selectors
:
tr td:first-child{
color:red;
}
tr td:last-child {
color:green
}
Or you can use other way like
// To first child
tr td:nth-child(1){
color:red;
}
// To last child
tr td:nth-last-child(1){
color:green;
}
Both way are perfectly working
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
Personally I preferred to insert a 1. *
at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0
like 20.0
. And in my case, wrapping with a float()
may lose a little bit readability.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
There are two reasons you could want to use a tree:
You want to mirror the problem using a tree-like structure:
For this we have boost graph library
Or you want a container that has tree like access characteristics For this we have
std::map
(and std::multimap
)std::set
(and std::multiset
)Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).
See also this question: C tree Implementation
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
Similar to Jakub's answer, this allows you to easily select consecutive commits to revert.
# revert all commits from B to HEAD, inclusively
$ git revert --no-commit B..HEAD
$ git commit -m 'message'
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
Check out eval:
x = 1
print eval('x+1')
->2
Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error
<bean class="com.demo.dao.RailwayDao"></bean>
<bean class="com.demo.service.RailwayService"></bean>
<bean class="com.demo.model.RailwayReservation"></bean>
Run SDK Manager as Admin will solve your problem
I was based off Nate's solution, but then i found it that this causes problems when you use the leftView/rightView properties, so its better tune the super's implementation, because it will take the left/right view's into account.
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect ret = [super textRectForBounds:bounds];
ret.origin.x = ret.origin.x + 5;
ret.size.width = ret.size.width - 10;
return ret;
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!
The longer answer:
The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.
If you must modify the old list, simply collect the mapped items into a fresh list:
final List<Integer> newList = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
and then do list.addAll(newList)
— again: if you really must.
(or construct a new list concatenating the old one and the new one, and assign it back to the list
variable—this is a little bit more in the spirit of FP than addAll
)
As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.
The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)
To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.
If you have to display the field on report header then try this... RightClick on Textbox > Properties > Category > date > select *Format (Note this will maintain the regional settings).
Since this question has been viewed many times, I'm posting it... Hope it helps.
You might also try:
background-size: cover;
There are some good articles to read about using this CSS3 property: Perfect Full Page Background Image by CSS-Tricks and CSS Background-Size by David Walsh.
PLEASE NOTE - This will not work with IE8-. However, it will work on most versions of Chrome, Firefox and Safari.
hostname
also works just fine in Powershell
try:
git ls-files --error-unmatch <file name>
will exit with 1 if file is not tracked
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
Check that you included the script in header and not in footer of the page. Particularly in WordPress this one didn't work:
wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js', array(), false, true);
The last parameter indicates including the script in footer and needed to be changed to false (default). The way it worked:
wp_register_script('cookie', get_template_directory_uri() . '/js/jquery.cookie.js');
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
function setValToAssessment(id)
{
$.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
{
var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm');
$.each(response,function(key,value){
$("<input type='text' value='"+value+"' >")
.attr("id", key)
.attr("name", key)
.appendTo("form");
});
$('#hiddenForm').appendTo('body').submit();
// window.location.href = "<?=URL.$param->module?>/assessment";
});
}
Tilde expansion in Bash:
http://bash-hackers.org/wiki/doku.php/syntax/expansion/tilde
For setting the input type for an EditText programmatically, you have to specify that input class type is text.
editPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char*
arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.
Use cast:
(char*)const_char_ptr
Open the build gradle module app file and add your dependency. If you download the library, just import and build as gradle.
Otherwise add repositories in side gradle module app:
repositories {
maven { url 'http://clinker.47deg.com/nexus/content/groups/public' }
}
The first repositories will download the library for you.
And compile the downloaded library:
compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT@aar') {
transitive = true
}
If you are creating a library, you just need to import the project as import new module.
Try this
var myarray = ["item 1", "item 2", "item 3", "item 4"];
//removes the first element of the array, and returns that element apart from item 1.
myarray.shift();
console.log(myarray);
I am using Asp.Net WebForm and just I wanna to download a file from server side. There is a lot article but I cannot find just basic answer. Now, I tried a basic way and got it.
That's my problem.
I have to create a lot of input button dynamically on runtime. And I want to add each button to download button with giving an unique fileNumber.
I create each button like this:
fragment += "<div><input type=\"button\" value=\"Create Excel\" onclick=\"CreateExcelFile(" + fileNumber + ");\" /></div>";
_x000D_
Each button call this ajax method.
$.ajax({_x000D_
type: 'POST',_x000D_
url: 'index.aspx/CreateExcelFile',_x000D_
data: jsonData,_x000D_
contentType: 'application/json; charset=utf-8',_x000D_
dataType: 'json',_x000D_
success: function (returnValue) {_x000D_
window.location = '/Reports/Downloads/' + returnValue.d;_x000D_
}_x000D_
});
_x000D_
Then I wrote a basic simple method.
[WebMethod]
public static string CreateExcelFile2(string fileNumber)
{
string filePath = string.Format(@"Form_{0}.xlsx", fileNumber);
return filePath;
}
I am generating this Form_1, Form_2, Form_3.... And I am going to delete this old files with another program. But if there is a way to just sending byte array to download file like using Response. I wanna to use it.
I hope this will be usefull for anyone.
I'll add 2 points:
So, the 2 expressions are simply not equal.
WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
(
some_col = 1 OR
some_col = 2 OR
some_col = 3 OR
some_col = 4 OR
some_col = 5
)
AND
some_other_expr
So, when you break the IN clause up, you split the serial ORs up, and changed precedence.
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
I've found this one useful. Because if the recursion it can print nested tables too. It doesn't give the prettiest formatting in the output but for such a simple function it's hard to beat for debugging.
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
e.g.
local people = {
{
name = "Fred",
address = "16 Long Street",
phone = "123456"
},
{
name = "Wilma",
address = "16 Long Street",
phone = "123456"
},
{
name = "Barney",
address = "17 Long Street",
phone = "123457"
}
}
print("People:", dump(people))
Produces the following output:
People: { [1] = { ["address"] = 16 Long Street,["phone"] = 123456,["name"] = Fred,} ,[2] = { ["address"] = 16 Long Street,["phone"] = 123456,["name"] = Wilma,} ,[3] = { ["address"] = 17 Long Street,["phone"] = 123457,["name"] = Barney,} ,}
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.
Help on function resource in module boto3:
resource(*args, **kwargs)
Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`.
https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265
you can see that it just takes the same arguments as Boto3.Session
import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()
The complete list of the regexp_like and other regexp functions in Oracle 11.1:
http://66.221.222.85/reference/regexp.html
In your example:
SELECT X
FROM test
WHERE REGEXP_LIKE(X, '^[[:digit:]]$');
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
It's better to use the actual (msi) installer from nodejs.org instead of downloading the node executable only. The installer includes npm and makes it easier to manage your node installation. There is an installer for both 32-bit and 64-bit Windows.
Also a couple of other tidbits:
Installing modules globally doesn't do what you might expect. The only modules you should install globally (the -g
flag in npm) are ones that install commands. So to install Express you would just do npm install express
and that will install Express to your current working directory. If you were instead looking for the Express project generator (command), you need to do npm install -g express-generator
for Express 4.
You can use node anywhere from your command prompt to execute scripts. For example if you have already written a separate script: node foo.js
. Or you can open up the REPL (as you've already found out) by just selecting the node.js (start menu) shortcut or by just typing node
in a command prompt.
You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()
FUNCTIONAL REQUIREMENTS the activities the system must perform
Gson 1.6 now includes a low-level streaming API and a new parser which is actually faster than Jackson.
Based on official documentation https://developer.android.com/studio/command-line/variables.html you should change ANDROID_AVD_HOME environment var:
Emulator Environment Variables
By default, the emulator stores configuration files under $HOME/.android/ and AVD data under $HOME/.android/avd/. You can override the defaults by setting the following environment variables. The emulator -avd command searches the avd directory in the order of the values in $ANDROID_AVD_HOME, $ANDROID_SDK_HOME/.android/avd/, and $HOME/.android/avd/. For emulator environment variable help, type emulator -help-environment at the command line. For information about emulator command-line options, see Control the Emulator from the Command Line.
- ANDROID_EMULATOR_HOME: Sets the path to the user-specific emulator configuration directory. The default location is
$ANDROID_SDK_HOME/.android/.- ANDROID_AVD_HOME: Sets the path to the directory that contains all AVD-specific files, which mostly consist of very large disk images. The default location is $ANDROID_EMULATOR_HOME/avd/. You might want to specify a new location if the default location is low on disk space.
After change or set ANDROID_AVD_HOME you will have to move all content inside ~user/.android/avd/ to your new location and change path into ini file of each emulator, just replace it with your new path
A simple, fast way to get the content by id :
echo get_post_field('post_content', $id);
And if you want to get the content formatted :
echo apply_filters('the_content', get_post_field('post_content', $id));
Works with pages, posts & custom posts.
public class SwingExample implements Runnable {
@Override
public void run() {
// Create the window
final JFrame f = new JFrame("Hello, World!");
SwingExample.centerWindow(f);
f.setPreferredSize(new Dimension(500, 250));
f.setMaximumSize(new Dimension(10000, 200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void centerWindow(JFrame frame) {
Insets insets = frame.getInsets();
frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
frame.setVisible(true);
frame.setResizable(false);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
}
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
Background image is not supported in Outlook. You have to use an image and position it behind the text using position relative or absolute.
there's also ndisasm, which has some quirks, but can be more useful if you use nasm. I agree with Michael Mrozek that objdump is probably best.
[later] you might also want to check out Albert van der Horst's ciasdis: http://home.hccnet.nl/a.w.m.van.der.horst/forthassembler.html. it can be hard to understand, but has some interesting features you won't likely find anywhere else.
I think problem is in
3 + ', ' + 4
change it to
'3' + ', ' + '4'
DECLARE @ExcludedList VARCHAR(MAX)
SET @ExcludedList = '3' + ', ' + '4' + ' ,' + '22'
SELECT * FROM A WHERE Id NOT IN (@ExcludedList)
SET @ExcludedListe such that your query should become
either
SELECT * FROM A WHERE Id NOT IN ('3', '4', '22')
or
SELECT * FROM A WHERE Id NOT IN (3, 4, 22)
Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so
import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')
to yield,
0 58
1 3
2 8
dtype: float64
var classname=$('#div1').attr('class')
You don't need complicated algorithms.
Just one simple line:
Random random = new Random();
array.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();
Note that we need to convert the Array
to a List
first, if you don't use List
in the first place.
Also, mind that this is not efficient for very large arrays! Otherwise it's clean & simple.
You can use this function :
send_static_file(filename)
Function used internally to send static files from the static folder to the browser.
app = Flask(__name__)
@app.route('/<path:path>')
def static_file(path):
return app.send_static_file(path)
In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.
Please post the warning message, we can try help you further.
The following works for me:
class Fruits: pass
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
import pickle
filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()
file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()
print(object_file.color, object_file.value, sep=', ')
# yellow, 30
git checkout -b your-new-branch
git add <files>
git commit -m <message>
First, checkout your new branch. Then add all the files you want to commit to staging.
Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch
afterward so your changes show up on the remote.
When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).
function login(accessedViaPopup) {
//pass FB.login a call back function wrapper that will accept the
//response param and then call my "real" callback with the additional param
FB.login(function(response){
fb_login_callback(response,accessedViaPopup);
});
}
//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
//do stuff
}
Is it timer
?
For WIN32 try http://msdn.microsoft.com/en-us/library/ms687012%28VS.85%29.aspx
Use reqclient: not designed for scripting purpose
like request
or many other libraries. Reqclient allows in the constructor
specify many configurations useful when you need to reuse the same
configuration again and again: base URL, headers, auth options,
logging options, caching, etc. Also has useful features like
query and URL parsing, automatic query encoding and JSON parsing, etc.
The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:
Module client.js
:
let RequestClient = require("reqclient").RequestClient
let client = new RequestClient({
baseUrl: "https://myapp.com/api/v1",
cache: true,
auth: {user: "admin", pass: "secret"}
})
module.exports = client
And in the controllers where you need to consume the API use like this:
let client = require('client')
//let router = ...
router.get('/dashboard', (req, res) => {
// Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
client.get("reports/clients")
.then(response => {
console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
res.render('clients/dashboard', {title: 'Customer Report', report: response})
})
.catch(err => {
console.error("Ups!", err)
res.status(400).render('error', {error: err})
})
})
router.get('/orders', (req, res, next) => {
// GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
.then(orders => {
res.render('clients/orders', {title: 'Customer Orders', orders: orders})
})
.catch(err => someErrorHandler(req, res, next))
})
router.delete('/orders', (req, res, next) => {
// DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
client.delete({
"uri": "orders/{client}/{id}",
"params": {"client": "A987", "id": 1234}
})
.then(resp => res.status(204))
.catch(err => someErrorHandler(req, res, next))
})
reqclient
supports many features, but it has some that are not supported by other
libraries: OAuth2 integration and logger integration
with cURL syntax, and always returns native Promise objects.
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
Firstly uninstall Android Studio from control panel using program and features. Later you also need to enable displaying of hidden files and folders and delete the following:
users/${yourUserName}/appData/Local/Android
In Oracle 12c and above, we have two types of databases:
If you want to create an user, you have two possibilities:
You can create a "container user" aka "common user".
Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.
create user c##username identified by password;
You can create a "pluggable user" aka "local user".
Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:
alter session set container = nameofyourpluggabledatabase;
and there, you can create user like usually:
create user username identified by password;
Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503
The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if
is a statement, it cannot return a value.
git clone your-url local-dir
to checkout source code;
git pull
to update source code in local-dir;
As radio button mostly used in group, its a lot easier to grab them by getElementsByName( ' ' );
in your script tag. This will return an array, put an event listener on each array child and set the check state. Look at this sample.
var myRadios = document.getElementsByName('subscribe');
var setCheck;
var x = 0;
for(x = 0; x < myRadios.length; x++){
myRadios[x].onclick = function(){
if(setCheck != this){
setCheck = this;
}else{
this.checked = false;
setCheck = null;
}
};
}
This guide explain how the code works with a visual demonstration.
They have a very good answer here: https://stackoverflow.com/a/32455275/165865
Just run below images:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t
public byte UserType
public string SelectUserType
You need to get one and set different one. Selected value can not be the same item that you are about to set.
@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))
I use Enum dictionary for my list, that's why there is "key", "value" pair.
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
what about this
<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
<input type="submit" name="submit" id="submit" value="Email"/>
</FORM>
This worked for me, even within a div:
div.cntrblk tr:hover td {
line-height: 150%;
background-color: rgb(255,0,0);
font-weight: bold;
font-size: 150%;
border: 0;
}
It selected the entire row, but I'd like it to not do the header, haven't looked at that yet. It also partially fixed the fonts that wouldn't scale-up with the hover??? Apparently you to have apply settings to the cell not the row, but select all the component cells with the tr:hover. On to tracking down the in-consistent font scaling problem. Sweet that CSS will do this.
use curl php library: http://php.net/manual/en/book.curl.php
direct example: CURL_EXEC:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
It might also be (which was the case for my colleague) that you have disabled automatic loading of symbols for whichever reason.
If so, reenable it by opening Tools -> Options -> Debugging -> Symbols
and move the radiobutton to "Load all modules, unless excluded"
It's not quite what you asked for, but
git log --graph --simplify-by-decoration --pretty=format:'%d' --all
does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration
is the big trick here for limiting the refs shown.
I use a similar command to view my log. I've been able to completely replace my gitk
usage with it:
git log --graph --oneline --decorate --all
I use it by including these aliases in my ~/.gitconfig file:
[alias]
l = log --graph --oneline --decorate
ll = log --graph --oneline --decorate --branches --tags
lll = log --graph --oneline --decorate --all
Edit: Updated suggested log command/aliases to use simpler option flags.
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Try to use (focus)
and (focusout)
instead of onfocus
and onfocusout
like this : -
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
also you can use like this :-
some people prefer the on- prefix alternative, known as the canonical form:
<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">
Know more about event binding see here.
you have to use HostListner for your use case
Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
is a decorator for the callback/event handler method
See my Update working Plunker.
Working Example Working Stackblitz
Some other events can be used in angular -
(focus)="myMethod()"
(blur)="myMethod()"
(submit)="myMethod()"
(scroll)="myMethod()"
The error string is quite simply exactly what libcurl sees: since it is receiving a chunked encoding stream it knows when there is data left in a chunk to receive. When the connection is closed, libcurl knows that the last received chunk was incomplete. Then you get this error code.
There's nothing you can do to avoid this error with the request unmodified, but you can try to work around it by issuing a HTTP 1.0 request instead (since chunked encoding won't happen then) but the fact is that this is most likely a flaw in the server or in your network/setup somehow.
Too late to respond. But, if this helps someone who is still facing the issue. I got this fixed by:
? Set site on dedicated pool instead of shared one.
? Enable 32 bit application support.
? Set identity of the application pool to LocalSystem.
On Mac, if you have multiple GitHub logins and are not using SSH, force the correct login by using:
git remote set-url origin https://[email protected]/username/repo-name.git
This also works if you're having issues pushing to a private repository.
How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).
/*
Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";
@each $i in $social {
[data-social="#{$i}"] {
background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
background-size: cover; // Only seems to work if placed below background property
}
}
Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.
Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.
It is access_type=offline
that you want.
This will return the refresh token the first time the user authorises the app. Subsequent calls do not force you to re-approve the app (approval_prompt=force
).
See further detail: https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
If you want the overflow to wrap: flex-flow: row wrap
You can call net start "service name"
on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.
The current best practice is to configure Jackson within the application.yml
(or properties
) file.
Example:
spring:
jackson:
property-naming-strategy: SNAKE_CASE
If you have more complex configuration requirements, you can also configure Jackson programmatically.
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new Jackson2ObjectMapperBuilder()
.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
// insert other configurations
}
}
Sadly accepted answer isn't working.
I'm late, but here's the solution for internal Android Email application unless the content uri is changed by provider:
Uri EMAIL_ACCOUNTS_DATABASE_CONTENT_URI =
Uri.parse("content://com.android.email.provider/account");
public ArrayList<String> GET_EMAIL_ADDRESSES ()
{
ArrayList<String> names = new ArrayList<String>();
ContentResolver cr = m_context.getContentResolver();
Cursor cursor = cr.query(EMAIL_ACCOUNTS_DATABASE_CONTENT_URI ,null,
null, null, null);
if (cursor == null) {
Log.e("TEST", "Cannot access email accounts database");
return null;
}
if (cursor.getCount() <= 0) {
Log.e("TEST", "No accounts");
return null;
}
while (cursor.moveToNext()) {
names.add(cursor.getString(cursor.getColumnIndex("emailAddress")));
Log.i("TEST", cursor.getString(cursor.getColumnIndex("emailAddress")));
}
return names;
}
Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app
, then IE will block all cookies and your session information will not be accessible between requests.
In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.
Further information: http://support.microsoft.com/kb/316112
I compiled some of the other answers into a single utility method:
public class TimeLimitedCodeBlock {
public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception {
runWithTimeout(new Callable<Object>() {
@Override
public Object call() throws Exception {
runnable.run();
return null;
}
}, timeout, timeUnit);
}
public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception {
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<T> future = executor.submit(callable);
executor.shutdown(); // This does not cancel the already-scheduled task.
try {
return future.get(timeout, timeUnit);
}
catch (TimeoutException e) {
//remove this if you do not want to cancel the job in progress
//or set the argument to 'false' if you do not want to interrupt the thread
future.cancel(true);
throw e;
}
catch (ExecutionException e) {
//unwrap the root cause
Throwable t = e.getCause();
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof Exception) {
throw (Exception) t;
} else {
throw new IllegalStateException(t);
}
}
}
}
Sample code making use of this utility method:
public static void main(String[] args) throws Exception {
final long startTime = System.currentTimeMillis();
log(startTime, "calling runWithTimeout!");
try {
TimeLimitedCodeBlock.runWithTimeout(new Runnable() {
@Override
public void run() {
try {
log(startTime, "starting sleep!");
Thread.sleep(10000);
log(startTime, "woke up!");
}
catch (InterruptedException e) {
log(startTime, "was interrupted!");
}
}
}, 5, TimeUnit.SECONDS);
}
catch (TimeoutException e) {
log(startTime, "got timeout!");
}
log(startTime, "end of main method!");
}
private static void log(long startTime, String msg) {
long elapsedSeconds = (System.currentTimeMillis() - startTime);
System.out.format("%1$5sms [%2$16s] %3$s\n", elapsedSeconds, Thread.currentThread().getName(), msg);
}
Output from running the sample code on my machine:
0ms [ main] calling runWithTimeout!
13ms [ pool-1-thread-1] starting sleep!
5015ms [ main] got timeout!
5016ms [ main] end of main method!
5015ms [ pool-1-thread-1] was interrupted!
It's your choice. There are basically three ways in a Java web application archive (WAR):
So that you can load it by ClassLoader#getResourceAsStream()
with a classpath-relative path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);
Here foo.properties
is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib
and /WEB-INF/classes
, server's /lib
, or JDK/JRE's /lib
. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes
. If you're developing a standard WAR project in an IDE, drop it in src
folder (the project's source folder). If you're using a Maven project, drop it in /main/resources
folder.
You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader
property of Tomcat/conf/catalina.properties
.
If you have placed the foo.properties
it in a Java package structure like com.example
, then you need to load it as below
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...
Note that this path of a context class loader should not start with a /
. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader()
, then you indeed need to start it with a /
.
ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...
However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.
So that you can load it by ServletContext#getResourceAsStream()
with a webcontent-relative path:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...
Note that I have demonstrated to place the file in /WEB-INF
folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext
is in any HttpServlet
class just accessible by the inherited GenericServlet#getServletContext()
and in Filter
by FilterConfig#getServletContext()
. In case you're not in a servlet class, it's usually just injectable via @Inject
.
So that you can load it the usual java.io
way with an absolute local disk file system path:
InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...
Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.
Just weigh the advantages/disadvantages in your own opinion of maintainability.
If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.
If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).
If you prefer being able to edit properties files programmatically from inside the web application using Properties#store()
method, put it outside the web application. As the Properties#store()
requires a Writer
, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath()
. All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
You can chain .fail()
callback for error response.
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
})
.fail(function() {
//Error logic
})
I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.
Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.
Just to expand on Daniel's solution, you can shorten things up tremendously by inserting the following import into any file which requires file manipulation:
import scala.io.Source._
With this, you can now do:
val lines = fromFile("file.txt").getLines
I would be wary of reading an entire file into a single String
. It's a very bad habit, one which will bite you sooner and harder than you think. The getLines
method returns a value of type Iterator[String]
. It's effectively a lazy cursor into the file, allowing you to examine just the data you need without risking memory glut.
Oh, and to answer your implied question about Source
: yes, it is the canonical I/O library. Most code ends up using java.io
due to its lower-level interface and better compatibility with existing frameworks, but any code which has a choice should be using Source
, particularly for simple file manipulation.
You need to encode your parameter's values before concatenating them to URL.
Backslash \
is special character which have to be escaped as %5C
Escaping example:
String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);
The result is http://host.com?param=param%5Cwith%5Cbackslash
which is properly formatted url string.
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
I just copied the META-INF into src and worked!
The solution below incorporates all of the suggestions here. It starts with what was originally posted by Dunni. It uses a binary search like gjpc's, but it is a bit more readable. It also include's gregm's bug fixes and a bug-fix of my own.
import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialise();
}
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialise();
}
private void initialise() {
mTestPaint = new Paint();
mTestPaint.set(this.getPaint());
//max size defaults to the initially specified text size unless it is too small
}
/* Re size the font so the specified text fits in the text box
* assuming the text box is the specified width.
*/
private void refitText(String text, int textWidth)
{
if (textWidth <= 0)
return;
int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
float hi = 100;
float lo = 2;
final float threshold = 0.5f; // How close we have to be
mTestPaint.set(this.getPaint());
while((hi - lo) > threshold) {
float size = (hi+lo)/2;
mTestPaint.setTextSize(size);
if(mTestPaint.measureText(text) >= targetWidth)
hi = size; // too big
else
lo = size; // too small
}
// Use lo so that we undershoot rather than overshoot
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();
refitText(this.getText().toString(), parentWidth);
this.setMeasuredDimension(parentWidth, height);
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}
//Attributes
private Paint mTestPaint;
}
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
Isn't your issue that you're setting the webkitAnimationName back to nothing so that's resetting the CSS for your object back to it's default state. Won't it stay where it ended up if you just remove the setTimeout function that's resetting the state?
See C++ FAQ Lite How do I convert a std::string to a number?
See C++ Super-FAQ How do I convert a std::string to a number?
Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.
// the requested function
#include <sstream>
double string_to_double( const std::string& s )
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
// some tests
#include <cassert>
int main( int, char** )
{
// simple case:
assert( 0.5 == string_to_double( "0.5" ) );
// blank space:
assert( 0.5 == string_to_double( "0.5 " ) );
assert( 0.5 == string_to_double( " 0.5" ) );
// trailing non digit characters:
assert( 0.5 == string_to_double( "0.5a" ) );
// note that with your requirements you can't distinguish
// all the the allowed string representation of zero from
// the non numerical strings:
assert( 0 == string_to_double( "0" ) );
assert( 0 == string_to_double( "0." ) );
assert( 0 == string_to_double( "0.0" ) );
assert( 0 == string_to_double( "0.00" ) );
assert( 0 == string_to_double( "0.0e0" ) );
assert( 0 == string_to_double( "0.0e-0" ) );
assert( 0 == string_to_double( "0.0e+0" ) );
assert( 0 == string_to_double( "+0" ) );
assert( 0 == string_to_double( "+0." ) );
assert( 0 == string_to_double( "+0.0" ) );
assert( 0 == string_to_double( "+0.00" ) );
assert( 0 == string_to_double( "+0.0e0" ) );
assert( 0 == string_to_double( "+0.0e-0" ) );
assert( 0 == string_to_double( "+0.0e+0" ) );
assert( 0 == string_to_double( "-0" ) );
assert( 0 == string_to_double( "-0." ) );
assert( 0 == string_to_double( "-0.0" ) );
assert( 0 == string_to_double( "-0.00" ) );
assert( 0 == string_to_double( "-0.0e0" ) );
assert( 0 == string_to_double( "-0.0e-0" ) );
assert( 0 == string_to_double( "-0.0e+0" ) );
assert( 0 == string_to_double( "foobar" ) );
return 0;
}
what platform are you running?..
if its unix, maybe adding
alias java='java -Xmx1g'
to .bashrc (or similar) work
edit: Changing XmX to Xmx
When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(
You can setup environment variables in your code as follows:
import sys,os,os.path
sys.path.append(os.path.expanduser('~/code/eol_hsrl_python'))
os.environ['HSRL_INSTRUMENT']='gvhsrl'
os.environ['HSRL_CONFIG']=os.path.expanduser('~/hsrl_config')
This if of course a temporary fix, to get a permanent one, you probably need to export the variables into your ~.profile
, more information can be found here
Simple like a piece of CAKE!
You can define a new column type like (L
in this case) while maintaining the current alignment (c
, r
or l
):
\documentclass{article}
\usepackage{array}
\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}
\begin{document}
\begin{table}
\begin{tabular}{|c|L|L|}
\hline
Title 1 & Title 2 & Title 3 \\
\hline
one-liner & multi-line and centered & \multicolumn{1}{m{3cm}|}{multi-line piece of text to show case a multi-line and justified cell} \\
\hline
apple & orange & banana \\
\hline
apple & orange & banana \\
\hline
\end{tabular}
\end{table}
\end{document}
based on other solutions, you generate accumulative distribution (as integer or float whatever you like), then you can use bisect to make it fast
this is a simple example (I used integers here)
l=[(20, 'foo'), (60, 'banana'), (10, 'monkey'), (10, 'monkey2')]
def get_cdf(l):
ret=[]
c=0
for i in l: c+=i[0]; ret.append((c, i[1]))
return ret
def get_random_item(cdf):
return cdf[bisect.bisect_left(cdf, (random.randint(0, cdf[-1][0]),))][1]
cdf=get_cdf(l)
for i in range(100): print get_random_item(cdf),
the get_cdf
function would convert it from 20, 60, 10, 10 into 20, 20+60, 20+60+10, 20+60+10+10
now we pick a random number up to 20+60+10+10 using random.randint
then we use bisect to get the actual value in a fast way
You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.
VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;
select * from dbMaster oMaster where ((CAST(GETDATE() as time)) between (CAST(oMaster.DateFrom as time)) and
(CAST(oMaster.DateTo as time)))
Please check this
Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serializeArray();
var formData = JSON.stringify(criteria);
serializeArray() will produce an array of names and values
0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serialize();
serialize() creates a text string in standard URL-encoded notation
"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/
Wrote this for one of my sites and probably is the most foolproof solution. Especially since even Modernizr can get false positives on touch detection.
If you're using jQuery
$(window).one({
mouseover : function(){
Modernizr.touch = false; // Add this line if you have Modernizr
$('html').removeClass('touch').addClass('mouse');
}
});
or just pure JS...
window.onmouseover = function(){
window.onmouseover = null;
document.getElementsByTagName("html")[0].className += " mouse";
}
I used the TryParse that @fjdumont mentioned but in the validating event instead.
private void Number_Validating(object sender, CancelEventArgs e) {
int val;
TextBox tb = sender as TextBox;
if (!int.TryParse(tb.Text, out val)) {
MessageBox.Show(tb.Tag + " must be numeric.");
tb.Undo();
e.Cancel = true;
}
}
I attached this to two different text boxes with in my form initializing code.
public Form1() {
InitializeComponent();
textBox1.Validating+=new CancelEventHandler(Number_Validating);
textBox2.Validating+=new CancelEventHandler(Number_Validating);
}
I also added the tb.Undo()
to back out invalid changes.
I find this approach useful:
Create click event:
$( button ).on('click', function(e) {
let id = e.node.data.id;
$('#myModal').modal('show', {id: id});
});
Create show.bs.modal event:
$('#myModal').on('show.bs.modal', function (e) {
// access parsed information through relatedTarget
console.log(e.relatedTarget.id);
});
Extra:
Make your logic inside show.bs.modal to check whether the properties are parsed, like for instance as this:
id: ( e.relatedTarget.hasOwnProperty( 'id' ) ? e.relatedTarget.id : null )
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
Add the following lines in "mongo.config" file
port=27017
dbpath=C:\mongodb\data\db\
logpath=C:\mongodb\log\mongo.log
Start server :
mongod.exe --config="C:\mongodb\mongo.config"
Connect to localhost MongoDB server via command line
mongo --port 27017
Connect to remote MongoDB server via command line with authentication.
mongo --username abcd --password abc123 --host server_ip_or_dns --port 27017
That's it !!!
img.centered {
display: block;
margin: auto auto;
}
private void UpdateFont()
{
//Change cell font
foreach(DataGridViewColumn c in dgAssets.Columns)
{
c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
}
}
You haven't accepted an answer, so here's what worked for me in PuTTY:
Without allowing username changes, i got this question's subject as error on the gateway machine.
This code is in groovy, so most likely you will need to do some rework. The first param is a url, the second is a counter to limit the tries.
public boolean selectWindow(window, maxTries) {
def handles
int tries = 0
while (true) {
try {
handles = driver.getWindowHandles().toArray()
for (int a = handles.size() - 1; a >= 0 ; a--) { // Backwards is faster with FF since it requires two windows
try {
Log.logger.info("Attempting to select window: " + window)
driver.switchTo().window(handles[a]);
if (driver.getCurrentUrl().equals(window))
return true;
else {
Thread.sleep(2000)
tries++
}
if (tries > maxTries) {
Log.logger.warn("Cannot select page")
return false
}
} catch (Exception ex) {
Thread.sleep(2000)
tries++
}
}
} catch (Exception ex2) {
Thread.sleep(2000)
tries++
}
}
return false;
}
Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.
When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger?
The Service is triggered by calling method startService()
.
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent()
is called on this thread.
Triggered From
Runs On
The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.
Limitations / Drawbacks
The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
When to stop?
If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf()
or stopService()
. (If you only want to provide binding, you don't need to implement this method).
The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf()
.
If you are the owner it is simple:
Settings
button.Collaborators
Then collaborator should visit this example repo link https://github.com/user/repo/invitations
Source: Github Docs.
If you are not sure if the call to "back" will exit the app, or will take the user to another activity, you can wrap the above answers in a check, isTaskRoot(). This can happen if your main activity can be added to the back stack multiple times, or if you are manipulating your back stack history.
if(isTaskRoot()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourActivity.super.onBackPressed;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
super.onBackPressed();
}
Is Powershell an option?
Start Powershell:
powershell
Create the VPN Connection: Add-VpnConnection
Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]
Edit VPN connections: Set-VpnConnection
Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]
Lookup VPN Connections: Get-VpnConnection
Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]
Connect: rasdial [connectionName]
rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]
You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial
.
The results of Get-VpnConnection
can be a little verbose. This can be simplified with a simple Select-Object
filter:
Get-VpnConnection | Select-Object -Property Name
More information can be found here:
This solution is (only) for SQL Server 2005
You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:
:
context.Database.SqlQuery<EntityType>(
"EXEC ProcName @param1, @param2",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2)
);
I took Nico Burns's answer and made it using jQuery:
div contentEditable="true"
You'll need jQuery 1.6 or higher:
savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
var s = window.getSelection();
var t = $('div[contenteditable="true"]').index(this);
if (typeof(savedRanges[t]) === "undefined"){
savedRanges[t]= new Range();
} else if(s.rangeCount > 0) {
s.removeAllRanges();
s.addRange(savedRanges[t]);
}
}).bind("mouseup keyup",function(){
var t = $('div[contenteditable="true"]').index(this);
savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
if(!$(this).is(":focus")){
e.stopPropagation();
e.preventDefault();
$(this).focus();
}
});
savedRanges = new Object();_x000D_
$('div[contenteditable="true"]').focus(function(){_x000D_
var s = window.getSelection();_x000D_
var t = $('div[contenteditable="true"]').index(this);_x000D_
if (typeof(savedRanges[t]) === "undefined"){_x000D_
savedRanges[t]= new Range();_x000D_
} else if(s.rangeCount > 0) {_x000D_
s.removeAllRanges();_x000D_
s.addRange(savedRanges[t]);_x000D_
}_x000D_
}).bind("mouseup keyup",function(){_x000D_
var t = $('div[contenteditable="true"]').index(this);_x000D_
savedRanges[t] = window.getSelection().getRangeAt(0);_x000D_
}).on("mousedown click",function(e){_x000D_
if(!$(this).is(":focus")){_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$(this).focus();_x000D_
}_x000D_
});
_x000D_
div[contenteditable] {_x000D_
padding: 1em;_x000D_
font-family: Arial;_x000D_
outline: 1px solid rgba(0,0,0,0.5);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>
_x000D_
thanks @balpha and @Kevin, I combine two method together.
no js needed in this method.
you can use background-image
and no gradient needed to hide dots.
the innerHTML
of .ellipsis-placeholder
is not necessary, I use .ellipsis-placeholder
to keep the same width and height with .ellipsis-more
.
You could use display: inline-block
instead.
.ellipsis {_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
}_x000D_
.ellipsis-more-top {/*push down .ellipsis-more*/_x000D_
content: "";_x000D_
float: left;_x000D_
width: 5px;_x000D_
}_x000D_
.ellipsis-text-container {_x000D_
float: right;_x000D_
width: 100%;_x000D_
margin-left: -5px;_x000D_
}_x000D_
.ellipsis-more-container {_x000D_
float: right;_x000D_
position: relative;_x000D_
left: 100%;_x000D_
width: 5px;_x000D_
margin-left: -5px;_x000D_
border-right: solid 5px transparent;_x000D_
white-space: nowrap;_x000D_
}_x000D_
.ellipsis-placeholder {/*keep text around ,keep it transparent ,keep same width and height as .ellipsis-more*/_x000D_
float: right;_x000D_
clear: right;_x000D_
color: transparent;_x000D_
}_x000D_
.ellipsis-placeholder-top {/*push down .ellipsis-placeholder*/_x000D_
float: right;_x000D_
width: 0;_x000D_
}_x000D_
.ellipsis-more {/*ellipsis things here*/_x000D_
float: right;_x000D_
}_x000D_
.ellipsis-height {/*the total height*/_x000D_
height: 3.6em;_x000D_
}_x000D_
.ellipsis-line-height {/*the line-height*/_x000D_
line-height: 1.2;_x000D_
}_x000D_
.ellipsis-margin-top {/*one line height*/_x000D_
margin-top: -1.2em;_x000D_
}_x000D_
.ellipsis-text {_x000D_
word-break: break-all;_x000D_
}
_x000D_
<div class="ellipsis ellipsis-height ellipsis-line-height">_x000D_
<div class="ellipsis-more-top ellipsis-height"></div>_x000D_
<div class="ellipsis-text-container">_x000D_
<div class="ellipsis-placeholder-top ellipsis-height ellipsis-margin-top"></div>_x000D_
<div class="ellipsis-placeholder">_x000D_
<span>...</span><span>more</span>_x000D_
</div>_x000D_
<span class="ellipsis-text">text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </span>_x000D_
</div>_x000D_
<div class="ellipsis-more-container ellipsis-margin-top">_x000D_
<div class="ellipsis-more">_x000D_
<span>...</span><span>more</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Express deprecated res.send(body, status)
.
Use res.status(status).send(body)
instead
Something like this:
if($('#postageyes').is(':checked')) {
// do stuff
}
In Ubuntu, set path of node_modules in .bashrc file
export PATH="/home/username/node_modules/.bin:$PATH"
public class Sam_Stringnth {
public static void main(String[] args) {
String str="abcabcabc";
int n = nthsearch(str, 'c', 3);
if(n<=0)
System.out.println("Character not found");
else
System.out.println("Position is:"+n);
}
public static int nthsearch(String str, char ch, int n){
int pos=0;
if(n!=0){
for(int i=1; i<=n;i++){
pos = str.indexOf(ch, pos)+1;
}
return pos;
}
else{
return 0;
}
}
}
Given there is only one (or with this solution potentially not even one) submit button, here is jQuery based solution that will work for multiple forms on the same page...
<script type="text/javascript">
$(document).ready(function () {
var makeAllFormSubmitOnEnter = function () {
$('form input, form select').live('keypress', function (e) {
if (e.which && e.which == 13) {
$(this).parents('form').submit();
return false;
} else {
return true;
}
});
};
makeAllFormSubmitOnEnter();
});
</script>
Bootstrap 2.3.2
<ul class="inline">
<li>...</li>
</ul>
Bootstrap 3
<ul class="list-inline">
<li>...</li>
</ul>
Bootstrap 4
<ul class="list-inline">
<li class="list-inline-item">Lorem ipsum</li>
<li class="list-inline-item">Phasellus iaculis</li>
<li class="list-inline-item">Nulla volutpat</li>
</ul>
source: http://v4-alpha.getbootstrap.com/content/typography/#inline
Updated link https://getbootstrap.com/docs/4.4/content/typography/#inline
The right solution would be if you have android studio installed then
Android SDK Tools (Obsolete)
flutter doctor
and it should now prompt you to run flutter doctor --android-licenses
once you run the license command accept all licenses by hitting y and it should solve the problemIEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.
IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };
use something like:
double step = 1d / 5;
(1d is a cast to double)
This should do the trick - setting the inline style to normal for zoom:
$('div').attr("style", "zoom:normal;");
$(document).ready( function() { YOUR CODE HERE } )
In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details
BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)
Means you should use like this :
Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)
So, it worked in MVC 4
@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
new { @id = "signupform" }))
{
<input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
<input type="submit" value="Create" id="btnSubmit" />
}
Replace
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
by
f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")
What tutorial are you using?
A lot of people come to this page with the goal of finding the webpack config and files in order to add their own configuration to them. Another way to achieve this without running npm run eject
is to use react-app-rewired. This allows you to overwrite your webpack config file without ejecting.
select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;
place the number whatever the highest sal you want to retrieve.
The best option according to me is to have key/value pairs file as it could be read from other scripting languages.
Other thing is I would prefer to have an option for comments in the values file - which can be easy achieved with eol
option in for /f
command.
Here's the example
values file:
;;;;;; file with example values ;;;;;;;;
;; Will be processed by a .bat file
;; ';' can be used for commenting a line
First_Value=value001
;;Do not let spaces arround the equal sign
;; As this makes the processing much easier
;; and reliable
Second_Value=%First_Value%_test
;;as call set will be used in reading script
;; refering another variables will be possible.
Third_Value=Something
;;; end
Reading script:
@echo off
:::::::::::::::::::::::::::::
set "VALUES_FILE=E:\scripts\example.values"
:::::::::::::::::::::::::::::
FOR /F "usebackq eol=; tokens=* delims=" %%# in (
"%VALUES_FILE%"
) do (
call set "%%#"
)
echo %First_Value% -- %Second_Value% -- %Third_Value%
One simple example for return SQL table as formatted JSON and fix error as he had @Whitecat
I get the error datetime.datetime(1941, 10, 31, 0, 0) is not JSON serializable
In that example you should use JSONEncoder.
import json
import pymssql
# subclass JSONEncoder
class DateTimeEncoder(JSONEncoder):
#Override the default method
def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
def mssql_connection():
try:
return pymssql.connect(server="IP.COM", user="USERNAME", password="PASSWORD", database="DATABASE")
except Exception:
print("\nERROR: Unable to connect to the server.")
exit(-1)
def query_db(query):
cur = mssql_connection().cursor()
cur.execute(query)
r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return r
def write_json(query_path):
# read sql from file
with open("../sql/my_sql.txt", 'r') as f:
sql = f.read().replace('\n', ' ')
# creating and writing to a json file and Encode DateTime Object into JSON using custom JSONEncoder
with open("../output/my_json.json", 'w', encoding='utf-8') as f:
json.dump(query_db(sql), f, ensure_ascii=False, indent=4, cls=DateTimeEncoder)
if __name__ == "__main__":
write_json()
# You get formatted my_json.json, for example:
[
{
"divroad":"N",
"featcat":null,
"countyfp":"001",
"date":"2020-08-28"
}
]
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
import { combineReducers } from '../../store/reducers';
should be
import combineReducers from '../../store/reducers';
since it's a default export, and not a named export.
There's a good breakdown of the differences between the two here.
Handles hex, octal, binary, int, and float
Using the standard prefixes (i.e. 0x, 0b, 0, and 0o) this function will convert any suitable string to a number. I answered this here: https://stackoverflow.com/a/58997070/2464381 but here is the needed function.
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
# python 3 doesn't accept "010" as a valid octal. You must use the
# '0o' prefix
return int('0o' + n, 0)
except:
return float(n)
var s = ",'first string','more','even more'";
var array = s.split(',').slice(1);
That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.
The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource
which will clear and re-populate your list, losing the first manually added item.
So, you need to do this in reverse like this:
Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();
// Then add your first item
DropDownList1.Items.Insert(0, "Select");
To complete the answer of Hannes.
You need to change some setting in your php.ini:
upload_max_filesize = 2M
;or whatever size you want
max_execution_time = 60
; also, higher if you must
If someone want put in unlimited (I don't know why but if you want), you can set the time to 0:
You need to change some setting in your php.ini:
upload_max_filesize = 0
max_execution_time = 0
And if you don't know where is your php.ini. You can do a file "name.php" in your server and put:
<?php phpinfo(); ?>
And on your website, you can see the config of your php.ini and it's marked where is it.
If you can't access your php.ini, you have two more options.
You can set this line directly in your "name.php" file but I don't find for upload_max_filesize for this option:
set_time_limit(0);
Or in ".htaccess"
php_value upload_max_filesize 0
php_value max_execution_time 0
Python 2 uses ascii
as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses utf-8
as the default encoding for source files, so this is less of an issue.
See: http://docs.python.org/tutorial/interpreter.html#source-code-encoding
To enable utf-8 source encoding, this would go in one of the top two lines:
# -*- coding: utf-8 -*-
The above is in the docs, but this also works:
# coding: utf-8
Additional considerations:
The source file must be saved using the correct encoding in your text editor as well.
In Python 2, the unicode literal must have a u
before it, as in s.replace(u"Â ", u"")
But in Python 3, just use quotes. In Python 2, you can from __future__ import unicode_literals
to obtain the Python 3 behavior, but be aware this affects the entire current module.
s.replace(u"Â ", u"")
will also fail if s
is not a unicode string.
string.replace
returns a new string and does not edit in place, so make sure you're using the return value as well
I had the same problem. In my /etc/mysql/my.cnf
was no path more to mysqld.sock
defined. So I started a search to find it with: find / -type s | grep mysqld.sock
but it could not be found.
I reinstalled mysql with: apt install mysql-server-5.7
(please check before execute the current sql-server-version).
This solved my problem.
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
Since you have master page and your control is in content place holder, Your control id will be generated different in client side. you need to do like...
var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value;
Javascript runs on client side and to get value you have to provide client id of your control
my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine
Installing the aab directly from the device, I couldn't find a way for that.
But there is a way to install it through your command line using the following documentation You can install apk to a device through BundleTool
According to "@Albert Vila Calvo" comment he noted that to install bundletools using HomeBrew use brew install bundletool
You can now install extract apks from aab file and install it to a device
Extracting apk files from through the next command
java -jar bundletool-all-0.3.3.jar build-apks --bundle=bundle.aab --output=app.apks --ks=my-release-key.keystore --ks-key-alias=alias --ks-pass=pass:password
Arguments:
Then you will have a file with extension .apks So now you need to install it to a device
java -jar bundletool-all-0.6.0.jar install-apks --adb=/android-sdk/platform-tools/adb --apks=app.apks
Arguments:
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
You should reference the textarea ID and include the runat="server"
attribute to the textarea
message.Body = TextArea1.Text;
What is test123
?
As mentioned in the question, there is the clip
css property, although it does require that the element being clipped is position: absolute;
(which is a shame):
.container {_x000D_
position: relative;_x000D_
}_x000D_
#clip {_x000D_
position: absolute;_x000D_
clip: rect(0, 100px, 200px, 0);_x000D_
/* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path
, which has replaced the now-deprecated clip
property.
The clip-path
property allows a range of options (more-so than the original clip
), of:
inset
— rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left)
.circle
— circle(diameter at x-coordinate y-coordinate)
.ellipse
— ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate)
.polygon
— defined by a series of x
/y
coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...])
.url
— this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.div.container {_x000D_
display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
-webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
-webkit-clip-path: circle(75px at 50% 50%);_x000D_
clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
-webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
-webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
<img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
References:
clip
clip-path
(MDN).clip-path
(W3C).Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?
Would that require an IFNULL() and another SELECT statement for each field ?
The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.
Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.
Initial GeoJsonResponse class:
from pyexample.responses import Response
class GeoJsonResponse(Response):
def __init__(self, geo_json_data):
Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:
from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):
E TypeError: module() takes at most 2 arguments (3 given)
=================================== ERRORS ====================================
___________________ ERROR collecting tests/test_geojson.py ____________________
test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)
class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)
ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response
C:\Python37\lib\site-packages\aenum__init__.py:163
(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])
The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:
I was importing the module:
from pyexample.responses import Response
when I should have been importing the class:
from pyexample.responses.Response import Response
Hope this helps someone. (In my defense, it's still pretty early.)
The problem is that PHP mail()
function has a very limited functionality. There are several ways to send mail from PHP.
mail()
uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.mail()
uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail()
function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer
class or interface with abstract send()
method. Inherit two classes MyPhpMailer
and MySwiftMailer
. Implement send()
method in appropriate ways.