I have been fighting the same thing for a while.
after all the research, this is the best solution.....
add the following to your resolve.conf file /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
https://serverfault.com/questions/717226/ubuntu14-04-unable-to-apt-get-update/771826#771826
I had a similar challenge when working on a Rails 6 application.
Here's how I solved it:
I have a Users
table and a Roles
table. The Users
table belongs to the Roles
table. I also have an Admin
and Student
Models that inherit from the Users
table.
It then required that I set a default value for the role whenever a user is created, say admin
role that has an id = 1
or student
role that has an id = 2
.
class User::Admin < User
before_save :default_values
def default_values
# set role_id to '1' except if role_id is not empty
return self.role_id = '1' unless role_id.nil?
end
end
This means that before an admin
user is created/saved in the database the role_id
is set to a default of 1
if it is not empty.
return self.role_id = '1' unless role_id.nil?
is the same as:
return self.role_id = '1' unless self.role_id.nil?
and the same as:
self.role_id = '1' if role_id.nil?
but the first one is cleaner and more precise.
That's all.
I hope this helps
You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.
Take a look at this answer
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
var x = $(this).attr("name");_x000D_
$(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {_x000D_
$(".js-hide-onclick").click(function() {_x000D_
$($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
_x000D_
_x000D_
Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.
As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.
After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext
.
So, my logic follows below:
Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing
.
Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume
)
Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail
(which is also a product ID) along with some other values.
The possible productIds are provided here.
To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext
and try to see if any name has a prefix o365
, if it finds it then its O365. If it does not, then its Office 2019.
Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.
Hope this will help whoever's interest.
If you are defining your function:
function test() {};
Then, this is equivalent to:
window.test = function() {} /* (in the browser) */
So spyOn(window, 'test')
should work.
If that is not, you should also be able to:
test = jasmine.createSpy();
If none of those are working, something else is going on with your setup.
I don't think your fakeElement
technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.
To determine the package version in node code, you can use the following:
const version = require('./package.json').version;
for < ES6 versions
import {version} from './package.json';
for ES6 version
const version = process.env.npm_package_version;
if application has been started using npm start
, all npm_* environment variables become available.
You can use following npm packages as well - root-require, pkginfo, project-version.
not exactly an image, but i found the easiest solution was to just add some unicode code in, ? works great for me
I had a similar problem and in my case, the issue was different (I am using Django templates).
The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.
I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.
You can get sqlite3.dll
file with encryption support from http://system.data.sqlite.org/.
1 - Go to http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and download one of the packages. .NET version is irrelevant here.
2 - Extract SQLite.Interop.dll
from package and rename it to sqlite3.dll
. This DLL supports encryption via plaintext passwords or encryption keys.
The mentioned file is native and does NOT require .NET framework. It might need Visual C++ Runtime depending on the package you have downloaded.
UPDATE
This is the package that I've downloaded for 32-bit development: http://system.data.sqlite.org/blobs/1.0.94.0/sqlite-netFx40-static-binary-Win32-2010-1.0.94.0.zip
Just FYI:
html should be table & width:100%. span should be margin: auto;
EDIT
I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js
OLD ANSWER
this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help
(function (w,d) { //
var
nc = "", nu = "", nr = "", t,
a = "addEventListener",
n = a in w,
c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
u = n?(nu = "attach", "add"):(nu = "add","attach"),
r = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
*/
function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt ))}}
w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]
})(window, document)
This is the official document for a user to upgrade npm on Windows!
Here is my screenshot!
For those using Redux Pattern
I added in the file-saver as @Hector Cuevas named in his answer. Using Angular2 v. 2.3.1, I didn't need to add in the @types/file-saver.
The following example is to download a journal as PDF.
The journal actions
public static DOWNLOAD_JOURNALS = '[Journals] Download as PDF';
public downloadJournals(referenceId: string): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS,
payload: { referenceId: referenceId }
};
}
public static DOWNLOAD_JOURNALS_SUCCESS = '[Journals] Download as PDF Success';
public downloadJournalsSuccess(blob: Blob): Action {
return {
type: JournalActions.DOWNLOAD_JOURNALS_SUCCESS,
payload: { blob: blob }
};
}
The journal effects
@Effect() download$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS)
.switchMap(({payload}) =>
this._journalApiService.downloadJournal(payload.referenceId)
.map((blob) => this._actions.downloadJournalsSuccess(blob))
.catch((err) => handleError(err, this._actions.downloadJournalsFail(err)))
);
@Effect() downloadJournalSuccess$ = this.actions$
.ofType(JournalActions.DOWNLOAD_JOURNALS_SUCCESS)
.map(({payload}) => saveBlobAs(payload.blob, 'journal.pdf'))
The journal service
public downloadJournal(referenceId: string): Observable<any> {
const url = `${this._config.momentumApi}/api/journals/${referenceId}/download`;
return this._http.getBlob(url);
}
The HTTP service
public getBlob = (url: string): Observable<any> => {
return this.request({
method: RequestMethod.Get,
url: url,
responseType: ResponseContentType.Blob
});
};
The journal reducer Though this only sets the correct states used in our application I still wanted to add it in to show the complete pattern.
case JournalActions.DOWNLOAD_JOURNALS: {
return Object.assign({}, state, <IJournalState>{ downloading: true, hasValidationErrors: false, errors: [] });
}
case JournalActions.DOWNLOAD_JOURNALS_SUCCESS: {
return Object.assign({}, state, <IJournalState>{ downloading: false, hasValidationErrors: false, errors: [] });
}
I hope this is helpful.
simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)
Update March 2017: as commented by Anthony Accioly, the scala.Enumeration/enum
PR has been closed.
Dotty (next generation compiler for Scala) will take the lead, though dotty issue 1970 and Martin Odersky's PR 1958.
Note: there is now (August 2016, 6+ years later) a proposal to remove scala.Enumeration
: PR 5352
Deprecate
scala.Enumeration
, add@enum
annotationThe syntax
@enum
class Toggle {
ON
OFF
}
is a possible implementation example, intention is to also support ADTs that conform to certain restrictions (no nesting, recursion or varying constructor parameters), e. g.:
@enum
sealed trait Toggle
case object ON extends Toggle
case object OFF extends Toggle
Deprecates the unmitigated disaster that is
scala.Enumeration
.Advantages of @enum over scala.Enumeration:
- Actually works
- Java interop
- No erasure issues
- No confusing mini-DSL to learn when defining enumerations
Disadvantages: None.
This addresses the issue of not being able to have one codebase that supports Scala-JVM,
Scala.js
and Scala-Native (Java source code not supported onScala.js/Scala-Native
, Scala source code not able to define enums that are accepted by existing APIs on Scala-JVM).
Don't hard code image bounds. Just use:
RotateAnimation anim = new RotateAnimation( fromAngle, toAngle, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
To complement the existing helpful answers:
Using Bash's own regex-matching operator, =~
, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:
set -- '12-34-5678' # set $1 to sample value
kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match
Note, however, that the caveat re using flavor-specific regex constructs such as \d
equally applies:
While =~
supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.
To remain portable (in the context of Bash), stick to the POSIX ERE specification.
Note that =~
even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]}
array variable.
Further notes:
$kREGEX_DATE
is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).
While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \
.
\<
is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes
doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes
does.I've changed variable name REGEX_DATE
to kREGEX_DATE
(k
signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.
Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").
When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.
If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.
function getHomeUrl() {
var href = window.location.href;
var index = href.indexOf('/wp-admin');
var homeUrl = href.substring(0, index);
return homeUrl;
}
A variation is where you sort the collection in place using a selection sort algorithm. Elements are moved into place using the Move
method. Each move will fire the CollectionChanged
event with NotifyCollectionChangedAction.Move
(and also PropertyChanged
with property name Item[]
).
This algorithm has some nice properties:
CollectionChanged
events fired) is almost always less than other similar algorithms like insertion sort and bubble sort.The algorithm is quite simple. The collection is iterated to find the smallest element which is then moved to the start of the collection. The process is repeated starting at the second element and so on until all elements have been moved into place. The algorithm is not terribly efficient but for anything you are going to display in a user interface it shouldn't matter. However, in terms of the number of move operations it is quite efficient.
Here is an extension method that for simplicity requires that the elements implement IComparable<T>
. Other options are using an IComparer<T>
or a Func<T, T, Int32>
.
public static class ObservableCollectionExtensions {
public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable<T> {
if (collection == null)
throw new ArgumentNullException("collection");
for (var startIndex = 0; startIndex < collection.Count - 1; startIndex += 1) {
var indexOfSmallestItem = startIndex;
for (var i = startIndex + 1; i < collection.Count; i += 1)
if (collection[i].CompareTo(collection[indexOfSmallestItem]) < 0)
indexOfSmallestItem = i;
if (indexOfSmallestItem != startIndex)
collection.Move(indexOfSmallestItem, startIndex);
}
}
}
Sorting a collection is simply a matter of invoking the extension method:
var collection = new ObservableCollection<String>(...);
collection.Sort();
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.
As Joshua Bloch states in Effective Java, 2nd Edition:
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.
It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.
To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:
spring.datasource.maxActive=5
You can also use the following if you prefer:
spring.datasource.max-active=5
You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc
.
To understand how this works more generally you need to dig into the Spring-Boot code a bit.
Spring-Boot constructs the DataSource like this (see here, line 102):
@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
DataSourceBuilder factory = DataSourceBuilder
.create(this.properties.getClassLoader())
.driverClassName(this.properties.getDriverClassName())
.url(this.properties.getUrl())
.username(this.properties.getUsername())
.password(this.properties.getPassword());
return factory.build();
}
The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource()
function.
At this point, magic kicks in using @ConfigurationProperties
. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX
(which is spring.datasource
). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.
The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive()
.
And that's how your spring.datasource.maxActive=5
gets applied correctly!
I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.
Create an xml file in res/values and copy the below code
<style name="BlackText">
<item name="android:textColor">#000000</item>
</style>
and the specify the style in activity in Manifest like below
android:theme="@style/BlackText"
declare @sexo as char(1)
select @sexo='F'
select * from pessoa
where isnull(Sexo,0) =isnull(@Sexo,0)
Today, I was also struggling to merge JSON objects and came with following solution (uses Gson library).
private JsonObject mergeJsons(List<JsonObject> jsonObjs) {
JsonObject mergedJson = new JsonObject();
jsonObjs.forEach((JsonObject jsonObj) -> {
Set<Map.Entry<String, JsonElement>> entrySet = jsonObj.entrySet();
entrySet.forEach((next) -> {
mergedJson.add(next.getKey(), next.getValue());
});
});
return mergedJson;
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthesisWithStack {
/*This is purely Java Stack based solutions without using additonal
data structure like array/Map */
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
/*Take list of String inputs (parenthesis expressions both valid and
invalid from console*/
List<String> inputs=new ArrayList<>();
while (sc.hasNext()) {
String input=sc.next();
inputs.add(input);
}
//For every input in above list display whether it is valid or
//invalid parenthesis expression
for(String input:inputs){
System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
(input));
}
}
//This method identifies whether expression is valid parenthesis or not
public static boolean isBalancedParenthesis(String expression){
//sequence of opening parenthesis according to its precedence
//i.e. '[' has higher precedence than '{' or '('
String openingParenthesis="[{(";
//sequence of closing parenthesis according to its precedence
String closingParenthesis=")}]";
//Stack will be pushed on opening parenthesis and popped on closing.
Stack<Character> parenthesisStack=new Stack<>();
/*For expression to be valid :
CHECK :
1. it must start with opening parenthesis [()...
2. precedence of parenthesis should be proper (eg. "{[" invalid
"[{(" valid )
3. matching pair if( '(' => ')') i.e. [{()}(())] ->valid [{)]not
*/
if(closingParenthesis.contains
(((Character)expression.charAt(0)).toString())){
return false;
}else{
for(int i=0;i<expression.length();i++){
char ch= (Character)expression.charAt(i);
//if parenthesis is opening(ie any of '[','{','(') push on stack
if(openingParenthesis.contains(ch.toString())){
parenthesisStack.push(ch);
}else if(closingParenthesis.contains(ch.toString())){
//if parenthesis is closing (ie any of ']','}',')') pop stack
//depending upon check-3
if(parenthesisStack.peek()=='(' && (ch==')') ||
parenthesisStack.peek()=='{' && (ch=='}') ||
parenthesisStack.peek()=='[' && (ch==']')
){
parenthesisStack.pop();
}
}
}
return (parenthesisStack.isEmpty())? true : false;
}
}
With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.
See issue 89989:
It should be possible to e.g. invoke the "
Open Active File in New Window
" command and open that file into an empty workspace in the web.
yes there is!
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
Sorry Late to party but Firestore solved it way back in aug 2018 so If you still looking for that here it is all issues solved with regards to arrays.
https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.htmlOfficial blog post
array-contains, arrayRemove, arrayUnion for checking, removing and updating arrays. Hope it helps.
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.
# just an example
def func(): # define a function
func.y = 4 # here y is a local variable, which I want to access; func.y defines
# a method for my example function which will allow me to access
# function's local variable y
x = func.y + 8 # this is the main task for the function: what it should do
return x
func() # now I'm calling the function
a = func.y # I put it's local variable into my new variable
print(a) # and print my new variable
Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// Do something.
break;
case 5:
case 6:
case 7:
case 8:
// Do something.
break;
default:
break;
}
If you don't like the succession of cases, simply go for if/else if/else
statements.
Thanks Shuwaiee
I made a slight change though as using it in a Private Sub
already.
Dim GetIPAddress()
Dim strHostName As String
Dim strIPAddress As String
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)
But also made a change to the way the details are displayed so that they can show on seperate lines using & vbCrLf &
MessageBox.Show("Host Name: " & strHostName & vbCrLf & "IP Address: " & strIPAddress)
Hope this helps someone.
Use .length
refer to http://api.jquery.com/checked-selector/
if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");
I propose using Task<T>
instead of Thread
; it allows multiple parameters and executes really fine.
Here is a working example:
public static void Main()
{
List<Task> tasks = new List<Task>();
Console.WriteLine("Awaiting threads to finished...");
string par1 = "foo";
string par2 = "boo";
int par3 = 3;
for (int i = 0; i < 1000; i++)
{
tasks.Add(Task.Run(() => Calculate(par1, par2, par3)));
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All threads finished!");
}
static bool Calculate1(string par1, string par2, int par3)
{
lock(_locker)
{
//...
return true;
}
}
// if need to lock, use this:
private static Object _locker = new Object();"
static bool Calculate2(string par1, string par2, int par3)
{
lock(_locker)
{
//...
return true;
}
}
You can use guide=FALSE
in scale_..._...()
to suppress legend.
For your example you should use scale_colour_continuous()
because length
is continuous variable (not discrete).
(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_continuous(guide = FALSE) +
geom_point()
)
Or using function guides()
you should set FALSE
for that element/aesthetic that you don't want to appear as legend, for example, fill
, shape
, colour
.
p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
p0+guides(colour=FALSE)
Both provided solutions work in new ggplot2
version 2.0.0 but movies
dataset is no longer present in this library. Instead you have to use new package ggplot2movies
to check those solutions.
library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")
One solution is to add a UITextField below the UITextView, make the UITextView
background transparent and disable any user interaction on the UITextField
. Then in code change the UITextField
frame with something like that
self.textField.frame = CGRectInset(self.textView.frame, 0, -2);
You will have exactly the same look as a text field.
And as suggested by Jon, you should put this piece of code inside [UIViewController viewDidLayoutSubviews]
on iOS 5.0+.
Call cURL from your console app is not a good idea.
But you can use TinyRestClient which make easier to build requests :
var client = new TinyRestClient(new HttpClient(),"https://api.repustate.com/");
client.PostRequest("v2/demokey/score.json").
AddQueryParameter("text", "").
ExecuteAsync<MyResponse>();
It's easy to create this yourself
In your layout include the following ProgressBar
with a specific drawable (note you should get the width from dimensions instead). The max value is important here:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="500"
android:progress="0"
android:progressDrawable="@drawable/circular" />
Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius
instead of innerRadiusRatio
) and thickness values.
circular (Pre Lollipop OR API Level < 21)
<shape
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
circular ( >= Lollipop OR API Level >= 21)
<shape
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
useLevel is "false" by default in API Level 21 (Lollipop) .
Start Animation
Next in your code use an ObjectAnimator
to animate the progress field of the ProgessBar
of your layout.
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
Stop Animation
progressBar.clearAnimation();
P.S. unlike examples above, it give smooth animation.
There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess
The source code is easy to understand and provides a good starting point.
Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command %load
.
If you execute a cell containing:
%load filename.py
the content of filename.py
will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic %%writefile filename.py
at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a ?
: like %load?
or %%writefile?
.
For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.
See also: Magic functions from the official IPython docs.
I just had this problem
Hope this helps
# Works on hidden files, directories and regular files
### isEmpty()
# This function takes one parameter:
# $1 is the directory to check
# Echoes "huzzah" if the directory has files
function isEmpty(){
if [ "$(ls -A $1)" ]; then
echo "huzzah"
else
echo "has no files"
fi
}
Change the line where you print the output to:
printf("\nmaximum of %d and %d is = %d",a,b,c);
See the docs here
I like using a background image. I find it easier and more flexible:
CSS:
#menu {
max-width: 1200px;
text-align: center;
margin: auto;
}
.zoomimg {
display: inline-block;
width: 250px;
height: 375px;
padding: 0px 5px 0px 5px;
background-size: 100% 100%;
background-repeat: no-repeat;
background-position: center center;
transition: all .5s ease;
}
.zoomimg:hover {
cursor: pointer;
background-size: 150% 150%;
}
.blog {
background-image: url(http://s18.postimg.org/il7hbk7i1/image.png);
}
.music {
background-image: url(http://s18.postimg.org/4st2fxgqh/image.png);
}
.projects {
background-image: url(http://s18.postimg.org/sxtrxn115/image.png);
}
.bio {
background-image: url(http://s18.postimg.org/5xn4lb37d/image.png);
}
HTML:
<div id="menu">
<div class="blog zoomimg"></div>
<div class="music zoomimg"></div>
<div class="projects zoomimg"></div>
<div class="bio zoomimg"></div>
</div>
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
In case you are working with Maven and Apache Wicket also check for the following in order to try to resolve the issue with Font-Awesome and icons not being loaded:
If you have placed your files for example in the following file structure
/src
/main
/java
/your
/package
/css
font-awesome.css
/font
fontawesome-webfont.eot
fontawesome-webfont.svg
fontawesome-webfont.svgz
fontawesome-webfont.ttf
fontawesome-webfont.woff
Check 1) Are you correctly using a Package Resource Guard in order to allow to load the font files correctly?
Example from your class which extends WebApplication:
@Override
public void init() {
super.init();
get().getResourceSettings().setPackageResourceGuard(new PackageResourceGuard());
}
Check 2) After you have made sure that all fonts are correctly transferred to the Web Browser, check for what has been actually transferred to the Web Browser, i.e., did the integrity of the font files change? Compare the files in your source directory and the files transferred to the Web Browser using, e.g., the Web Developer Toolbar of Firefox and DiffDog (for file comparison).
In particular if you are using Maven be aware of resource filtering. Do not filter the folder where your /font files are contained - otherwise they will be corrupted.
Example from your pom.xml
<build>
<finalName>Your project</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
</build>
In the example above we do not filter the folder src/main/java, where the css and font files are contained.
For further information on the filtering of binary data please also see the documentation:
http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
In particular the documentation warns: "Warning: Do not filter files with binary content like images! This will most likely result in corrupt output. If you have both text files and binary files as resources, you need to declare two mutually exclusive resource sets. The first resource set defines the files to be filtered and the other resource set defines the files to copy unaltered..."
As you might hear, wayland is the featured choice of many distros these days, because of its protocol is simpler than the X.
Toolkits or gui libraries that wayland suggests are:
This can be done in java 8 using Stream.
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
for variable:
var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);
For normal inlined <code>
use:
<code>...</code>
and for each and every place where blocked <code>
is needed use
<code style="display:block; white-space:pre-wrap">...</code>
Alternatively, define a <codenza>
tag for break lining block <code>
(no classes)
<script>
</script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>`
Testing:
(NB: the following is a scURIple utilizing a data:
URI protocol/scheme, therefore the %0A
nl format codes are essential in preserving such when cut and pasted into the URL bar for testing - so view-source:
(ctrl-U) looks good preceed every line below with %0A
)
data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual <code> tag
<code>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
and then
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
<br>using an ersatz tag
<codenza>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</codenza>
</html>
<div class="field">
<label class="field-label" for="photo">Your photo</label>
<input class="field-input" type="file" name="photo" id="photo" value="photo" />
</div>
and the css
input[type="file"]
{
color: transparent;
background-color: #F89406;
border: 2px solid #34495e;
width: 100%;
height: 36px;
border-radius: 3px;
}
We use the node-deep-equal project which implements the same deep-equal comparison as nodejs
A google serach for deep-equal on npm will show you many alternatives
I think you can also use a scaffold to do the white background. Here's some piece of code that may help.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Testing',
home: new Scaffold(
//Here you can set what ever background color you need.
backgroundColor: Colors.white,
),
);
}
}
Hope this helps .
use android:theme="@android:style/Theme.NoTitleBar
in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.
You can use String.Format function to add second class based on condition:
<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">
Use the static Double.isNaN(double)
method, or your Double
's .isNaN()
method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
json.dump(data, open('data.txt', 'wb'))
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
I just got this problem today, since it showed up after Norton requested reboot I blamed Norton.
But it wasn't Norton, I removed Norton, rebooted -> problem still there.
netstat -nao was showing that PID 4 owned my port 80 connection.
I then went to control panel,
then "Turn Windows features on or off"
then unchecked Internet Information Services.
Rebooted, the problem went away.
My xampp server is running ok now.
I don't ever remembering turning IIS on in the first place. I had been running many months before this happened. I still don't know what caused it in the first place. Maybe a previous windows updated enabled iis and my reboot turned it on, I don't know.
Have a look to this wiki: LaTeX/Labels and Cross-referencing:
The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:
\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...
I'm going to add this here:
sudo python manage.py runserver 80
Go to your phone or computer and enter your computers internal IP (e.g 192.168.0.12
) into the browser.
At this point you should be connected to the Django server.
This should also work without sudo:
python manage.py runserver 0.0.0.0:8000
just change in settings.xml these as aliteralmind says:
<server>
<id>nexus-snapshots</id>
<username>MY_SONATYPE_DOT_COM_USERNAME</username>
<password>MY_SONATYPE_DOT_COM_PASSWORD</password>
</server>
you probably need to get the username / password from sonatype dot com.
employees.ToList().ForEach(
emp=>
{
collection.AddRange(emp.Departments);
emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
});
Please use following block of code in your include file which loaded in every pages.
$expiry = 1800 ;//session expiry required after 30 mins
if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
session_unset();
session_destroy();
}
$_SESSION['LAST'] = time();
step 1:
Download dex2jar here. Create a java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .
Copy apk file into java project
Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files
step 2: Download java decompiler here
Private Sub Main()
Dim value = getValue()
'do something with value
End Sub
Private Function getValue() As Integer
Return 3
End Function
I ultimately found nothing that would work across all my browsers and all DocTypes / browser rendering modes, except for using jQuery. So here is what I came up with.
It even takes rowspan into account.
function InitDivHeights() {
var spacing = 10; // <-- Tune this value to match your tr/td spacing and padding.
var rows = $('#MyTable tr');
var heights = [];
for (var i = 0; i < rows.length; i++)
heights[i] = $(rows[i]).height();
for (var i = 0; i < rows.length; i++) {
var row = $(rows[i]);
var cells = $('td', row);
for (var j = 0; j < cells.length; j++) {
var cell = $(cells[j]);
var rowspan = cell.attr('rowspan') || 1;
var newHeight = 0;
for (var k = 0; (k < rowspan && i + k < heights.length); k++)
newHeight += heights[i + k];
$('div', cell).height(newHeight - spacing);
}
}
}
$(document).ready(InitDivHeights);
Tested in IE11 (Edge mode), FF42, Chrome44+. Not tested with nested tables.
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
Will return a floating point number in the range [0,1]:
#define rand01() (((double)random())/((double)(RAND_MAX)))
while using Header array
String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
new BasicHeader("Authorization", "Basic " +auth)
};
May be the better way is
UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];
Thus we have colored text
if you use jQuery, you can simple do
$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);
and handle it with
$('#yourElement').on('customEventName',
function (objectEvent, [arg0, arg1, ..., argN]){
alert ("customEventName");
});
where "[arg0, arg1, ..., argN]" means that these args are optional.
Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name
<?php
$host="localhost";
$username="root";
$password="";
$dbname="your_database_name";
$con = new mysqli($host, $username, $password,$dbname);
$sql_data="select * from table_name";
$result_data=$con->query($sql_data);
$results=array();
filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while ($row = mysqli_fetch_assoc($result_data)) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
The poster has their java types mixed up. in java, his C in is a short: short (16 bit) = -32768 to 32767 int (32 bit) = -2,147,483,648 to 2,147,483,647
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
What is the code of your button? If it's an a tag, then you could do this:
a {_x000D_
padding: 5px;_x000D_
background: green;_x000D_
}_x000D_
a:visited {_x000D_
background: red;_x000D_
}
_x000D_
<a href="#">A button</a>
_x000D_
Or you could use jQuery to add a class on click, as below:
$("#button").click(function() {_x000D_
$("#button").addClass('button-clicked');_x000D_
});
_x000D_
.button-clicked {_x000D_
background: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="button">Button</button>
_x000D_
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
Use global namespace or global object like Constants.
var Constants = {};
And using defineObject write function which will add all properties to that object and assign value to it.
function createConstant (prop, value) {
Object.defineProperty(Constants , prop, {
value: value,
writable: false
});
};
Simple Solution, just type the below:
conda update pandas
Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).
To turn off highlighting until the next search:
:noh
Or turn off highlighting completely:
set nohlsearch
Or, to toggle it:
set hlsearch!
nnoremap <F3> :set hlsearch!<CR>
If the .htaccess
file not avilable create it on root folder and past this line of code.
Put this in .htaccess
file (tested working well for API)
<IfModule mod_php5.c>
php_value always_populate_raw_post_data -1
</IfModule>
The new official AWS CLI natively supports most of the functionality of s3cmd
. I'd previously been using s3cmd
or the ruby AWS SDK to do things like this, but the official CLI works great for this.
http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html
aws s3 sync s3://oldbucket s3://newbucket
I'm surprised no one mentioned the HTML entities  
and  
which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than
.
 
 
Along with <space>
and  
, these are the five entities HTML provides for horizontal white space.
Note that except for
, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With
it would wrap to a new line as a block even if the text before
could fit on the previous line.
Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John
Doe), addresses or references (see eq.
5), breaking as a block is usually undesired.
I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,
**<Div class = "navbar"**>
div class = "container">
<Div class = "navbar-header">
or
**<Div class = "navbar navbar-default">**
div class = "container">
<Div class = "navbar-header">
You got that place in your CSS
.navbar-default-toggle .navbar .icon-bar {
background-color: # 0000ff;
}
and what I did was add above
.navbar .navbar-toggle .icon-bar {
background-color: # ff0000;
}
Because my html code is
**<Div class = "navbar">**
div class = "container">
<Div class = "navbar-header">
and if you associate a file less / css
search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;
if your html code is like mine and is not navbar-default, add it as you did with the css.
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;
good luck
You can try with this below command:
python -m pip install --trusted-host https://pypi.python.org deepdiff
it will work.
inline
and inline-block
elements are affected by whitespace in the HTML.
The simplest way to fix your problem is to remove the whitespace between </div>
and <div id="col2">
, see: http://jsfiddle.net/XCDsu/15/
There are other possible solutions, see: bikeshedding CSS3 property alternative?
A simple method by using for
loop :
import os
dir = ["e","x","e"]
p = os.listdir('E:') #path
for n in range(len(p)):
name = p[n]
myfile = [name[-3],name[-2],name[-1]] #for .txt
if myfile == dir :
print(name)
else:
print("nops")
Though this can be made more generalised .
The file msrdo20.dll is missing from the installation.
According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.
I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:
regsvr32 c:\windows\system32\msrdo20.dll
In an ideal world you would package this up with the redistributable.
Here's the generic method to get values from map.
public static <T> List<T> ValueListFromMap(HashMap<String, T> map) {
List<T> thingList = new ArrayList<>();
for (Map.Entry<String, T> entry : map.entrySet()) {
thingList.add(entry.getValue());
}
return thingList;
}
Linux Mint, Debian 9, Ubuntu 16.04 and older:
Short info:
apt policy <package_name>
Detailed info (With Description and Depends):
apt show <package_name>
If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor
, TypeDescriptionProvider
and/or TypeCoverter
, you can create your own PropertyDescriptor
instances at runtime. This is what controls like DataGridView
, PropertyGrid
etc use to display properties.
To bind to lists, you'd need ITypedList
and IList
; for basic sorting: IBindingList
; for filtering and advanced sorting: IBindingListView
; for full "new row" support (DataGridView
): ICancelAddNew
(phew!).
It is a lot of work though. DataTable
(although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p
Here's a simple example - but you can do a lot more...
The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime
). Despite the often misleading name such classes like LocalDateTime
or LocalTime
have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime
(which contains an offset but not a timezone including DST-rules) or ZonedDateTime
. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds
is supported in OffsetDateTime
and ZonedDateTime
, but not in LocalDateTime
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
Above works for me in build.gradle
file
Here is my ES3 commented solution (gory details after the code):
function object_equals( x, y ) {
if ( x === y ) return true;
// if both x and y are null or undefined and exactly the same
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
// if they are not strictly equal, they both need to be Objects
if ( x.constructor !== y.constructor ) return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
for ( var p in x ) {
if ( ! x.hasOwnProperty( p ) ) continue;
// other properties were tested using x.constructor === y.constructor
if ( ! y.hasOwnProperty( p ) ) return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if ( x[ p ] === y[ p ] ) continue;
// if they have the same strict value or identity then they are equal
if ( typeof( x[ p ] ) !== "object" ) return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( ! object_equals( x[ p ], y[ p ] ) ) return false;
// Objects and Arrays must be tested recursively
}
for ( p in y )
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
return false;
// allows x[ p ] to be set to undefined
return true;
}
In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.
First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.
Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.
Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.
The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.
The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.
Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.
No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.
Overall this code handles most corner cases in only 16 lines of code (without comments).
Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.
This worked for me
In Controlle
ViewBag.AAA = default_Value ;
In View
@Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }
As promised, here is my Cairo version. I scripted it with Lua, using lfs to walk the directories. I love these little challenges, as they allow me to explore APIs I wanted to dig for quite some time...
lfs and LuaCairo are both cross-platform, so it should work on other systems (tested on French WinXP Pro SP3).
I made a first version drawing file names as I walked the tree. Advantage: no memory overhead. Inconvenience: I have to specify the image size beforehand, so listings are likely to be cut off.
So I made this version, first walking the directory tree, storing it in a Lua table. Then, knowing the number of files, creating the canvas to fit (at least vertically) and drawing the names.
You can easily switch between PNG rendering and SVG one. Problem with the latter: Cairo generates it at low level, drawing the letters instead of using SVG's text capability. Well, at least, it guarantees accurate rending even on systems without the font. But the files are bigger... Not really a problem if you compress it after, to have a .svgz file.
Or it shouldn't be too hard to generate the SVG directly, I used Lua to generate SVG in the past.
-- LuaFileSystem <http://www.keplerproject.org/luafilesystem/>
require"lfs"
-- LuaCairo <http://www.dynaset.org/dogusanh/>
require"lcairo"
local CAIRO = cairo
local PI = math.pi
local TWO_PI = 2 * PI
--~ local dirToList = arg[1] or "C:/PrgCmdLine/Graphviz"
--~ local dirToList = arg[1] or "C:/PrgCmdLine/Tecgraf"
local dirToList = arg[1] or "C:/PrgCmdLine/tcc"
-- Ensure path ends with /
dirToList = string.gsub(dirToList, "([^/])$", "%1/")
print("Listing: " .. dirToList)
local fileNb = 0
--~ outputType = 'svg'
outputType = 'png'
-- dirToList must have a trailing slash
function ListDirectory(dirToList)
local dirListing = {}
for file in lfs.dir(dirToList) do
if file ~= ".." and file ~= "." then
local fileAttr = lfs.attributes(dirToList .. file)
if fileAttr.mode == "directory" then
dirListing[file] = ListDirectory(dirToList .. file .. '/')
else
dirListing[file] = ""
end
fileNb = fileNb + 1
end
end
return dirListing
end
--dofile[[../Lua/DumpObject.lua]] -- My own dump routine
local dirListing = ListDirectory(dirToList)
--~ print("\n" .. DumpObject(dirListing))
print("Found " .. fileNb .. " files")
--~ os.exit()
-- Constants to change to adjust aspect
local initialOffsetX = 20
local offsetY = 50
local offsetIncrementX = 20
local offsetIncrementY = 12
local iconOffset = 10
local width = 800 -- Still arbitrary
local titleHeight = width/50
local height = offsetIncrementY * (fileNb + 1) + titleHeight
local outfile = "CairoDirTree." .. outputType
local ctxSurface
if outputType == 'svg' then
ctxSurface = cairo.SvgSurface(outfile, width, height)
else
ctxSurface = cairo.ImageSurface(CAIRO.FORMAT_RGB24, width, height)
end
local ctx = cairo.Context(ctxSurface)
-- Display a file name
-- file is the file name to display
-- offsetX is the indentation
function DisplayFile(file, bIsDir, offsetX)
if bIsDir then
ctx:save()
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)
ctx:set_source_rgb(0.5, 0.0, 0.7)
end
-- Display file name
ctx:move_to(offsetX, offsetY)
ctx:show_text(file)
if bIsDir then
ctx:new_sub_path() -- Position independent of latest move_to
-- Draw arc with absolute coordinates
ctx:arc(offsetX - iconOffset, offsetY - offsetIncrementY/3, offsetIncrementY/3, 0, TWO_PI)
-- Violet disk
ctx:set_source_rgb(0.7, 0.0, 0.7)
ctx:fill()
ctx:restore() -- Restore original settings
end
-- Increment line offset
offsetY = offsetY + offsetIncrementY
end
-- Erase background (white)
ctx:set_source_rgb(1.0, 1.0, 1.0)
ctx:paint()
--~ ctx:set_line_width(0.01)
-- Draw in dark blue
ctx:set_source_rgb(0.0, 0.0, 0.3)
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_BOLD)
ctx:set_font_size(titleHeight)
ctx:move_to(5, titleHeight)
-- Display title
ctx:show_text("Directory tree of " .. dirToList)
-- Select font for file names
ctx:select_font_face("Sans", CAIRO.FONT_SLANT_NORMAL, CAIRO.FONT_WEIGHT_NORMAL)
ctx:set_font_size(10)
offsetY = titleHeight * 2
-- Do the job
function DisplayDirectory(dirToList, offsetX)
for k, v in pairs(dirToList) do
--~ print(k, v)
if type(v) == "table" then
-- Sub-directory
DisplayFile(k, true, offsetX)
DisplayDirectory(v, offsetX + offsetIncrementX)
else
DisplayFile(k, false, offsetX)
end
end
end
DisplayDirectory(dirListing, initialOffsetX)
if outputType == 'svg' then
cairo.show_page(ctx)
else
--cairo.surface_write_to_png(ctxSurface, outfile)
ctxSurface:write_to_png(outfile)
end
ctx:destroy()
ctxSurface:destroy()
print("Found " .. fileNb .. " files")
Of course, you can change the styles. I didn't draw the connection lines, I didn't saw it as necessary. I might add them optionally later.
I recently had this error on a fresh OSX install of Node using homebrew.
Brew installed the latest at the time 13.8.0
.
I downgraded the last "stable" release of node.
sudo npm install -g n ## Installs Node Version Switcher
sudo n stable ## To switch to latest stable version
Then the rest of my npm installs finished and passed the dreaded gprc errors!
The LibreOffice writer comment has merit since the application can employ python macros. It seems to offer multiple benefits both for answering this question and furthering the macro base of LibreOffice. If this resolution is a one-off implementation, rather than to be used as part of a greater production program, opening the HTML in writer and saving the page as text would seem to resolve the issues discussed here.
You can create a one-way hash with bcrypt using PHP's crypt()
function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.
Find timestamp from DateTime:
private long ConvertToTimestamp(DateTime value)
{
TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
TimeZone localZone = TimeZone.CurrentTimeZone;
System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (NyTime - epoch);
return (long)Convert.ToDouble(span.TotalSeconds);
}
set the target
attribute of your <a>
element to "_tab"
EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp
EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):
_blank Opens the linked document in a new window or tab
_self Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top Opens the linked document in the full body of the window
framename Opens the linked document in a named frame
I was just working through this problem, and none of these solutions would work for me. I couldn't use the EmptyDataTemplate
property because I was creating my GridView
dynamically with custom fields which provide filters in the headers. I couldn't use the example almny posted because I'm using ObjectDataSource
s instead of DataSet
or DataTable
. However, I found this answer posted on another StackOverflow question, which links to this elegant solution that I was able to make work for my particular situation. It involves overriding the CreateChildControls
method of the GridView
to create the same header row that would have been created had there been real data. I thought it worth posting here, where it's likely to be found by other people in a similar fix.
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.
Aggregate the results from that table into a results cell.
The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.
this will set your session to keep everything till the browser is closed
session.setMaxinactiveinterval(-1);
and this should set it for 1 day
session.setMaxInactiveInterval(60*60*24);
jQuery Version
JavaScript (modified from a script I found on someone's site - I just can't find the site again, so I can't give the person credit):
$(document).ready(function() {
$("#bookmarkme").click(function() {
if (window.sidebar) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(location.href,document.title,"");
} else if(window.external) { // IE Favorite
window.external.AddFavorite(location.href,document.title); }
else if(window.opera && window.print) { // Opera Hotlist
this.title=document.title;
return true;
}
});
});
HTML:
<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
IE will show an error if you don't run it off a server (it doesn't allow JavaScript bookmarks via JavaScript when viewing it as a file://...
).
You can use the with_entities()
method to restrict which columns you'd like to return in the result. (documentation)
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.
Third times the charm. My guess is that this is a bug and Zhenya's answer suggests it's fixed in the latest version. I have version 0.99.1.1 and I've created the following solution:
import matplotlib.pyplot as plt
import numpy as np
def forceAspect(ax,aspect=1):
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
data = np.random.rand(10,20)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_xlabel('xlabel')
ax.set_aspect(2)
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
forceAspect(ax,aspect=1)
fig.savefig('force.png')
This is 'force.png':
Below are my unsuccessful, yet hopefully informative attempts.
Second Answer:
My 'original answer' below is overkill, as it does something similar to axes.set_aspect()
. I think you want to use axes.set_aspect('auto')
. I don't understand why this is the case, but it produces a square image plot for me, for example this script:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10,20)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_aspect('equal')
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
Produces an image plot with 'equal' aspect ratio: and one with 'auto' aspect ratio:
The code provided below in the 'original answer' provides a starting off point for an explicitly controlled aspect ratio, but it seems to be ignored once an imshow is called.
Original Answer:
Here's an example of a routine that will adjust the subplot parameters so that you get the desired aspect ratio:
import matplotlib.pyplot as plt
def adjustFigAspect(fig,aspect=1):
'''
Adjust the subplot parameters so that the figure has the correct
aspect ratio.
'''
xsize,ysize = fig.get_size_inches()
minsize = min(xsize,ysize)
xlim = .4*minsize/xsize
ylim = .4*minsize/ysize
if aspect < 1:
xlim *= aspect
else:
ylim /= aspect
fig.subplots_adjust(left=.5-xlim,
right=.5+xlim,
bottom=.5-ylim,
top=.5+ylim)
fig = plt.figure()
adjustFigAspect(fig,aspect=.5)
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))
fig.savefig('axAspect.png')
This produces a figure like so:
I can imagine if your having multiple subplots within the figure, you would want to include the number of y and x subplots as keyword parameters (defaulting to 1 each) to the routine provided. Then using those numbers and the hspace
and wspace
keywords, you can make all the subplots have the correct aspect ratio.
If you are trying to access the variable from another PHP file directly, you can include that file with include()
or include_once()
, giving you access to that variable. Note that this will include the entire first file in the second file.
I've got this working after doing the following:
Note: This doesn't give me the runtime exceptions either, it works.
I wanted to know (idx, key, value) for a python OrderedDict today (mapping of SKUs to quantities in order of the way they should appear on a receipt). The answers here were all bummers.
In python 3, at least, this way works and and makes sense.
In [1]: from collections import OrderedDict
...: od = OrderedDict()
...: od['a']='spam'
...: od['b']='ham'
...: od['c']='eggs'
...:
...: for i,(k,v) in enumerate(od.items()):
...: print('%d,%s,%s'%(i,k,v))
...:
0,a,spam
1,b,ham
2,c,eggs
An easy way I'm using:
file_put_contents($output_file, file_get_contents($base64_string));
This works well because file_get_contents
can read data from a URI, including a data:// URI.
Another tricky solution is to name elements of list and attach
it:
list_name = list(
head(iris),
head(swiss),
head(airquality)
)
names(list_name) <- paste("orca", seq_along(list_name), sep="")
attach(list_name)
orca1
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.
select
*
from
yourtable t
where
/* Greater or equal to the start of last month */
t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
/* Smaller or equal than one month ago */
t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)
Use Imagemagick, or better yet, Ghostscript.
http://www.ibm.com/developerworks/library/l-graf2/#N101C2 has an example for imagemagick:
convert foo.pdf pages-%03d.tiff
http://www.asmail.be/msg0055376363.html has an example for ghostscript:
gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit
I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
You can use two different techniques to achieve this.
The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;
).
The second is setting the link to point to a specific id in the page e.g.
<a href="mypage.html#sectionOne">section one</a>
Then if in your target page you'll have that ID the page will be scrolled automatically.
It just exits the method at that point. Once return
is executed, the rest of the code won't be executed.
eg.
public void test(int n) {
if (n == 1) {
return;
}
else if (n == 2) {
doStuff();
return;
}
doOtherStuff();
}
Note that the compiler is smart enough to tell you some code cannot be reached:
if (n == 3) {
return;
youWillGetAnError(); //compiler error here
}
A couple of things wrong here.
Do you really want to open and close the connection for every single log entry?
Shouldn't you be using SqlCommand
instead of SqlDataAdapter
?
The data adapter (or SqlCommand
) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).
I highly recommend a C# / SQL Server tutorial.
To use a theme for all the application, and don't use the second parameter to style your Dialog
<style name="MyTheme" parent="Base.Theme.AppCompat.Light">
<item name="alertDialogTheme">@style/dialog</item>
<item name="colorAccent">@color/accent</item>
</style>
<style name="dialog" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/accent</item>
</style>
On my app using a color accent in theme don't show the alertDialog's buttons with the theme colorAccent I have to add a dialog style in the theme.
Try this,
this.searchAll = element(by.xpath('path here'));
this.searchAll.sendKeys('');
Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.
While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.
Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.
Just want to reiterate this will work in pandas >= 0.9.1:
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
I'm creating an issue about detecting integer overflows also.
EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247
Update as it helps others:
To have all columns as str, one can do this (from the comment):
pd.read_csv('sample.csv', dtype = str)
To have most or selective columns as str, one can do this:
# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str' for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)
I was going crazy trying to find why System
process held an open handle on the EXE I was working with for another minute after it was terminated, and I was getting the same error as the OP.
The reason was that the previous developers did not wrap IDisposable
objects in using(){}
. Once the IDisposable
objects correctly destroyed themselves, the error occurred no more and I was able to rebuild immediately.
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range()
function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range()
function to produce a list and pass into a function.
Therefore, in this case, Python3 is less convenient as compared to Python2 because:
xrange()
and range()
; range()
and list(range())
Nonetheless, you can still use list expansion in this way:
[*range(N)]
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
dict
keys need to be hashable. Lists are Mutable and they do not provide a valid hash method.
While not strictly serialization, json may be reasonable approach here. That will handled nested dicts and lists, and data as long as your data is "simple": strings, and basic numeric types.
I modified Jayram Singh's post slightly in order to replace every instance of a '!' character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I'm very new at coding so apologies if my post is inappropriate in any way, but this worked for me.
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1
# if word=='!'replace w/ [n] & increment n; else append same word to
# file2
for line in f1:
for word in line:
if word == '!':
f2.write(word.replace('!', f'[{n}]'))
n += 1
else:
f2.write(word)
f1.close()
f2.close()
You don't need to send messages.
Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.
The built-in timeit module works best from the IPython command line.
To time functions from within a module:
from timeit import default_timer as timer
import sys
def timefunc(func, *args, **kwargs):
"""Time a function.
args:
iterations=3
Usage example:
timeit(myfunc, 1, b=2)
"""
try:
iterations = kwargs.pop('iterations')
except KeyError:
iterations = 3
elapsed = sys.maxsize
for _ in range(iterations):
start = timer()
result = func(*args, **kwargs)
elapsed = min(timer() - start, elapsed)
print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
return result
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
Here is a method I wrote that behaves like all other programming languages:
String.prototype.insert = function(index, string) {
if (index > 0) {
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
_x000D_
For those of you that are interested in this topic, I should mention how I create the DMG:
hdiutil create XXX.dmg -volname "YYY" -fs HFS+ -srcfolder "ZZZ"
where
XXX == disk image file name (duh!)
YYY == window title displayed when DMG is opened
ZZZ == Path to a folder containing the files that will be copied into the DMG
Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
equivalent to
-lpthread
I just want to say guys:
Only Play With Margin
It is a lot easier to add space between <li>
if you play with margin.
Case C) is the fastest. Having this as an extension:
Public Module MyExtensions
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
End Sub
End Module
Usage:
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)
' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec
Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}
The reference to the string is passed by value. There's a big difference between passing a reference by value and passing an object by reference. It's unfortunate that the word "reference" is used in both cases.
If you do pass the string reference by reference, it will work as you expect:
using System;
class Test
{
public static void Main()
{
string test = "before passing";
Console.WriteLine(test);
TestI(ref test);
Console.WriteLine(test);
}
public static void TestI(ref string test)
{
test = "after passing";
}
}
Now you need to distinguish between making changes to the object which a reference refers to, and making a change to a variable (such as a parameter) to let it refer to a different object. We can't make changes to a string because strings are immutable, but we can demonstrate it with a StringBuilder
instead:
using System;
using System.Text;
class Test
{
public static void Main()
{
StringBuilder test = new StringBuilder();
Console.WriteLine(test);
TestI(test);
Console.WriteLine(test);
}
public static void TestI(StringBuilder test)
{
// Note that we're not changing the value
// of the "test" parameter - we're changing
// the data in the object it's referring to
test.Append("changing");
}
}
See my article on parameter passing for more details.
It looks like the files npm
uses to edit its config files are not created on a clean install, as npm
has a default option for each one. This is why you can still get options with npm config get <option>
: having those files only overrides the defaults, it doesn't create the options from scratch.
I had never touched my npm config
stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc
(on a Windows 8.1 machine with Git Bash
), yet I could run npm config get <something>
and, if it was a correct npm
option, it returned a value. When I ran npm config set <option> <value>
, the file ~/.npmrc
seemed to be created automatically, with the option & its value as the only non-commented-out line.
As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc
is deleted, too, and recreated if you set
anything else later.
In your case (assuming it is still the same over a year later), it looks like you never set the proxy
option in npm
. Therefore, as npm
's config
help page says, it is set to whatever your http_proxy
(case-insensitive) environment variable is. This means there is nothing to delete
, unless you want to "delete" your HTTP proxy, although you could set
the option or environment variable to something else and hope neither breaks your set-up somehow.
You can use %~dp0
, d means the drive only, p means the path only, 0 is the argument for the full filename of the batch file.
For example if the file path was C:\Users\Oliver\Desktop\example.bat then the argument would equal C:\Users\Oliver\Desktop\, also you can use the command set cpath=%~dp0 && set cpath=%cpath:~0,-1%
and use the %cpath%
variable to remove the trailing slash.
Use
<string name="win_percentage">%d%% wins</string>
to get
80% wins
as a formatted string.
I'm using String.format()
method to get the number inserted instead of %d
.
You can use the first method:
$('li').first()
btw I agree with Nick Craver -- use document.getElementById()...
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
Giving us the whole error message would be much more useful. If it's for make install then you're probably trying to install something to a system directory and you're not root. If you have root access then you can run
sudo make install
or log in as root and do the whole process as root.
your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript
You could also just wrap that in a form and have hidden fields for id
, productid
, and unitrate
Here's a sample for ya.
HTML
<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate" href="/someurl?quantity=1">click me</a>
JS
function changeUrl(){
var url = document.getElementById("imgUpdate").getAttribute('href');
var inputValue = document.getElementById('ss').value;
var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}
function GiveMeTheQueryStringParameterValue(parameterName, input) {
parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
var results = regex.exec(input);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
this could be cleaned up and expanded as you need it but the example works
The solution is just 3 lines:
@media only screen and (max-width: 479px) {
.nav-tabs > li {
width: 100%;
}
}
..but you have to accept the idea of tabs that wrap to more lines in other dimensions.
Of course you can achieve a horizontal scrolling area with white-space: nowrap
trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!
Look in the SDK Manager what is your highest Android SDK Build-tools
version, and copy this version number in your project build.gradle
file, in the android/buildToolsVersion
property (for me, version was "18.1.1").
Hope it help!
You can use Regex.Match
if(text.matches("\\d*")&& text.length() > 2){
System.out.println("number");
}
Or you could use onversions like Integer.parseInt(String)
or better Long.parseLong(String)
for bigger numbers
like for example:
private boolean onlyContainsNumbers(String text) {
try {
Long.parseLong(text);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
And then test with:
if (onlyContainsNumbers(text) && text.length() > 2) {
// do Stuff
}
you can use stuff() to convert rows as comma separated values
select
EmployeeID,
stuff((
SELECT ',' + FPProjectMaster.GroupName
FROM FPProjectInfo AS t INNER JOIN
FPProjectMaster ON t.ProjectID = FPProjectMaster.ProjectID
WHERE (t.EmployeeID = FPProjectInfo.EmployeeID)
And t.STatusID = 1
ORDER BY t.ProjectID
for xml path('')
),1,1,'') as name_csv
from FPProjectInfo
group by EmployeeID;
Thanks @AlexKuznetsov for the reference to get this answer.
I solved the problem updating all packages from Android SDK Manager and also, I had to install Extras -> Android Support Repository
.
If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...
$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);
$image->scaleImage(100,200,FALSE);
$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);
You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight();
and $image->getImageWidth();
Hercules is fantastic. It's a fully functioning tcp/udp client/server, amazing for debugging sockets. More details on the web site.
The aptitude --download-only ...
approach only works if you have a debian distro with internet connection in your hands.
If you don't, I think it is better to run the following script on the disconnected debian machine:
apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list
move the downloads.list file into a connected linux (or non linux) machine, and run:
wget --input-file myurilist
this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.
credits: http://www.tuxradar.com/answers/517
PS I basically copied the blog post because it was not very readable, and in case the post will disappear.
The difference is :
"If you use !=
, it returns sub-second. If you use <>
, it takes 7 seconds to return. Both return the right answer."
Oracle not equals (!=) SQL operator
Regards
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
You basically need a helper method to read a stream into memory. This works pretty well:
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
Then you'd call it with:
public static byte[] loadFile(String sourcePath) throws IOException
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
Don't mix up text and binary data - it only leads to tears.
Using boost tokenizer to parse records, see here for more details.
ifstream in(data.c_str());
if (!in.is_open()) return 1;
typedef tokenizer< escaped_list_separator<char> > Tokenizer;
vector< string > vec;
string line;
while (getline(in,line))
{
Tokenizer tok(line);
vec.assign(tok.begin(),tok.end());
/// do something with the record
if (vec.size() < 3) continue;
copy(vec.begin(), vec.end(),
ostream_iterator<string>(cout, "|"));
cout << "\n----------------------" << endl;
}
To get each sum in a separate column:
Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash')
and CDate<=SYSDATETIME()
and CStatus='Active';
You use the hash mark like this
# This is a comment in Powershell
Wikipedia has a good page for keeping track of how to do comments in several popular languages
http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(syntax)#Comments
All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.
Download and install from http://www.microsoft.com/en-us/download/details.aspx?id=34595. You need Windows 7 SP1 though.
It's worth keeping in mind that PowerShell 3 on Windows 7 does not have all the cmdlets as PowerShell 3 on Windows 8. So you may still encounter cmdlets that are not present on your system.
use following LoadType method to use System.Reflection to load all registered(GAC) and referenced assemblies and check for typeName
public Type[] LoadType(string typeName)
{
return LoadType(typeName, true);
}
public Type[] LoadType(string typeName, bool referenced)
{
return LoadType(typeName, referenced, true);
}
private Type[] LoadType(string typeName, bool referenced, bool gac)
{
//check for problematic work
if (string.IsNullOrEmpty(typeName) || !referenced && !gac)
return new Type[] { };
Assembly currentAssembly = Assembly.GetExecutingAssembly();
List<string> assemblyFullnames = new List<string>();
List<Type> types = new List<Type>();
if (referenced)
{ //Check refrenced assemblies
foreach (AssemblyName assemblyName in currentAssembly.GetReferencedAssemblies())
{
//Load method resolve refrenced loaded assembly
Assembly assembly = Assembly.Load(assemblyName.FullName);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
}
if (gac)
{
//GAC files
string gacPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\assembly";
var files = GetGlobalAssemblyCacheFiles(gacPath);
foreach (string file in files)
{
try
{
//reflection only
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
catch
{
//your custom handling
}
}
}
return types.ToArray();
}
public static string[] GetGlobalAssemblyCacheFiles(string path)
{
List<string> files = new List<string>();
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles("*.dll"))
{
files.Add(fi.FullName);
}
foreach (DirectoryInfo diChild in di.GetDirectories())
{
var files2 = GetGlobalAssemblyCacheFiles(diChild.FullName);
files.AddRange(files2);
}
return files.ToArray();
}
To change only the second column of a table use the following:
General Case:
table td + td{ /* this will go to the 2nd column of a table directly */
background:red
}
Your case:
.countTable table table td + td{
background: red
}
Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question
You can use .concat
method to create copy of your array with new data:
this.setState({ myArray: this.state.myArray.concat('new value') })
But beware of special behaviour of .concat
method when passing arrays - [1, 2].concat(['foo', 3], 'bar')
will result in [1, 2, 'foo', 3, 'bar']
.
Have you read about the nohup command?
For strings or input values you could simply use this:
var a = $('#some_hidden_var').val(),
b = a.substr(0);
ENV['RAILS_ENV']
is now deprecated.
You should use Rails.env
which is clearly much nicer.
What follows from the code and code docs is that coalesce(n)
is the same as coalesce(n, shuffle = false)
and repartition(n)
is the same as coalesce(n, shuffle = true)
Thus, both coalesce
and repartition
can be used to increase number of partitions
With
shuffle = true
, you can actually coalesce to a larger number of partitions. This is useful if you have a small number of partitions, say 100, potentially with a few partitions being abnormally large.
Another important note to accentuate is that if you drastically decrease number of partitions you should consider using shuffled version of coalesce
(same as repartition
in that case). This will allow your computations be performed in parallel on parent partitions (multiple task).
However, if you're doing a drastic coalesce, e.g. to
numPartitions = 1
, this may result in your computation taking place on fewer nodes than you like (e.g. one node in the case ofnumPartitions = 1
). To avoid this, you can passshuffle = true
. This will add a shuffle step, but means the current upstream partitions will be executed in parallel (per whatever the current partitioning is).
Please also refer to the related answer here
If you have a reporting services infrastructure available to you, use it. You will find RDL development to be a bit more pleasant. You can preview the report, easily setup parameters, etc.
Use VisualTreeHelper.GetParent or the recursive function below to find the parent window.
public static Window FindParentWindow(DependencyObject child)
{
DependencyObject parent= VisualTreeHelper.GetParent(child);
//CHeck if this is the end of the tree
if (parent == null) return null;
Window parentWindow = parent as Window;
if (parentWindow != null)
{
return parentWindow;
}
else
{
//use recursion until it reaches a Window
return FindParentWindow(parent);
}
}
Please follow these Steps:
For Eclipse:
Properties
Java Build Path
Libraries
tab. There click the Add External JARs
Button on the Right pane.android-support-v4.jar
file, usually the path for the Jar file is :android-support-v4.jar
Library, navigate to the Order and Export
tab and put check mark on the android-support-v4
Library file.For Android Studio:
Short Version:
build.gradle
file: implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'
Long Version:
Go to File -> Project Structure
Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"
Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"
Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.
Rebuild your project and now everything should work.
Further reading regarding this Question:
I hope this helps.
A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:
$ curl -I https://atmosphere.meteor.com HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive
However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.
<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script>
If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.
From the documentation:
[...] the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
If you print the unicode point values of the array then it will get clear.
console.log("140000".charCodeAt(0));_x000D_
console.log("104".charCodeAt(0));_x000D_
console.log("99".charCodeAt(0));_x000D_
_x000D_
//Note that we only look at the first index of the number "charCodeAt( 0 )"
_x000D_
This returns: "49, 49, 57".
49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)
Now, because 140000 and 104 returned the same values (49) it cuts the first index and checks again:
console.log("40000".charCodeAt(0));_x000D_
console.log("04".charCodeAt(0));_x000D_
_x000D_
//Note that we only look at the first index of the number "charCodeAt( 0 )"
_x000D_
52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)
If we sort this, then we will get:
40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)
so 104 comes before 140000.
So the final result will be:
var numArray = [140000, 104, 99];_x000D_
numArray = numArray.sort();_x000D_
console.log(numArray)
_x000D_
104, 140000, 99
Conclusion:
sort()
does sorting by only looking at the first index of the numbers. sort()
does not care if a whole number is bigger than another, it compares the value of the unicode of the digits, and if there are two equal unicode values, then it checks if there is a next digit and compares it as well.
To sort correctly, you have to pass a compare function to sort()
like explained here.
Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
Best answer: https://stackoverflow.com/a/19168199/413127
Example for
http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
Now with Kotlin
val myUrl = Uri.Builder().apply {
scheme("https")
authority("www.myawesomesite.com")
appendPath("turtles")
appendPath("types")
appendQueryParameter("type", "1")
appendQueryParameter("sort", "relevance")
fragment("section-name")
build()
}.toString()
You can copy, past and execute this piece of code to get all table record counts into a table. Note: Code is commented with instructions
create procedure RowCountsPro
as
begin
--drop the table if exist on each exicution
IF OBJECT_ID (N'dbo.RowCounts', N'U') IS NOT NULL
DROP TABLE dbo.RowCounts;
-- creating new table
CREATE TABLE RowCounts
( [TableName] VARCHAR(150)
, [RowCount] INT
, [Reserved] NVARCHAR(50)
, [Data] NVARCHAR(50)
, [Index_Size] NVARCHAR(50)
, [UnUsed] NVARCHAR(50))
--inserting all records
INSERT INTO RowCounts([TableName], [RowCount],[Reserved],[Data],[Index_Size],[UnUsed])
-- "sp_MSforeachtable" System Procedure, 'sp_spaceused "?"' param to get records and resources used
EXEC sp_MSforeachtable 'sp_spaceused "?"'
-- selecting data and returning a table of data
SELECT [TableName], [RowCount],[Reserved],[Data],[Index_Size],[UnUsed]
FROM RowCounts
ORDER BY [TableName]
end
I have tested this code and it works fine on SQL Server 2014.
Simple and easy way to show back button on toolbar
Paste this code in onCreate method
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Paste this override method outside the onCreate method
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here https://github.com/artybug/TNSNamesSync/releases
The docs are here: https://github.com/artchik/TNSNamesSync/blob/master/README.md
This is for Windows only, though.
In PostreSQL you can use SIMILAR TO operator (more):
-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';
I got this idea from someone. - don't know who. Let the OS do the heavy lifting.
public bool IsPathFileNameGood(string fname)
{
bool rc = Constants.Fail;
try
{
this._stream = new StreamWriter(fname, true);
rc = Constants.Pass;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Problem opening file");
rc = Constants.Fail;
}
return rc;
}
There's also another way to do this-
select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;
GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.
A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)
Improving the first answer just get rid of the padding and add line-height
and vertical-align
:
.numberCircle {
border-radius: 50%;
width: 36px;
height: 36px;
line-height: 36px;
vertical-align:middle;
background: #fff;
border: 2px solid #666;
color: #666;
text-align: center;
font: 32px Arial, sans-serif;
}
The shortest version.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")));
page 1 : Detail page 2 : <% String id = request.getParameter("userid");%> // now you can using id for sql query of hsql detail product
If you somehow change scrollView contentSize (ex. add something to stackView which is inside scrollView) you must call scrollView.layoutIfNeeded()
before scrolling, otherwise it does nothing.
Example:
scrollView.layoutIfNeeded()
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
if(bottomOffset.y > 0) {
scrollView.setContentOffset(bottomOffset, animated: true)
}
The only thing that can be a null
is a non-primivite.
A boolean
which can only hold TRUE
or FALSE
is a primitive. The TRUE
/FALSE
in memory are actually numbers (0
and 1
)
0 = FALSE
1 = TRUE
So when you instantiate an object it will be null
String str; // will equal null
On the other hand if you instaniate a primitive it will be assigned to 0 default.
boolean isTrue; // will be 0
int i; // will be 0
You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}
This is relatively simple example and worked for me.
hr {
width: 70%;
margin-left: auto;
margin-right: auto;
}
Resource: https://www.w3docs.com/snippets/css/how-to-style-a-horizontal-line.html
integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.
Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:
Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):
openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A
crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.
crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.
Here is a case when requesting “use-credentials” from CDN:
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
crossorigin="use-credentials"></script>
A browser can cancel the request if crossorigin incorrectly set.
Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link
Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity
From my experience, if your application is designed to work in both portrait and landscape orientation, you need to declare the variable cam
as static. Otherwise, onDestroy()
, which is called on switching orientation, destroys it but doesn't release Camera so it's not possible to reopen it again.
package com.example.flashlight;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Camera cam = null;// has to be static, otherwise onDestroy() destroys it
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void flashLightOn(View view) {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOn()",
Toast.LENGTH_SHORT).show();
}
}
public void flashLightOff(View view) {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam.stopPreview();
cam.release();
cam = null;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOff",
Toast.LENGTH_SHORT).show();
}
}
}
to manifest I had to put this line
<uses-permission android:name="android.permission.CAMERA" />
from http://developer.android.com/reference/android/hardware/Camera.html
suggested lines above wasn't working for me.