I find this library helpful. 3.128 kb of pure convenience.
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
Two's complement is mainly used for the following reasons:
Per the TypeScript 2.3 release notes on "New --downlevelIteration
":
for..of statements
, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using--downlevelIteration
This is not enabled by default! Add "downlevelIteration": true
to your tsconfig.json
, or pass --downlevelIteration
flag to tsc
, to get full iterator support.
With this in place, you can write for (let keyval of myMap) {...}
and keyval
's type will be automatically inferred.
Why is this turned off by default? According to TypeScript contributor @aluanhaddad,
It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).
If you can target ES2015 ("target": "es2015"
in tsconfig.json
or tsc --target ES2015
) or later, enabling downlevelIteration
is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from
conversion or forEach
or some other workaround).
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
If you need to run inside a shell:
shell.run(["sh", "-c", "echo -n hello"])
The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.
For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.
The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.
Another great resource is the NIST Dictionary of Data structures and algorithms.
Is your server sending data as Content-Type "*/json"
? If not, modify the response headers accordingly. Sending "application/json"
would be fine, for example.
Also, see the Stack Overflow question How to detect what .NET Framework versions and service packs are installed? which also mentions:
There is an official Microsoft answer to this question at the knowledge base article [How to determine which versions and service pack levels of the Microsoft .NET Framework are installed][2]
Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied.
Unfortunately, it doesn't appear to work, because the mscorlib.dll
version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll
version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... Why would the official Microsoft answer be so misinformed?
.bak files are database backups. You can restore the backup with the method below:
How to: Restore a Database Backup (SQL Server Management Studio)
Like @SharadHolani said. This won't match every word beginning with "stop"
. Only if it's at the beginning of a line like "stop going". @Waxo gave the right answer:
This one is slightly better, if you want to match any word beginning with "stop" and containing nothing but letters from A to Z.
\bstop[a-zA-Z]*\b
This would match all
stop (1)
stop random (2)
stopping (3)
want to stop (4)
please stop (5)
But
/^stop[a-zA-Z]*/
would only match (1) until (3), but not (4) & (5)
/appointments?users=1d1,1d2..
is fine. It's pretty much your only sensible option since you can't pass in a body with a GET.
Look at http://ss64.com/nt/if.html for an answer; the command is IF [%1]==[] GOTO NO_ARGUMENT
or similar.
Without the loop:
function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}
// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN
Also isn't it better not to use loop tests that have to be evaluated?
For example, instead of:
for (var i = 0; i < hex.length; i++){}
have
for (var i = 0, var j = hex.length; i < j; i++){}
Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.
You can even add a dummy div
to the container and set something like padding-top: 56.25%
to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).
Padding and margin use the percentage of the width, that's really the trick here.
Maven will fail the build if it detects a cycle, as the dependencies must be a tree.
You may find that you have additional declarations in the manifest.mf over those defined in the pom.xml. any extra declaration could introduce a cycle that wouldn't be apparent to Maven.
Made an improvement code by @Ipsita - for use asynchronous read\write file I/O
readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
TextReader tr = new StreamReader(logPath);
string data = await tr.ReadLineAsync();
tr.Close();
TextWriter tw = new StreamWriter(logPath);
await tw.WriteLineAsync(data + dataToWrite);
tw.Close();
}
...
await WriteToLogAsync("Write this to file");
<input type="text" class="form-control timepicker2" ng-model='programRow.StationAuxiliaryTime.ST88' />
accessing scope value
assume that programRow.StationAuxiliaryTime is an array of object
$('.timepicker2').on('click', function ()
{
var currentElement = $(this);
var scopeValues = angular.element(currentElement).scope();
var model = currentElement.attr('ng-model');
var stationNumber = model.split('.')[2];
var val = '';
if (model.indexOf("StationWaterTime") > 0) {
val = scopeValues.programRow.StationWaterTime[stationNumber];
}
else {
val = scopeValues.programRow.StationAuxiliaryTime[stationNumber];
}
currentElement.timepicker('setTime', val);
});
I personally need to ensure the page keeps state, so all the text boxes and other input fields retain their values. by doing meta refresh it's like a new post, IsPostBack is always false so all your controls are in the initialized state again. To retain state put this at the end of your Page_Load(). create a hidden button on the page with an event hooked up, something like butRefresh with event butRefresh_Click(...). This code sets a timer on the page to fire a postback just like a user clicked the refresh button themselves. all state and session is retained. Enjoy! (P.S. you may need to put the directive in the @Page header EnableEventValidation="false" if you receive an error on postback.
//tell the browser to post back again in 5 seconds while keeping state of all controls
ClientScript.RegisterClientScriptBlock(this.GetType(), "refresh", "<script>setTimeout(function(){ " + ClientScript.GetPostBackClientHyperlink(butRefresh, "refresh") + " },5000);</script>");
Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
console.log('style changed!');
});
});
var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });
The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.
Support is good in modern browsers including IE 11+.
To select and element where you know only the attribute value you can use the below jQuery script
var src = $('.conversation_img[alt="example"]').attr('src');
Please refer the jQuery Documentation for attribute equals selectors
Please also refer to the example in Demo
Following is the code incase you are not able to access the demo..
HTML
<div>
<img alt="example" src="\images\show.jpg" />
<img alt="exampleAll" src="\images\showAll.jpg" />
</div>
SCRIPT JQUERY
var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);
var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );
Output will be
Two Alert messages each having values
The previous answers did not work for me, so I decided to improve this.
You should work with url('')
, and not with value.
<li *ngFor="let item of items">
<div
class="img-wrapper"
[ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
</div>
</li>
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
Forgot to relate to the first code snippet. I wouldn't use forEach
at all. Since you are collecting the elements of the Stream
into a List
, it would make more sense to end the Stream
processing with collect
. Then you would need peek
in order to set the ID.
List<Entry> updatedEntries =
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());
For the second snippet, forEach
can execute multiple expressions, just like any lambda expression can :
entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});
However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null
) if you do.
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
?hange USB connection mode from MTP to Camera (for Nexus 7) or, possibly, to Mass Storage or something else (for other devices). This option is usually under Settings -> Storage
. Then connect the device again, you'll get the authorization dialog.
MTP has been known to interfere with USB debugging -- these two did not work together at all on majority of older devices. Nexus 7 and many newer devices do allow both to work alongside, but this particular issue suggests it's not all that smooth yet.
Bonus -- checklist for when adb
is not behaving well:
adb kill-server
followed by adb start-server
Settings -> Developer Options -> USB Debugging
-- switch off and on/etc/udev/rules.d/51-android.rules
(again, universal solution: https://github.com/snowdream/51-android)~/.android
is owned by you, not root
(and upvote this answer)I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
First in your terminal:
rails g migration change_date_format_in_my_table
Then in your migration file:
For Rails >= 3.2:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
I recommend to use memcpy() for copying data.
Also if we assign a buffer to another as array2 = array1
, both array have same memory and any change in the arrary1 deflects in array2 too. But we use memcpy, both buffer have different array. I recommend memcpy() because strcpy and related function do not copy NULL character.
git clone --single-branch --branch <branchname> <remote-repo>
The --single-branch
option is valid from version 1.7.10 and later.
Please see also the other answer which many people prefer.
You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url
you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.
Again, that is not to say git clone --branch
is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.
This should work:
txtfarmersize = Convert.ToInt32(reader["farmsize"]);
Sometimes I have been getting some errors when you want to pass httpBody serialized to Data
from Dictionary
, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary
.
Depending on your requirements one easy solution would be to create a String
instead of Dictionary
and convert it to Data
. You have the code samples below written on Objective-C
and Swift 3.0
.
// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Handle your response here
}];
// Fire the request
[dataTask resume];
// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)
// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!) // Note: This is a demo, that's why I use implicitly unwrapped optional
// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)
// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData
// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
// Handle your response here
}
// Fire the request
dataTask.resume()
The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of
-13 % 64
the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51 -13 - (-64) = -13 + 64 = 51
I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1
PyCharm - Preferences - Project interpreter - Cog symbol - Show All
At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.
Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.
If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.
I think better to used
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise, false is returned.
Tweaked version from Techie Delight:
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> strings;
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
strings.push_back(str.substr(start, end - start));
}
return strings;
}
in most cases, got no authentication method error when using the wrong username for logging in. But I do find something else if you still struggle with connection issue and you have tried all the options above.
I created couple Linux VM and try to reproduce such connection issue, one thing I found is, when AWS asked you name your key pair, DO NOT user blank space (" ") and dot (".") in key pair name, even AWS actually allow you to do so.
ex. when I named the key pair as "AWS.FREE.LINUX", connection always be refused. When I named as "AWS_FREE_LINUX", everything works fine.
Hope this will help a little bit.
If you are using Zsh, then try to add this line in ~/.zshrc file & restart terminal.
export JAVA_HOME=$(/usr/libexec/java_home)
I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.
Otherwise you're paving way to mess that HTML ended up in.
For some reason in Angular 6 simply importing the FormsModule did not fix my issue. What finally fixed my issue was by adding
import { CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule],
})
export class MyClass{
}
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
Using Excel 2010 x64
. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:
Swap the data columns, to end with X_data in column A and Y_data in column B.
My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me:
an Excel XY plot literally wants {x,y}
pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away.
For me an XY plot means Y=f(X)
plotted.
Adding these two lines fixed this problem for me
"responsive": true,
"bAutoWidth": true
There is now a responsive plugin available: https://datatables.net/extensions/responsive/. However, in my experience I have found that there are still a few bugs. It's still the best solution I've found so far.
Try to use the rack-cors gem. And add the header field in your Ajax call.
There are subtle differences as to how the fileName
you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream()
and Class.getResourceAsStream()
. These two methods will locate the resource differently.
In Class.getResourceAsStream(path)
, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt")
will look for a file in your classpath at the following location: "java/lang/myfile.txt"
. If your path starts with a /
, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt")
will look at the following location in your class path ./myfile.txt
.
ClassLoader.getResourceAsStream(path)
will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt")
and String.class.getClassLoader().getResourceAsStream("/myfile.txt")
will both look for a file in your classpath at the following location: ./myfile.txt
.
Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.
In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
instead of this.getClass().getClassLoader().getResourceAsStream(fileName)
. this.getClass().getResourceAsStream()
will also work.
Read this article for more detailed information about that particular problem.
One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.
So I've looked at the source code of Tomcat's WebAppClassLoader
for several versions of Tomcat. The implementation of findResource(String name)
(which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.
In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt")
may not produce the same result as classLoader.getResourceAsStream("resource.txt")
event though it should (since that what the Javadoc specifies). [source code]
In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]
As a result, you have to be extra careful when using ClassLoader.getResourceAsStream()
or Class.getResourceAsStream()
on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt")
actually calls classLoader.getResourceAsStream("resource.txt")
(the leading /
is stripped).
I know this question is old, but between all the answers, I miss one that is a common approach for this use-case in XSLT development.
I am imagining that the missing code from the OP looks something like this:
<xsl:template match="category">
<xsl:choose>
<xsl:when test="categoryName !=null">
<xsl:value-of select="categoryName " />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="other" />
</xsl:otherwise>
</xsl:choose>
</category>
And that the input looks something like this:
<categories>
<category>
<categoryName>Books</categoryName>
</category>
<category>
<categoryName>Magazines</categoryName>
<categoryName>Periodicals</categoryName>
<categoryName>Journals</categoryName>
</category>
<category>
<categoryName><!-- please fill in category --></categoryName>
</category>
<category>
<categoryName />
</category>
<category />
</categories>
I.e., I assume there can be zero, empty, single or multiple categoryName
elements. To deal with all these cases using xsl:choose
-style constructs, or in other words, imperatively, is quickly getting messy (even more so if elements can be at different levels!). A typical programming idiom in XSLT is using templates (hence the T in XSLT), which is declarative programming, not imperative (you don't tell the processor what to do, you just tell what you want output if certain conditions are met). For this use-case, that can look something like the following:
<!-- positive test, any category with a valid categoryName -->
<xsl:template match="category[categoryName[text()]]">
<xsl:apply-templates />
</xsl:template>
<!-- any other category (without categoryName, "null", with comments etc) -->
<xsl:template match="category">
<xsl:text>Category: Other</xsl:text>
</xsl:template>
<!-- matching the categoryName itself for easy handling of multiple names -->
<xsl:template match="categoryName">
<xsl:text>Category: </xsl:text>
<xsl:value-of select="." />
</xsl:template>
This works (with any XSLT version), because the first one above has a higher precedence (it has a predicate). The "fall-through" matching template, the second one, catches anything that is not valid. The third one then takes care of outputting the categoryName
value in a proper way.
Note that in this scenario there is no need to specifially match categories
or category
, because the processor will automatically process all children, unless we tell it otherwise (in this example, the second and third template do not further process the children, because there is no xsl:apply-templates
in them).
This approach is more easily extendible then the imperative approach, because it automically deals with multiple categories and it can be expanded for other elements or exceptions by just adding another matching template. Programming without if-branches.
Note: there is no such thing as null
in XML. There is xsi:nil, but that is rarely used, especially rarely in untyped scenarios without a schema of some sort.
You can use the ProcessLifecycleOwner attaching a lifecycle observer to it.
public class ForegroundLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onAppCreated() {
Timber.d("onAppCreated() called");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppStarted() {
Timber.d("onAppStarted() called");
}
@OnLifecycleEvent(Event.ON_RESUME)
public void onAppResumed() {
Timber.d("onAppResumed() called");
}
@OnLifecycleEvent(Event.ON_PAUSE)
public void onAppPaused() {
Timber.d("onAppPaused() called");
}
@OnLifecycleEvent(Event.ON_STOP)
public void onAppStopped() {
Timber.d("onAppStopped() called");
}
}
then on the onCreate()
of your Application class you call this:
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ForegroundLifecycleObserver());
with this you will be able to capture the events of ON_PAUSE
and ON_STOP
of your application that happen when it goes in background.
As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.
Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class
(or rather, a subclass of Class
) corresponding to it. (When you say class Foo
, you're really declaring a constant Foo
and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.
The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.
In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.
The most easiest way would be to use unfactor
function from package varhandle which can accept a factor vector or even a dataframe:
unfactor(your_factor_variable)
This example can be a quick start:
x <- rep(c("a", "b", "c"), 20)
y <- rep(c(1, 1, 0), 20)
class(x) # -> "character"
class(y) # -> "numeric"
x <- factor(x)
y <- factor(y)
class(x) # -> "factor"
class(y) # -> "factor"
library(varhandle)
x <- unfactor(x)
y <- unfactor(y)
class(x) # -> "character"
class(y) # -> "numeric"
You can also use it on a dataframe. For example the iris
dataset:
sapply(iris, class)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species "numeric" "numeric" "numeric" "numeric" "factor"
# load the package
library("varhandle")
# pass the iris to unfactor
tmp_iris <- unfactor(iris)
# check the classes of the columns
sapply(tmp_iris, class)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species "numeric" "numeric" "numeric" "numeric" "character"
# check if the last column is correctly converted
tmp_iris$Species
[1] "setosa" "setosa" "setosa" "setosa" "setosa" [6] "setosa" "setosa" "setosa" "setosa" "setosa" [11] "setosa" "setosa" "setosa" "setosa" "setosa" [16] "setosa" "setosa" "setosa" "setosa" "setosa" [21] "setosa" "setosa" "setosa" "setosa" "setosa" [26] "setosa" "setosa" "setosa" "setosa" "setosa" [31] "setosa" "setosa" "setosa" "setosa" "setosa" [36] "setosa" "setosa" "setosa" "setosa" "setosa" [41] "setosa" "setosa" "setosa" "setosa" "setosa" [46] "setosa" "setosa" "setosa" "setosa" "setosa" [51] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [56] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [61] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [66] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [71] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [76] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [81] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [86] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [91] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [96] "versicolor" "versicolor" "versicolor" "versicolor" "versicolor" [101] "virginica" "virginica" "virginica" "virginica" "virginica" [106] "virginica" "virginica" "virginica" "virginica" "virginica" [111] "virginica" "virginica" "virginica" "virginica" "virginica" [116] "virginica" "virginica" "virginica" "virginica" "virginica" [121] "virginica" "virginica" "virginica" "virginica" "virginica" [126] "virginica" "virginica" "virginica" "virginica" "virginica" [131] "virginica" "virginica" "virginica" "virginica" "virginica" [136] "virginica" "virginica" "virginica" "virginica" "virginica" [141] "virginica" "virginica" "virginica" "virginica" "virginica" [146] "virginica" "virginica" "virginica" "virginica" "virginica"
This is the required source code :
public static void openKeypad(final Context context, final View v)
{
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
Log.e("openKeypad", "Inside Handler");
}
},300);}
For details , Please go through this link. This helped me. https://github.com/Nikhillosalka/Keyboard/blob/master/README.md
SELECT username FROM all_users ORDER BY username;
there is a function called isNaN
it return true if it's (Not-a-number) , so u can check for a number this way
if(!isNaN(miscCharge))
{
//do some thing if it's a number
}else{
//do some thing if it's NOT a number
}
hope it works
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
The delete
operator allows you to remove a property from an object.
The following examples all do the same thing.
// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
If you're interested, read Understanding Delete for an in-depth explanation.
At least three ways:
var result = /[^/]*$/.exec("foo/bar/test.html")[0];
...which says "grab the series of characters not containing a slash" ([^/]*
) at the end of the string ($
). Then it grabs the matched characters from the returned match object by indexing into it ([0]
); in a match object, the first entry is the whole matched string. No need for capture groups.
lastIndexOf
and substring
:var str = "foo/bar/test.html";
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);
lastIndexOf
does what it sounds like it does: It finds the index of the last occurrence of a character (well, string) in a string, returning -1 if not found. Nine times out of ten you probably want to check that return value (if (n !== -1)
), but in the above since we're adding 1 to it and calling substring, we'd end up doing str.substring(0)
which just returns the string.
Array#split
Sudhir and Tom Walters have this covered here and here, but just for completeness:
var parts = "foo/bar/test.html".split("/");
var result = parts[parts.length - 1]; // Or parts.pop();
split
splits up a string using the given delimiter, returning an array.
The lastIndexOf
/ substring
solution is probably the most efficient (although one always has to be careful saying anything about JavaScript and performance, since the engines vary so radically from each other), but unless you're doing this thousands of times in a loop, it doesn't matter and I'd strive for clarity of code.
You can look at the following in linux
cd /root
ls -al
vi .mysql_history
It may help
For large datasets a faster solution is required.
Making use of 'Text to Columns' functionality provides a fast solution.
Example based on column F, starting range at 25 to LastRow
Sub ConvTxt2Nr()
Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Sheets("DumpDB")
LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)
SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
Try something like:
import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()
In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:
public class CustomRunner extends BlockJUnit4ClassRunner {
public CTRunner(Class<?> klass) throws initializationError {
super(klass);
}
@Override
protected boolean isIgnored(FrameworkMethod child) {
if(shouldIgnore()) {
return true;
}
return super.isIgnored(child);
}
private boolean shouldIgnore(class) {
/* some custom criteria */
}
}
slide_in_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="100%p" />
</set>
slide_in_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="100%p"
android:toYDelta="0%p" />
</set>
slide_out_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="-100%"
android:toYDelta="0"
/>
</set>
slide_out_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="-100%p"
/>
</set>
direction = down
activity.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_out_down, R.anim.slide_in_down)
.replace(R.id.container, new CardFrontFragment())
.commit();
direction = up
activity.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_up)
.replace(R.id.container, new CardFrontFragment())
.commit();
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
echo "discreet";history -d $(history 1)
x86 is a 32 bit instruction set, x86_64 is a 64 bit instruction set... the difference is simple architecture. in case of windows os you better use the x86/32bit version for compatibility issues. in case of Linux you will not be able to use a 64 bit s/w if the os does not have the long mode flag.
Whatever I recommend if you have a windows 7 32 bit OS then go for 32bit or x86 binaries and as for Ubuntu 12.04 use command uname -a
or grep lm /proc/cpuinfo
(grep lm /proc/cpuinfo
does not return value for 32 bit as 32 bit os does not has the cpuinfo flag) to know the architecture OS your OS then use the binaries according to your OS.
** Note. Remember you can always install 64 bit os in 32 bit system as long as it supports enhanced 64 bit.. 64 bit os works better some times for multi purpose work and also supports more ram than 32bits. also you can install 32bit s/w in 64 bit os..
** OS = Operating system.
This error happened because the image didn't load properly . So you have problem with the previous line cv2.imread
my suggestion is :
check if the images exist in the path you give
check the count variable if he have valid number
If you ever run in a situation where you need to get the next char of the word using __next__()
, remember to create a string_iterator
and iterate over it and not the original string (it does not have the __next__() method)
In this example, when I find a char = [
I keep looking into the next word while I don't find ]
, so I need to use __next__
here a for loop over the string wouldn't help
myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
if char == "'":
continue
processedInput+=char
if char == '[':
next_char=word_iterator.__next__()
while(next_char != "]"):
processedInput+=next_char
next_char=word_iterator.__next__()
else:
processedInput+=next_char
strgroupids = strgroupids.Remove(strgroupids.Length - 1);
String.Remove(Int32):
Deletes all the characters from this string beginning at a specified position and continuing through the last position
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};
kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));
Using this code:
foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
the expected output should be:
Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3
The same will work with a KeyValuePair or whatever other type you want to use..
Edit -
To lookup by the key, you can do the following:
var result = stringList.Where(s => s == "Lookup");
You could do this with a KeyValuePair by doing the following:
var result = kvpList.Where (kvp => kvp.Value == "Lookup");
Last edit -
Made the answer specific to KeyValuePair rather than string.
[A-Za-z0-9_.-]*
This will also match for empty strings, if you do not want that exchange the last *
for an +
The simpliest way is to install the needed package:
sudo apt-get install tesseract-ocr-eng #for english
sudo apt-get install tesseract-ocr-tam #for tamil
sudo apt-get install tesseract-ocr-deu #for deutsch (German)
As you can notice, it opens the road to others languages (i.e. tesseract-ocr-fra).
I use typeof
to determine if the variable I'm looking at is an object. If it is then I use instanceof
to determine what kind it is
var type = typeof elem;
if (type == "number") {
// do stuff
}
else if (type == "string") {
// do stuff
}
else if (type == "object") { // either array or object
if (elem instanceof Buffer) {
// other stuff
I agree to Ashot and Cwan, but maybe you like to convert an ascii-cipher like '7' into an int like 7?
Then I recoomend:
char seven = '7';
int i = seven - '0';
or, maybe you get a warning,
int i = (int) (seven - '0');
corrected after comments, thanks.
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
I think this answer will give all the solutions for:
function NumberOf() { _x000D_
var string = "Write a piece of code in any language of your choice that computes the total number of characters, words and lines in a given text. \n This is second line. \n This is third line.";_x000D_
_x000D_
var length = string.length; //No of characters_x000D_
var words = string.match(/\w+/g).length; //No of words_x000D_
var lines = string.split(/\r\n|\r|\n/).length; // No of lines_x000D_
_x000D_
console.log('Number of characters:',length);_x000D_
console.log('Number of words:',words);_x000D_
console.log('Number of lines:',lines);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
NumberOf();
_x000D_
string.length
string.match(/\w+/g).length
string.length(/\r\n|\r|\n/).length
I hope this can help those who are searching for these 3 answers.
have you tried:
.image_block{
text-align: center;
vertical-align: bottom;
}
Another approach is to use timestamp values:
end_time.timestamp() - start_time.timestamp()
Also remember that an uninstall can be initiated using the WMIC command:
wmic product get name
--> This will list the names of all installed apps
wmic product where name='myappsname' call uninstall
--> this will uninstall the app.
Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm
such an utility class :
class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
public String extension() {
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
public String filename() { // gets filename without extension
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
usage:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH, '/', '.');
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
first, give the div an id. Then, call function appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>
Here's another option. It works by putting an ActiveX ComboBox on top of the cell with validation enabled, and then providing autocomplete in the ComboBox instead.
Option Explicit
' Autocomplete - replacing validation lists with ActiveX ComboBox
'
' Usage:
' 1. Copy this code into a module named m_autocomplete
' 2. Go to Tools / References and make sure "Microsoft Forms 2.0 Object Library" is checked
' 3. Copy and paste the following code to the worksheet where you want autocomplete
' ------------------------------------------------------------------------------------------------------
' - autocomplete
' Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' m_autocomplete.SelectionChangeHandler Target
' End Sub
' Private Sub AutoComplete_Combo_KeyDown(ByVal KeyCode As msforms.ReturnInteger, ByVal Shift As Integer)
' m_autocomplete.KeyDownHandler KeyCode, Shift
' End Sub
' Private Sub AutoComplete_Combo_Click()
' m_autocomplete.AutoComplete_Combo_Click
' End Sub
' ------------------------------------------------------------------------------------------------------
' When the combobox is clicked, it should dropdown (expand)
Public Sub AutoComplete_Combo_Click()
Dim ws As Worksheet: Set ws = ActiveSheet
Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
Dim cb As ComboBox: Set cb = cbo.Object
If cbo.Visible Then cb.DropDown
End Sub
' Make it easier to navigate between cells
Public Sub KeyDownHandler(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Const UP As Integer = -1
Const DOWN As Integer = 1
Const K_TAB_______ As Integer = 9
Const K_ENTER_____ As Integer = 13
Const K_ARROW_UP__ As Integer = 38
Const K_ARROW_DOWN As Integer = 40
Dim direction As Integer: direction = 0
If Shift = 0 And KeyCode = K_TAB_______ Then direction = DOWN
If Shift = 0 And KeyCode = K_ENTER_____ Then direction = DOWN
If Shift = 1 And KeyCode = K_TAB_______ Then direction = UP
If Shift = 1 And KeyCode = K_ENTER_____ Then direction = UP
If Shift = 1 And KeyCode = K_ARROW_UP__ Then direction = UP
If Shift = 1 And KeyCode = K_ARROW_DOWN Then direction = DOWN
If direction <> 0 Then ActiveCell.Offset(direction, 0).Activate
AutoComplete_Combo_Click
End Sub
Public Sub SelectionChangeHandler(ByVal Target As Range)
On Error GoTo errHandler
Dim ws As Worksheet: Set ws = ActiveSheet
Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
Dim cb As ComboBox: Set cb = cbo.Object
' Try to hide the ComboBox. This might be buggy...
If cbo.Visible Then
cbo.Left = 10
cbo.Top = 10
cbo.ListFillRange = ""
cbo.LinkedCell = ""
cbo.Visible = False
Application.ScreenUpdating = True
ActiveSheet.Calculate
ActiveWindow.SmallScroll
Application.WindowState = Application.WindowState
DoEvents
End If
If Not HasValidationList(Target) Then GoTo ex
Application.EnableEvents = False
' TODO: the code below is a little fragile
Dim lfr As String
lfr = Mid(Target.Validation.Formula1, 2)
lfr = Replace(lfr, "INDIREKTE", "") ' norwegian
lfr = Replace(lfr, "INDIRECT", "") ' english
lfr = Replace(lfr, """", "")
lfr = Application.Range(lfr).Address(External:=True)
cbo.ListFillRange = lfr
cbo.Visible = True
cbo.Left = Target.Left
cbo.Top = Target.Top
cbo.Height = Target.Height + 5
cbo.Width = Target.Width + 15
cbo.LinkedCell = Target.Address(External:=True)
cbo.Activate
cb.SelStart = 0
cb.SelLength = cb.TextLength
cb.DropDown
GoTo ex
errHandler:
Debug.Print "Error"
Debug.Print Err.Number
Debug.Print Err.Description
ex:
Application.EnableEvents = True
End Sub
' Does the cell have a validation list?
Function HasValidationList(Cell As Range) As Boolean
HasValidationList = False
On Error GoTo ex
If Cell.Validation.Type = xlValidateList Then HasValidationList = True
ex:
End Function
' Retrieve or create the ComboBox
Function GetComboBoxObject(ws As Worksheet) As OLEObject
Dim cbo As OLEObject
On Error Resume Next
Set cbo = ws.OLEObjects("AutoComplete_Combo")
On Error GoTo 0
If cbo Is Nothing Then
'Dim EnableSelection As Integer: EnableSelection = ws.EnableSelection
Dim ProtectContents As Boolean: ProtectContents = ws.ProtectContents
Debug.Print "Lager AutoComplete_Combo"
If ProtectContents Then ws.Unprotect
Set cbo = ws.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
Left:=50, Top:=18.75, Width:=129, Height:=18.75)
cbo.name = "AutoComplete_Combo"
cbo.Object.MatchRequired = True
cbo.Object.ListRows = 12
If ProtectContents Then ws.Protect
End If
Set GetComboBoxObject = cbo
End Function
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
When calling the function, follow it by return false
example:
<input type="submit" value="Add" onclick="addNewPayment();return false;">
I tried most things here, none worked on my Ubuntu VM.
Here is a quick hack (credits goes here):
#include <iostream>
int main() {
system("(speaker-test -t sine -f 1000)& pid=$!; sleep 1.0s; kill -9 $pid");
}
It will basically use system's speaker-test
to produce the sound. This will not terminate quickly though, so the command runs it in background (the &
part), then captures its process id (the pid=$1
part), sleeps for a certain amount that you can change (the sleep 1.0s
part) and then it kills that process (the kill -9 $pid
part).
sine
is the sound produced. You can change it to pink
or to a wav
file.
I was testing my application with special characters & was observing the same error. After some research, turns out the % symbol was the cause. I had to modify it to the encoded representation %25. Its all fine now, thanks to the below post
I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"
Example:
<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">×</button>
<strong>Error ! </strong>{{vm.exception}}
</div>
works for me and stops the need to go out to jquery
I encountered the same problem and I was able to resolve it with two solutions: First, I used the MMC snap-in "Certificates" for the "Computer account" and dragged the self-signed certificate into the "Trusted Root Certification Authorities" folder. This means the local computer (the one that generated the certificate) will now trust that certificate. Secondly I noticed that the certificate was generated for some internal computer name, but the web service was being accessed using another name. This caused a mismatch when validating the certificate. We generated the certificate for computer.operations.local, but accessed the web service using https://computer.internaldomain.companydomain.com. When we switched the URL to the one used to generate the certificate we got no more errors.
Maybe just switching URLs would have worked, but by making the certificate trusted you also avoid the red screen in Internet Explorer where it tells you it doesn't trust the certificate.
I've found the answer:
You MUST encode your json like this: {"c":21001,"m":"p"}
but not {c:21001,m:"p"}
or {'c':21001,'m':'p'}
Thus, the key of a dict must be wrapped in double quotes:"
, then chrome will preview it as json rather than plain text.
Sometimes VS2010 switches my configuration from Any CPU to Mixed Platforms. When this happens I get this error message.
To resolve it I switch back to Any CPU:
1. Right click on the solution and select properties.
2. Click on Configuration Properties and then the Configuration Manager... button.
3. Under Active solution platform select Any CPU
I found some way to perform in on dictionary contain my custom class methods
foreach (var item in this.Values.Where(p => p.IsActive == false))
item.Refresh();
Where 'this' derived from : Dictionary<string, MyCustomClass>
class MyCustomClass
{
public void Refresh(){}
}
One of the JPA ways for getting only particular columns is to ask for a Tuple object.
In your case you would need to write something like this:
CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION)); //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
Long id = (Long) t.get(0);
Long version = (Long) t.get(1);
}
Another approach is possible if you have a class representing the result, like T
in your case. T
doesn't need to be an Entity class. If T
has a constructor like:
public T(Long id, Long version)
then you can use T
directly in your CriteriaQuery
constructor:
CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION)); //using metamodel
List<T> result = em.createQuery(cq).getResultList();
See this link for further reference.
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.
The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:
public enum Example {
UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");
private static HashMap<Integer, Example> enumById = new HashMap<>();
static {
Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
}
public static Example getById(int id) {
return enumById.getOrDefault(id, UNKNOWN);
}
private int id;
private String description;
private Example(int id, String description) {
this.id = id;
this.description= description;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
}
}
If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN
like I did above you can of course also do:
public static Example getById(int id) {
return enumById.get(id);
}
For anyone encountering a similar situation I was able to solve the issue above as follows:
Regenerate your pkcs12 file as follows:
openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts
, password: changeit
).
Set the following system properties:
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
Test ur url.
Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333
All proposed solutions didn't work for me but the closest one was from @Rishii.
I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.
.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
return {
restrict: 'EAC',
require: 'ngModel',
priority: 1,
link: function(scope, element, attrs, ngModel) {
var dateFormat = 'yyyy-MM-dd';
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, dateFormat);
});
ngModel.$validators.date = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if (!attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
else if (angular.isDate(value) && !isNaN(value)) {
return true;
}
else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat);
return !isNaN(date);
}
else {
return false;
}
};
}
};
}])
Swift 4.0 iOS 11.2.6 list parsed and code to parse it, based on https://stackoverflow.com/users/3647770/ashok-r answer above.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>identity</key>
<string>blah-1</string>
<key>major</key>
<string>1</string>
<key>minor</key>
<string>1</string>
<key>uuid</key>
<string>f45321</string>
<key>web</key>
<string>http://web</string>
</dict>
<dict>
<key>identity</key>
<string></string>
<key>major</key>
<string></string>
<key>minor</key>
<string></string>
<key>uuid</key>
<string></string>
<key>web</key>
<string></string>
</dict>
</array>
</plist>
do {
let plistXML = try Data(contentsOf: url)
var plistData: [[String: AnyObject]] = [[:]]
var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml
do {
plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [[String:AnyObject]]
} catch {
print("Error reading plist: \(error), format: \(propertyListFormat)")
}
} catch {
print("error no upload")
}
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
in the V2.0 it's not possible. The iframe blocks all styling out of this. It's difficult to add a custom theme instead of the dark or light one.
Origin null
is the local file system, so that suggests that you're loading the HTML page that does the load
call via a file:///
URL (e.g., just double-clicking it in a local file browser or similar). Different browsers take different approaches to applying the Same Origin Policy to local files.
My guess is that you're seeing this using Chrome. Chrome's rules for applying the SOP to local files are very tight, it disallows even loading files from the same directory as the document. So does Opera. Some other browsers, such as Firefox, allow limited access to local files. But basically, using ajax with local resources isn't going to work cross-browser.
If you're just testing something locally that you'll really be deploying to the web, rather than use local files, install a simple web server and test via http://
URLs instead. That gives you a much more accurate security picture.
https://docs.mongodb.com/manual/reference/configuration-options/#security.authorization
Edit the mongo settings file;
sudo nano /etc/mongod.conf
Add the line:
security.authorization : enabled
Restart the service
sudo service mongod restart
Regards
This is the strict aliasing rule, found in section 3.10 of the C++03 standard (other answers provide good explanation, but none provided the rule itself):
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:
- the dynamic type of the object,
- a cv-qualified version of the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union),
- a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
- a
char
orunsigned char
type.
C++11 and C++14 wording (changes emphasized):
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
- the dynamic type of the object,
- a cv-qualified version of the dynamic type of the object,
- a type similar (as defined in 4.4) to the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to the dynamic type of the object,
- a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
- an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
- a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
- a
char
orunsigned char
type.
Two changes were small: glvalue instead of lvalue, and clarification of the aggregate/union case.
The third change makes a stronger guarantee (relaxes the strong aliasing rule): The new concept of similar types that are now safe to alias.
Also the C wording (C99; ISO/IEC 9899:1999 6.5/7; the exact same wording is used in ISO/IEC 9899:2011 §6.5 ¶7):
An object shall have its stored value accessed only by an lvalue expression that has one of the following types 73) or 88):
- a type compatible with the effective type of the object,
- a quali?ed version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the object,
- a type that is the signed or unsigned type corresponding to a quali?ed version of the effective type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
- a character type.
73) or 88) The intent of this list is to specify those circumstances in which an object may or may not be aliased.
However iOS Simulator->HardWare->Device
menu.
This is commonly referred to as screen scraping, by the way. The library I have used for this is Simple HTML Dom Parser.
A const
object is always static
.
Here is the swift 3 updated answer
var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0) Backslash (\\) Horizontal Tab (\t) Line Feed (\n) Carriage Return (\r) Double Quote (\") Single Quote (\') Unicode scalar (\u{n})
Squash commits locally with
git rebase -i origin/master~4 master
and then force push with
git push origin +master
--force
and +
From the documentation of git push
:
Note that
--force
applies to all the refs that are pushed, hence using it withpush.default
set tomatching
or with multiple push destinations configured withremote.*.push
may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a+
in front of the refspec to push (e.ggit push origin +master
to force a push to themaster
branch).
Use a good XSD Schema to create a set of classes with xsd.exe and use an XmlSerializer
to create a object tree out of your XML and vice versa. If you have few restrictions on your model, you could even try to create a direct mapping between you model classes and the XML with the Xml*Attributes.
There is an introductory article about XML Serialisation on MSDN.
Performance tip: Constructing an XmlSerializer
is expensive. Keep a reference to your XmlSerializer
instance if you intend to parse/write multiple XML files.
I thought it would be useful to compare the timings of the different solutions presented here. For this I used my own library simple_benchmark
:
So indeed for this case the solution from Denis Otkidach is fastest.
Some of the approaches also exhibit a much steeper curve, these are the approaches that scale quadratic with the number of elements (Alex Martellis first solution, wjandrea and both of Xavier Decorets solutions). Also important to mention is that the pandas solution from Keiku has a very big constant factor. But for larger lists it almost catches up with the other solutions.
And in case the duplicate is at the first position. This is useful to see which solutions are short-circuiting:
Here several approaches don't short-circuit: Kaiku, Frank, Xavier_Decoret (first solution), Turn, Alex Martelli (first solution) and the approach presented by Denis Otkidach (which was fastest in the no-duplicate case).
I included a function from my own library here: iteration_utilities.all_distinct
which can compete with the fastest solution in the no-duplicates case and performs in constant-time for the duplicate-at-begin case (although not as fastest).
The code for the benchmark:
from collections import Counter
from functools import reduce
import pandas as pd
from simple_benchmark import BenchmarkBuilder
from iteration_utilities import all_distinct
b = BenchmarkBuilder()
@b.add_function()
def Keiku(l):
return pd.Series(l).duplicated().sum() > 0
@b.add_function()
def Frank(num_list):
unique = []
dupes = []
for i in num_list:
if i not in unique:
unique.append(i)
else:
dupes.append(i)
if len(dupes) != 0:
return False
else:
return True
@b.add_function()
def wjandrea(iterable):
seen = []
for x in iterable:
if x in seen:
return True
seen.append(x)
return False
@b.add_function()
def user(iterable):
clean_elements_set = set()
clean_elements_set_add = clean_elements_set.add
for possible_duplicate_element in iterable:
if possible_duplicate_element in clean_elements_set:
return True
else:
clean_elements_set_add( possible_duplicate_element )
return False
@b.add_function()
def Turn(l):
return Counter(l).most_common()[0][1] > 1
def getDupes(l):
seen = set()
seen_add = seen.add
for x in l:
if x in seen or seen_add(x):
yield x
@b.add_function()
def F1Rumors(l):
try:
if next(getDupes(l)): return True # Found a dupe
except StopIteration:
pass
return False
def decompose(a_list):
return reduce(
lambda u, o : (u[0].union([o]), u[1].union(u[0].intersection([o]))),
a_list,
(set(), set()))
@b.add_function()
def Xavier_Decoret_1(l):
return not decompose(l)[1]
@b.add_function()
def Xavier_Decoret_2(l):
try:
def func(s, o):
if o in s:
raise Exception
return s.union([o])
reduce(func, l, set())
return True
except:
return False
@b.add_function()
def pyrospade(xs):
s = set()
return any(x in s or s.add(x) for x in xs)
@b.add_function()
def Alex_Martelli_1(thelist):
return any(thelist.count(x) > 1 for x in thelist)
@b.add_function()
def Alex_Martelli_2(thelist):
seen = set()
for x in thelist:
if x in seen: return True
seen.add(x)
return False
@b.add_function()
def Denis_Otkidach(your_list):
return len(your_list) != len(set(your_list))
@b.add_function()
def MSeifert04(l):
return not all_distinct(l)
And for the arguments:
# No duplicate run
@b.add_arguments('list size')
def arguments():
for exp in range(2, 14):
size = 2**exp
yield size, list(range(size))
# Duplicate at beginning run
@b.add_arguments('list size')
def arguments():
for exp in range(2, 14):
size = 2**exp
yield size, [0, *list(range(size)]
# Running and plotting
r = b.run()
r.plot()
Search the file my.cnf and comment the line
skip-networking
to
#skip-networking
Restart mysql
There is a hackish solution using OpenFileDialog
where ValidateNames
and CheckFileExists
are both set to false and FileName
is given a mock value to indicate that a directory is selected.
I say hack because it is confusing to users about how to select a folder. They need to be in the desired folder and then just press Open while file name says "Folder Selection."
This is based on Select file or folder from the same dialog by Denis Stankovski.
OpenFileDialog folderBrowser = new OpenFileDialog();
// Set validate names and check file exists to false otherwise windows will
// not let you select "Folder Selection."
folderBrowser.ValidateNames = false;
folderBrowser.CheckFileExists = false;
folderBrowser.CheckPathExists = true;
// Always default to Folder Selection.
folderBrowser.FileName = "Folder Selection.";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
string folderPath = Path.GetDirectoryName(folderBrowser.FileName);
// ...
}
In command line it's better to use REG tool rather than REGEDIT:
REG IMPORT yourfile.reg
REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:
> REG IMPORT missing_file.reg
ERROR: Error opening the file. There may be a disk or file system error.
> %windir%\System32\reg.exe /?
REG Operation [Parameter List]
Operation [ QUERY | ADD | DELETE | COPY |
SAVE | LOAD | UNLOAD | RESTORE |
COMPARE | EXPORT | IMPORT | FLAGS ]
Return Code: (Except for REG COMPARE)
0 - Successful
1 - Failed
For help on a specific operation type:
REG Operation /?
Examples:
REG QUERY /?
REG ADD /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG COMPARE /?
REG EXPORT /?
REG IMPORT /?
REG FLAGS /?
nm -g list the extern variable, which is not necessary exported symbol. Any non-static file scope variable(in C) are all extern variable.
nm -D will list the symbol in the dynamic table, which you can find it's address by dlsym.
nm --version
GNU nm 2.17.50.0.6-12.el5 20061020
You can select a child like
TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);
Kindly try below on postman :-
In header section example work for me..
Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU
To run the batch file when the VM
user logs in:
Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.
Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\
.
As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:
start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"
But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.
I fixed this problem by running this in terminal. Full writeup is available over here
rvm install 2.2.0 --disable-binary
I'll rename the function take_closest
to conform with PEP8 naming conventions.
If you mean quick-to-execute as opposed to quick-to-write, min
should not be your weapon of choice, except in one very narrow use case. The min
solution needs to examine every number in the list and do a calculation for each number. Using bisect.bisect_left
instead is almost always faster.
The "almost" comes from the fact that bisect_left
requires the list to be sorted to work. Hopefully, your use case is such that you can sort the list once and then leave it alone. Even if not, as long as you don't need to sort before every time you call take_closest
, the bisect
module will likely come out on top. If you're in doubt, try both and look at the real-world difference.
from bisect import bisect_left
def take_closest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
Bisect works by repeatedly halving a list and finding out which half myNumber
has to be in by looking at the middle value. This means it has a running time of O(log n) as opposed to the O(n) running time of the highest voted answer. If we compare the two methods and supply both with a sorted myList
, these are the results:
$ python -m timeit -s " from closest import take_closest from random import randint a = range(-1000, 1000, 10)" "take_closest(a, randint(-1100, 1100))" 100000 loops, best of 3: 2.22 usec per loop $ python -m timeit -s " from closest import with_min from random import randint a = range(-1000, 1000, 10)" "with_min(a, randint(-1100, 1100))" 10000 loops, best of 3: 43.9 usec per loop
So in this particular test, bisect
is almost 20 times faster. For longer lists, the difference will be greater.
What if we level the playing field by removing the precondition that myList
must be sorted? Let's say we sort a copy of the list every time take_closest
is called, while leaving the min
solution unaltered. Using the 200-item list in the above test, the bisect
solution is still the fastest, though only by about 30%.
This is a strange result, considering that the sorting step is O(n log(n))! The only reason min
is still losing is that the sorting is done in highly optimalized c code, while min
has to plod along calling a lambda function for every item. As myList
grows in size, the min
solution will eventually be faster. Note that we had to stack everything in its favour for the min
solution to win.
if you want to access a method :
1) while using an object of a class:
Myclass myclass;
myclass.DoSomething();
2) while using a pointer to an object of a class:
Myclass *myclass=&abc;
myclass->DoSomething();
You can do as follow :
import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))
https://developer.rhino3d.com/guides/rhinopython/python-xml-json/
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
I have put this in my partial view:
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.
So use this alert instead:
alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
NodeJS now includes threads (as an experimental feature at time of answering).
I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.
I have come up with a solution based on your comment for the output you are looking for:
Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces
var str = "<p> </p><div> </div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p> </p><div> </div>";_x000D_
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
raw_input
can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
IMPORTANT - on ubuntu package docker
is something entirely different ( avoid it ) :
issue following to view what if any packages you have mentioning docker
dpkg -l|grep docker
if only match is following then you do NOT have docker installed below is an unrelated package
docker - System tray for KDE3/GNOME2 docklet applications
if you see something similar to following then you have docker installed
dpkg -l|grep docker
ii docker-ce 5:19.03.13~3-0~ubuntu-focal amd64 Docker: the open-source application container engine
ii docker-ce-cli 5:19.03.13~3-0~ubuntu-focal amd64 Docker CLI: the open-source application container engine
NOTE - ubuntu package docker.io
is not getting updates ( obsolete do NOT use )
Instead do this : install the latest version of docker on linux by executing the following:
sudo curl -sSL https://get.docker.com/ | sh
# sudo curl -sSL https://test.docker.com | sh # get dev pipeline version
here is a typical output ( ubuntu 16.04 )
apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/gpg.1.sh --keyserver
hkp://ha.pool.sks-keyservers.net:80
--recv-keys
58118E89F3A912897C070ADBF76221572C52609D
gpg: requesting key 2C52609D from hkp server ha.pool.sks-keyservers.net
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg: new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://download.virtualbox.org/virtualbox/debian xenial InRelease
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:4 http://dl.google.com/linux/chrome/deb stable Release
Hit:5 http://archive.canonical.com/ubuntu xenial InRelease
Hit:6 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial InRelease
Hit:7 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-updates InRelease
Hit:8 http://ppa.launchpad.net/me-davidsansome/clementine/ubuntu xenial InRelease
Ign:9 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease
Hit:10 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-backports InRelease
Hit:11 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release
Hit:12 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-security InRelease
Hit:14 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease
Ign:15 http://linux.dropbox.com/ubuntu wily InRelease
Ign:16 http://repo.vivaldi.com/stable/deb stable InRelease
Hit:17 http://repo.vivaldi.com/stable/deb stable Release
Get:18 http://linux.dropbox.com/ubuntu wily Release [6,596 B]
Get:19 https://apt.dockerproject.org/repo ubuntu-xenial InRelease [20.6 kB]
Ign:20 http://packages.amplify.nginx.com/ubuntu xenial InRelease
Hit:22 http://packages.amplify.nginx.com/ubuntu xenial Release
Hit:23 https://deb.opera.com/opera-beta stable InRelease
Hit:26 https://deb.opera.com/opera-developer stable InRelease
Get:28 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: http://repo.mongodb.org/apt/debian/dists/wheezy/mongodb-org/3.2/Release.gpg: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
aufs-tools cgroupfs-mount
The following NEW packages will be installed:
aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
Client:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:
sudo usermod -aG docker stens
Remember that you will have to log out and back in for this to take effect!
Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :
https://docs.docker.com/engine/installation/linux/ubuntulinux/
Once installed you can see what docker packages were installed by issuing
dpkg -l|grep docker
ii docker-ce 5:19.03.13~3-0~ubuntu-focal amd64 Docker: the open-source application container engine
ii docker-ce-cli 5:19.03.13~3-0~ubuntu-focal amd64 Docker CLI: the open-source application container engine
now Docker updates will get installed going forward when you issue
sudo apt-get update
sudo apt-get upgrade
take a look at
ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/docker.list.save
-rw-r--r-- 1 root root 71 Jul 4 11:32 /etc/apt/sources.list.d/docker.list
cat /etc/apt/sources.list.d/docker.list
deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main
or more generally
cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] https://download.docker.com/linux/ubuntu focal test
I've had to try to 'fix' a number of UTF8 broken situations in the past, and unfortunately it's never easy, and often rather impossible.
Unless you can determine exactly how it was broken, and it was always broken in that exact same way, then it's going to be hard to 'undo' the damage.
If you want to try to undo the damage, your best bet would be to start writing some sample code, where you attempt numerous variations on calls to mb_convert_encoding() to see if you can find a combination of 'from' and 'to' that fixes your data. In the end, it's often best to not even bother worrying about fixing the old data because of the pain levels involved, but instead to just fix things going forward.
However, before doing this, you need to make sure that you fix everything that is causing this issue in the first place. You've already mentioned that your DB table collation and editors are set properly. But there are more places where you need to check to make sure that everything is properly UTF-8:
If you miss up on any one step through your whole process, the encoding can be mangled and problems arise. Once you get in the 'groove' of doing utf-8 though, this all becomes second nature. And of course, PHP6 is supposed to be fully unicode complaint from the getgo, which will make lots of this easier (hopefully)
the only solution for me was:
click on window->close all perspective (you can try also close perspective)
after this, in the top right corner click on: open perspective->resource
done
for _ in {1..10}; do command; done
Note the underscore instead of using a variable.
Found the issue by rolling back to Angular 1.5.9 and rerunning the test. It was a simple injection issue but Angular 1.6.0 superseded this by throwing the "Possibly Unhandled Rejection" error instead, obfuscating the actual error.
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
You can make the border transparent. In this way it exists, but is invisible, so it doesn't push anything around:
.jobs .item {
background: #eee;
border: 1px solid transparent;
}
.jobs .item:hover {
background: #e1e1e1;
border: 1px solid #d0d0d0;
}
_x000D_
<div class="jobs">
<div class="item">Item</div>
</div>
_x000D_
For elements that already have a border, and you don't want them to move, you can use negative margins:
.jobs .item {
background: #eee;
border: 1px solid #d0d0d0;
}
.jobs .item:hover {
background: #e1e1e1;
border: 3px solid #d0d0d0;
margin: -2px;
}
_x000D_
<div class="jobs">
<div class="item">Item</div>
</div>
_x000D_
Another possible trick for adding width to an existing border is to add a box-shadow
with the spread attribute of the desired pixel width.
.jobs .item {
background: #eee;
border: 1px solid #d0d0d0;
}
.jobs .item:hover {
background: #e1e1e1;
box-shadow: 0 0 0 2px #d0d0d0;
}
_x000D_
<div class="jobs">
<div class="item">Item</div>
</div>
_x000D_
initialize the Session class in the constructor of controller using
$this->load->library('session');
for example :
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->model('user_activity','',TRUE);
$this->load->library('session');
}
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
You can try jclasslib:
https://github.com/ingokegel/jclasslib
It's nice that it can associate itself with *.class extension.
In Python there's no POSIX regex classes
There are when using the regex
library: https://pypi.org/project/regex/
It is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is very similar to Python's re
.
From the documentation:
[[:alpha:]]; [[:^alpha:]]
POSIX character classes are supported. These are normally treated as an alternative form of
\p{...}
.
(I'm not affiliated, just a user.)
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
Check if folder .ssh is on your system
If not, then
Paste in the terminal
Remove existing SSH keys
rm ~/.ssh/github_rsa.pub
Create New
Create new SSH key ? ssh-keygen -t rsa -b 4096 -C "[email protected]"
The public key has been saved in "/Users/administrator/.ssh/id_ed25519.pub."
Open the public key saved path.
Copy the SSH key ? GitLab Account ? Setting ? SSH Key ? Add key
Test again from the terminal ? ssh -T [email protected]
PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.
>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'
For me, i had to uninstall R from brew brew uninstall --force R
and then head over to the R website and download and install it from there.
As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.
https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5
From the commit:
This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like
edit/color/:color/largecode/*largecode
will match with something like thishttp://appdomain.com/edit/color/brown/largecode/code/with/slashs
.
I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
Let's illustrate what's happening here:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults
.
As other posters have pointed out, you probably want to use None
as a sentinel value and give each instance it's own list.
I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
UIFont *systemFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
This will give you the system font with the default system font size applied for the label texts by default.
Do a git rebase -i FAR_ENOUGH_BACK
and drop the line for the commit you don't want.
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
The query below returns a list of information about each field, including the MySQL field type. Here is an example:
SHOW FIELDS FROM tablename
/* returns "Field", "Type", "Null", "Key", "Default", "Extras" */
See this manual page.
This happens when Eclipse shuts down incorrectly - delete the server and then re-create it again.
How about creating two dataframes, each with different data types for their columns, and then appending them together?
d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))
Results
In[8}: d1.dtypes
Out[8]:
float_column float64
string_column object
dtype: object
After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.
It says:
When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:
$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with
It does not mean:
type again
git rebase -i HEAD~3
Try to not typing git rebase -i HEAD~3
when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort
might be needed to reset everything and allow you to try again)
As Dave Vogt mentions in the comments, git rebase --continue
is for going to the next task in the rebasing process, after you've amended the first commit.
Also, Gregg Lind mentions in his answer the reword
command of git rebase
:
By replacing the command "pick" with the command "edit", you can tell
git rebase
to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.If you just want to edit the commit message for a commit, replace the command "
pick
" with the command "reword
", since Git1.6.6 (January 2010).It does the same thing ‘
edit
’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:
$ git rebase -i next
Then set all the commits to ‘edit’. Then on each one:
# Change the message in your editor.
$ git commit --amend
$ git rebase --continue
Using ‘
reword
’ instead of ‘edit
’ lets you skip thegit-commit
andgit-rebase
calls.
CTL + M + L expands all
CTL + M + O collapses all
In the MSDN article "Default Keyboard Shortcuts in Visual Studio," see the section "Text Editor" if you're looking for other shortcuts - these 2 are just a few of the many that are available.
This is because findViewById()
searches in the activity_main
layout, while the button is located in the fragment's layout fragment_main
.
Move that piece of code in the onCreateView()
method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView
view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
Can be seen from UI as well. Go to overview tab on table, you will see item count. Hope it helps someone.
How about this approach, which splits the problem into two parts:
textarea
, which turns red when it hits zero but still allows the user to type.textarea
is greater than 160.My textarea
has an id of Message
, and the span
in which I display the number of remaining characters has an id of counter
. The css class of error
gets applied when the number of remaining characters hits zero.
var charactersAllowed = 160;
$(document).ready(function () {
$('#Message').keyup(function () {
var left = charactersAllowed - $(this).val().length;
if (left < 0) {
$('#counter').addClass('error');
left = 0;
}
else {
$('#counter').removeClass('error');
}
$('#counter').text('Characters left: ' + left);
});
});
Status code 0 means the requested url is not reachable. By changing http://something/something to https://something/something worked for me. IE throwns an error saying "permission denied" when the status code is 0, other browsers dont.
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
if it still throw the same problem, from root folder run
php artisan cache:clear
php artisan config:cache
php artisan serve
if you still have the problem, check whether you are using multiple copies of sql server, for example through Ubuntu app, if so stop the MySQL server in ubuntu
sudo service MySQL stop
Here is an interesting case: method receieves generic collection and returns generic collection of same base type. For example:
Collection<? extends Assertion> map(Collection<? extends Assertion> assertions);
This method can be mocked with combination of Mockito anyCollectionOf matcher and the Answer.
when(mockedObject.map(anyCollectionOf(Assertion.class))).thenAnswer(
new Answer<Collection<Assertion>>() {
@Override
public Collection<Assertion> answer(InvocationOnMock invocation) throws Throwable {
return new ArrayList<Assertion>();
}
});
XML defines the syntax of elements and attributes for structuring data in a well-formed document.
XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
use filter
var json = {
homes: [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
]
}
let filter =
json.homes.filter(d =>
d.price >= 1000 &
d.sqft >= 500 &
d.num_of_beds >=2 &
d.num_of_baths >= 2.5
)
console.log(filter)
_x000D_
I have a huge database with no (separate) index.
Any time I query by the primary key the results are, for all intensive purposes, instant.
You can use the following code snippet :
java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
-version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
In my pc I am getting following output :
uintx InitialHeapSize := 536870912 {product}
uintx MaxHeapSize := 1073741824 {product}
uintx PermSize := 67108864 {pd product}
uintx MaxPermSize := 134217728 {pd product}
intx ThreadStackSize := 512 {pd product}
I think I found a simpler solution, only this uses a subclass of ViewPager instead of (its parent) ScrollView.
UPDATE 2013-07-16: I added an override for onTouchEvent
as well. It could possibly help with the issues mentioned in the comments, although YMMV.
public class UninterceptableViewPager extends ViewPager {
public UninterceptableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean ret = super.onInterceptTouchEvent(ev);
if (ret)
getParent().requestDisallowInterceptTouchEvent(true);
return ret;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean ret = super.onTouchEvent(ev);
if (ret)
getParent().requestDisallowInterceptTouchEvent(true);
return ret;
}
}
This is similar to the technique used in android.widget.Gallery's onScroll(). It is further explained by the Google I/O 2013 presentation Writing Custom Views for Android.
Update 2013-12-10: A similar approach is also described in a post from Kirill Grouchnikov about the (then) Android Market app.
Here is an elegant library that records video in all supported browsers and supports uploading:
Change the wrapping from "onload
" to "No wrap - in <body>
"
The function defined has a different scope.
If you happen to be using sass in a build system, one way to do this that will work in all the major browsers is to wrap all your style imports with a :not() selector like so...
:not(.disable-all-styles) {
@import 'my-sass-file';
@import 'my-other-sass-file';
}
Then you can use the disable class on a container and the sub-content won't have any of your styles.
<div class="disable-all-styles">
<p>Nothing in this div is affected by my sass styles.</p>
</div>
Of course all your styles will now be prepended with the :not() selector, so it's a little fugly, but works well.
If you can get away with using Guava it is by far the simplest way to do it, and you don't have to reinvent the wheel:
final HashCode hashCode = Hashing.sha1().hashString(yourValue, Charset.defaultCharset());
You can then take the hashed value and get it as a byte[]
, as an int
, or as a long
.
No wrapping in a try catch, no shenanigans. And if you decide you want to use something other than SHA-1, Guava also supports sha256, sha 512, and a few I had never even heard about like adler32 and murmur3.
th
for a td
, taking into account colspan
index issues.$('table').on('click', 'td', get_TH_by_TD)_x000D_
_x000D_
function get_TH_by_TD(e){_x000D_
var idx = $(this).index(),_x000D_
th, th_colSpan = 0;_x000D_
_x000D_
for( var i=0; i < this.offsetParent.tHead.rows[0].cells.length; i++ ){_x000D_
th = this.offsetParent.tHead.rows[0].cells[i];_x000D_
th_colSpan += th.colSpan;_x000D_
if( th_colSpan >= (idx + this.colSpan) )_x000D_
break;_x000D_
}_x000D_
_x000D_
console.clear();_x000D_
console.log( th );_x000D_
return th;_x000D_
}
_x000D_
table{ width:100%; }_x000D_
th, td{ border:1px solid silver; padding:5px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Click a TD:</p>_x000D_
<table>_x000D_
<thead> _x000D_
<tr>_x000D_
<th colspan="2"></th>_x000D_
<th>Name</th>_x000D_
<th colspan="2">Address</th>_x000D_
<th colspan="2">Other</th>_x000D_
</tr>_x000D_
</thead> _x000D_
<tbody>_x000D_
<tr>_x000D_
<td>X</td>_x000D_
<td>1</td>_x000D_
<td>Jon Snow</td>_x000D_
<td>12</td>_x000D_
<td>High Street</td>_x000D_
<td>Postfix</td>_x000D_
<td>Public</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Just change the target to "ES2017" in tsconfig.json file.
this is my tsconfig.json file
{
"compilerOptions": {
/* Basic Options */
"target": "ES2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"strict": true /* Enable all strict type-checking options. */
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
I had the same problem and the only thing that works for my was to uninstall entity framework package from each project using Uninstall-Package. And then intall it again in the whole solution. It will ask you to choose in which project you want to install it, you shall select all.
A HANDLE
is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLE
s.
For example, GetModuleHandle
returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle
to HeapDestroy
and expect it to do something sensible.
The HANDLE
itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE
returned by GetModuleHandle
is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).
HANDLE
s are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).
Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget
is a struct
.
Widget * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return w;
}
void * GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<void *>(w);
}
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
Widget *w;
w = findWidget(name);
return reinterpret_cast<HANDLE>(w);
}
The first example exposes the internal details about the API: it allows the user code to know that GetWidget
returns a pointer to a struct Widget
. This has a couple of consequences:
Widget
structWidget
struct Both of these consequences may be undesirable.
The second example hides this internal detail from the user code, by returning just void *
. The user code doesn't need access to the header that defines the Widget
struct.
The third example is exactly the same as the second, but we just call the void *
a HANDLE
instead. Perhaps this discourages user code from trying to figure out exactly what the void *
points to.
Why go through this trouble? Consider this fourth example of a newer version of this same API:
typedef void * HANDLE;
HANDLE GetWidget (std::string name)
{
NewImprovedWidget *w;
w = findImprovedWidget(name);
return reinterpret_cast<HANDLE>(w);
}
Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget
struct instead.
The handles in these example are really just a new, presumably friendlier, name for void *
, which is exactly what a HANDLE
is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.
I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:
?function Variable(initVal, onChange)
{
this.val = initVal; //Value to be stored in this object
this.onChange = onChange; //OnChange handler
//This method returns stored value
this.GetValue = function()
{
return this.val;
}
//This method changes the value and calls the given handler
this.SetValue = function(value)
{
this.val = value;
this.onChange();
}
}
And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:
var myVar = new Variable(10, function(){alert("Value changed!");});
Handler function(){alert("Value changed!");}
will be called (if you look at the code) when SetValue()
is called.
You can get value like so:
alert(myVar.GetValue());
You can set value like so:
myVar.SetValue(12);
And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/
The ready event is always execute at the only html page is loaded to the browser and the functions are executed.... But the load event is executed at the time of all the page contents are loaded to the browser for the page..... we can use $ or jQuery when we use the noconflict() method in jquery scripts...
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
use:
std::vector <Acard> playerHand;
everywhere qualify it by std::
or do:
using std::vector;
in your cpp file.
You have to do this because vector
is defined in the std
namespace and you do not tell your program to find it in std
namespace, you need to tell that.
Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then()
so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback
app.service('cookieInfoService', function() {
this.getInfo = function(callback) {
var model = {};
chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
model.response= response;
callback(model);
});
};
});
Then in my controller
app.controller("MyCtrl", function ($scope, cookieInfoService) {
cookieInfoService.getInfo(function (info) {
console.log(info);
});
});
Hope this can help others getting the same issue.
Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "master";
var connectionString = builder.ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "WAITFOR DELAY '00:00:02'";
command.CommandTimeout = 1;
command.ExecuteNonQuery();
}
}
}
}
}
You have set the upstream of that branch
(see:
--set-upstream-to
all the time?"git branch -f --track my_local_branch origin/my_remote_branch # OR (if my_local_branch is currently checked out): $ git branch --set-upstream-to my_local_branch origin/my_remote_branch
(git branch -f --track
won't work if the branch is checked out: use the second command git branch --set-upstream-to
instead, or you would get "fatal: Cannot force update the current branch.
")
That means your branch is already configured with:
branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch
Git already has all the necessary information.
In that case:
# if you weren't already on my_local_branch branch:
git checkout my_local_branch
# then:
git pull
is enough.
If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch
', then a simple git push -u origin my_local_branch:my_remote_branch
would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull
or git push
would, again, have been enough.
Just try the code below:
As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'
I hope this will help ;)
f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file
x = f.readlines() #this command will read file lines
y = int(x)+1
print y
z = str(y) #making data as string to avoid buffer error
f.write(z)
f.close()
I checked most of these answers. then decided to check out Angular documentation on Layout.
Angular has its own Observer for detecting different sizes and it is easy to implement into the component or a Service.
a simpl example would be:
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';_x000D_
_x000D_
@Component({...})_x000D_
class MyComponent {_x000D_
constructor(breakpointObserver: BreakpointObserver) {_x000D_
breakpointObserver.observe([_x000D_
Breakpoints.HandsetLandscape,_x000D_
Breakpoints.HandsetPortrait_x000D_
]).subscribe(result => {_x000D_
if (result.matches) {_x000D_
this.activateHandsetLayout();_x000D_
}_x000D_
});_x000D_
}_x000D_
}
_x000D_
hope it helps
After reading this post some time ago I was wondering if it was safe to use domains for exception handling on an api / function level. I wanted to use them to simplify exception handling code in each async function I wrote. My concern was that using a new domain for each function would introduce significant overhead. My homework seems to indicate that there is minimal overhead and that performance is actually better with domains than with try catch in some situations.
http://www.lighthouselogic.com/#/using-a-new-domain-for-each-async-function-in-node/
as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float
them so that they don't affect each other. the simpler solution is to just set the :active
button to position:relative;
and use top
instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/
Try restarting the mysql or starting it if it wasn't started already. Type this within terminal.
mysql.server restart
To auto start go to the following link below:
How to auto-load MySQL on startup on OS X Yosemite / El Capitan
No jQuery Needed
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
Use the below method to allow css styles in innerhtml
.
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;
constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
<head></head>
<body>
<div style="display:flex; color: blue;">
<div>
<h1>Hello World..!!!!!</h1>
</div>
</div>
</body>
</html>`);
}
Example code stackblitz
Or use the below method to write directly in html. https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1
In addition to values_list
as Daniel mentions you can also use only
(or defer
for the opposite effect) to get a queryset of objects only having their id and specified fields:
Employees.objects.only('eng_name')
This will run a single query:
SELECT id, eng_name FROM employees
Try to relay an array into newArray when looping:
var auctions = Auction.auctions;
var auctionIndex;
var auction;
var newAuctions = [];
for (
auctionIndex = 0;
auctionIndex < Auction.auctions.length;
auctionIndex++) {
auction = auctions[auctionIndex];
if (auction.seconds >= 0) {
newAuctions.push(
auction);
}
}
Auction.auctions = newAuctions;
I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.
private string buffer { get; set; }
private SerialPort _port { get; set; }
public Port()
{
_port = new SerialPort();
_port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
buffer = string.Empty;
}
private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{
buffer += _port.ReadExisting();
//test for termination character in buffer
if (buffer.Contains("\r\n"))
{
//run code on data received from serial port
}
}
Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1
in order to call the method:
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var theType = DLL.GetType("DLL.Class1");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("Output");
method.Invoke(c, new object[]{@"Hello"});
Console.ReadLine();
}
}
BufferedImage in = ImageIO.read(img);
BufferedImage newImage = new BufferedImage(
in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
Your syntax is pretty screwy.
Change this:
input:not(disabled)not:[type="submit"]:focus{
to:
input:not(:disabled):not([type="submit"]):focus{
Seems that many people don't realize :enabled
and :disabled
are valid CSS selectors...
Normal select-dropdown things won't accept styles. BUT. If there's a "size" parameter in the tag, almost any CSS will apply. With this in mind, I've created a fiddle that's practically equivalent to a normal select tag, plus the value can be edited manually like a ComboBox in visual languages (unless you put readonly in the input tag).
<style>
/* only these 2 lines are truly required */
.stylish span {position:relative;}
.stylish select {position:absolute;left:0px;display:none}
/* now you can style the hell out of them */
.stylish input { ... }
.stylish select { ... }
.stylish option { ... }
.stylish optgroup { ... }
</style>
...
<div class="stylish">
<label> Choose your superhero: </label>
<span>
<input onclick="$(this).closest('div').find('select').slideToggle(110)">
<br>
<select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">
<optgroup label="Fantasy"></optgroup>
<option value="gandalf">Gandalf</option>
<option value="harry">Harry Potter</option>
<option value="jon">Jon Snow</option>
<optgroup label="Comics"></optgroup>
<option value="tony">Tony Stark</option>
<option value="steve">Steven Rogers</option>
<option value="natasha">Natasha Romanova</option>
</select>
</span>
<!--
For the sake of simplicity, I used jQuery here.
Today it's easy to do the same without it, now
that we have querySelector(), closest(), etc.
-->
</div>
https://jsfiddle.net/7ac9us70/1052/
Note 1: Sorry for the gradients & all fancy stuff, no they're not necessary, yes I'm showing off, I know, hashtag onlyhuman, hashtag notproud.
Note 2: Those <optgroup>
tags don't encapsulate the options belonging under them as they normally should; this is intentional. It's better for the styling (the well-mannered way would be a lot less stylable), and yes this is painless and works in every browser.
I'd use iloc
, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:
df.iloc[::5, :]
Simplest way is to just use the ShellJS lib ...
$ npm install [-g] shelljs
EXEC Example:
require('shelljs/global');
// Sync call to exec()
var version = exec('node --version', {silent:true}).output;
// Async call to exec()
exec('netstat.exe -an', function(status, output) {
console.log('Exit status:', status);
console.log('Program output:', output);
});
ShellJs.org supports many common shell commands mapped as NodeJS functions including:
It is bounded on the lower end by 2^(n/2)
and on the upper end by 2^n (as noted in other comments). And an interesting fact of that recursive implementation is that it has a tight asymptotic bound of Fib(n) itself. These facts can be summarized:
T(n) = O(2^(n/2)) (lower bound)
T(n) = O(2^n) (upper bound)
T(n) = T(Fib(n)) (tight bound)
The tight bound can be reduced further using its closed form if you like.
Here's an alternate
req.hostname
Read about it in the Express Docs.
Because if none of the if statements evaluate to true then the local variable will be unassigned. Throw an else statement in there and assign some values to those variables in case the if statements don't evaluate to true. Post back here if that doesn't make the error go away.
Your other option is to initialize the variables to some default value when you declare them at the beginning of your code.