Simple Steps, follow them and i guess it will solve your problem
Include these Css in your page,
.progress {
position: relative;
height: 2px;
display: block;
width: 100%;
background-color: white;
border-radius: 2px;
background-clip: padding-box;
/*margin: 0.5rem 0 1rem 0;*/
overflow: hidden;
}
.progress .indeterminate {
background-color:black; }
.progress .indeterminate:before {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; }
.progress .indeterminate:after {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
-webkit-animation-delay: 1.15s;
animation-delay: 1.15s; }
@-webkit-keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@-webkit-keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
@keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
Then include the progress bar your body tag,
<div class="progress" id="PreLoaderBar">
<div class="indeterminate"></div>
</div>
then it will start as your page loads, and now what you have to do is just hide this when the page loads,or set the visibility to none, or hidden, using javascript,
document.onreadystatechange = function () {
if (document.readyState === "complete") {
console.log(document.readyState);
document.getElementById("PreLoaderBar").style.display = "none";
}
}
Let me Know if you face any problems and also, you can add any type of progress bar you can easily find them, for this example i have used a indeterminate progress bar.
My favorite no-conflict-friendly construct:
jQuery(function($) {
// ...
});
Calling jQuery with a function pointer is a shortcut for $(document).ready(...)
Or as we say in coffeescript:
jQuery ($) ->
# code here
Flayway don't recognize the direct environment variables into the application.properties (Spring-Boot V2.1). e.g
spring.datasource.url=jdbc:mysql://${DB_HOSTNAME}:${DB_PORT}/${DB_DATABASE}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}
To solve this issue I did this environment variables, usually I create the file .env:
SPRING_DATASOURCE_URL=jdbc:mysql://127.0.0.1:3306/place
SPRING_DATASOURCE_USERNAME=root
SPRING_DATASOURCE_PASSWORD=root
And export the variables to my environment:
export $(cat .env | xargs)
And finally just run the command
mvn spring-boot:run
Or run your jar file
java -jar target/your-file.jar
There another approach here: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/maven-plugin/examples/run-env-variables.html
'vb.net
'Extended file stributes
'visual basic .net sample
Dim sFile As Object
Dim oShell = CreateObject("Shell.Application")
Dim oDir = oShell.Namespace("c:\temp")
For i = 0 To 34
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
For Each sFile In oDir.Items
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
Next
TextBox1.Text = TextBox1.Text & vbCrLf
Next
You can use UNION ALL instead.
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
Union ALL
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.OtherTable AS ot
In plain C you can use a pointer/size combination in your API.
void doSomething(MyStruct* mystruct, size_t numElements)
{
for (size_t i = 0; i < numElements; ++i)
{
MyStruct current = mystruct[i];
handleElement(current);
}
}
Using pointers is the closest to call-by-reference available in C.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
My guess is:
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Oracle has a similar limitation, which is annoying. I'm curious if there exists a better solution.
To answer the second half of the question, this limitation applies to more complex expressions such as your case statement as well. The best suggestion I've seen it to use a sub-select to name the complex expression.
Using your example::
list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)
Use '[[' to retrieve an element of a list:
b = list_all[[1]]
b
[[1]]
[1] 1
[[2]]
[1] 2
class(b)
[1] "list"
Don't video encoding algorithms like MPEG compute the difference between each frame of a video so they can just encode the delta? You might look into how video encoding algorithms compute those frame differences.
Look at this open source image search application http://www.semanticmetadata.net/lire/. It describes several image similarity algorighms, three of which are from the MPEG-7 standard: ScalableColor, ColorLayout, EdgeHistogram and Auto Color Correlogram.
querySelectorAll returns a NodeList which has its own forEach method:
document.querySelectorAll('input').forEach( input => {
// ...
});
getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:
Array.from(document.getElementsByTagName('input')).forEach( input => {
// ...
});
To do so without compiling the Regex first, use a lambda
function - for example:
from re import match
values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))
print(filtered_values)
Returns:
['123', '234']
filter()
just takes a callable
as it's first argument, and returns a list where that callable returned a 'truthy' value.
Here is a succinct variation that lets you specify any directory. The issue with using directories to find anything is that multiple variables can have the same value. So this code returns a list of possible variables.
def varname( var, dir=locals()):
return [ key for key, val in dir.items() if id( val) == id( var)]
A nice trick to use in place of the various print formats:
(1) Pad with spaces to the right:
('hi' + ' ')[:8]
(2) Pad with leading zeros on the left:
('0000' + str(2))[-4:]
Python support on netbeans is surprisingly good, and comes with most of the features you're looking for.
You can as well use $.when()
to wait until the promise
finished:
var myEvent = function() {
$( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
console.log( 'Task finished.' );
} );
In case you're doing a request that could as well fail, then you can even go one step further:
$.when( myEvent() )
.done( function( d ) {
console.log( d, 'Task done.' );
} )
.fail( function( err ) {
console.log( err, 'Task failed.' );
} )
// Runs always
.then( function( data, textStatus, jqXHR ) {
console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
} );
Swift:
your_CollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
Swift 3
let indexPath = IndexPath(row: itemIndex, section: sectionIndex)
collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.right, animated: true)
Scroll Position:
UICollectionViewScrollPosition.CenteredHorizontally / UICollectionViewScrollPosition.CenteredVertically
You can comput hashes using MessageDigest
, but this is wrong in terms of security. Hashes are not to be used for storing passwords, as they are easily breakable.
You should use another algorithm like bcrypt, PBKDF2 and scrypt to store you passwords. See here.
reference answer of Demodave to eating multi key
function array_sort_by(array $arr, $keys){
if(!is_array($keys))
$keyList = explode(',', $keys);
$keyList = array_keys(array_flip($keyList)); // array_unique
$keyList = array_reverse($keyList);
$result = &$arr;
foreach ($keyList as $key) {
if(array_key_exists($key, $arr))
$result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
}
return $result;
}
Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.
Original answer:
Follow these steps, closely:
C:\Program Files\nodejs
PATH
and choose to edit it.If the PATH variable is empty
, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs
If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm
, append the following right after: ;C:\Program Files\nodejs
If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs
Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.
Re-start the command prompt and npm will now work.
Symbols is the ruby way. However, sometimes one need to talk to some C code or something or Java that expose some enum for various things.
#server_roles.rb
module EnumLike
def EnumLike.server_role
server_Symb=[ :SERVER_CLOUD, :SERVER_DESKTOP, :SERVER_WORKSTATION]
server_Enum=Hash.new
i=0
server_Symb.each{ |e| server_Enum[e]=i; i +=1}
return server_Symb,server_Enum
end
end
This can then be used like this
require 'server_roles'
sSymb, sEnum =EnumLike.server_role()
foreignvec[sEnum[:SERVER_WORKSTATION]]=8
This is can of course be made abstract and you can roll our own Enum class
Thank you pomber but for
var result = client.PostAsync(url, content).Result;
I used
var result = await client.PostAsync(url, content);
because Result makes app lock for high request
Using __doPostBack
directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference
(More seriously though, adding this as an answer for completeness. Using the __doPostBack
directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)
Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):
function RefreshGrid() {
<%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}
You could also do:
Regions.query({}, function(response) {
$scope.regions = response;
// Do stuff that depends on $scope.regions here
});
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
Setting width to 'resolve' didn't work for me. Instead, i added "width:100%" to my select, and modified the css like this :
.select2-offscreen {position: fixed !important;}
This was the only solution that worked for me (my version is 2.2.1) Your select will take all the available place, it is better than using
class="input-medium"
from bootstrap, because the select is always staying in the container, even after resizing the window (responsive)
Use hashlib as hash()
was designed to be used to:
quickly compare dictionary keys during a dictionary lookup
and therefore does not guarantee that it will be the same across Python implementations.
Symfony 3 and newer
I recently made a function which creates a tree of form errors. This will be helpful for returning list of errors back to front-end. This is based on form types having:
'error_bubbling' => false
Code:
public static function getFormErrorsTree(FormInterface $form): array
{
$errors = [];
if (count($form->getErrors()) > 0) {
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
} else {
foreach ($form->all() as $child) {
$childTree = self::getFormErrorsTree($child);
if (count($childTree) > 0) {
$errors[$child->getName()] = $childTree;
}
}
}
return $errors;
}
Output:
Array
(
[name] => Array
(
[0] => This value is not valid.
)
[emails] => Array
(
[0] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
[1] => Array
(
[0] => Given e-mail is not valid.
[1] => Given e-mail is not valid #2.
)
)
)
Notice: I know that errors from deeper level fields can be overwritten if higher level has errors, but this is on purpose for my usage.
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
IE didn't add media query support until IE9. So with IE8 you're out of luck.
Leaving an incredibly simple example in case it helps.
When variable doesn't exist:
if defined? a then "hi" end
# => nil
When variable does exist:
a = 2
if defined? a then "hi" end
# => "hi"
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:
25 + ( std::rand() % ( 63 - 25 + 1 ) )
I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:
struct RuntimeError: LocalizedError
{
let message: String
init(_ message: String)
{
self.message = message
}
public var errorDescription: String?
{
return message
}
}
See this answer for more details.
Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.
Non-clustered indexes are stored separately, and you can have as many as you want.
The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.
If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page
Javascript to be used (always in myForm.php):
function submitform()
{
document.getElementById('myForm').submit();
}
Suppose your form is on myForm.php: Method 1:
<form action="./myForm.php" method="post" id="myForm">
...
</form>
Method 2:
myForm.php:
<form action="./myFormActor.php" method="post" id="myForm">
...
</form>
myFormActor.php:
<?php
//all code here, no output
header("Location: ./myForm.php");
?>
You could make use of APScheduler
in your Flask application and run your jobs via its interface:
import atexit
# v2.x version - see https://stackoverflow.com/a/38501429/135978
# for the 3.x version
from apscheduler.scheduler import Scheduler
from flask import Flask
app = Flask(__name__)
cron = Scheduler(daemon=True)
# Explicitly kick off the background thread
cron.start()
@cron.interval_schedule(hours=1)
def job_function():
# Do your work here
# Shutdown your cron thread if the web process is stopped
atexit.register(lambda: cron.shutdown(wait=False))
if __name__ == '__main__':
app.run()
I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.
<wsdl:service name="serviceMethodName_2">
<wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
<soap:address location="http://new_end_point_adress"/>
</wsdl:port>
</wsdl:service>
This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).
MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]
. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.
To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED
.
You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.
Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:
"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*
As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.
in PHP
$set=array('A','B','C','D');
function permutate($set) {
$b=array();
foreach($set as $key=>$value) {
if(count($set)==1) {
$b[]=$set[$key];
}
else {
$subset=$set;
unset($subset[$key]);
$x=permutate($subset);
foreach($x as $key1=>$value1) {
$b[]=$value.' '.$value1;
}
}
}
return $b;
}
$x=permutate($set);
var_export($x);
I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.
If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.
Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.
<script>
$(document).ready(function () {
$('#DateChanger').click(function() {
$('#dtFrom').val("2012-12-22");
});
});
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>
Remember to include JQuery reference.
//var val = $("#FieldId").val()_x000D_
//Get Value of hidden field by val() jquery function I'm using example string._x000D_
var val = "String to find after - DEMO"_x000D_
var foundString = val.substr(val.indexOf(' - ')+3,)_x000D_
console.log(foundString);
_x000D_
You should add "throws IOException" to your main method:
public static void main(String[] args) throws IOException {
You can read a bit more about checked exceptions (which are specific to Java) in JLS.
I was trying to do the same, but without keeping a variable of autocomplete. I walk throught this calling change handler programatically on the select event, you only need to worry about the actual value of input.
$("#CompanyList").autocomplete({
source: context.companies,
change: handleCompanyChanged,
select: function(event,ui){
$("#CompanyList").trigger('blur');
$("#CompanyList").val(ui.item.value);
handleCompanyChanged();
}
});
Shorter version:
$('#multiselect1').multiselect({
...
onChange: function() {
console.log($('#multiselect1').val());
}
});
If you load your data into ng-grid, you can use the CSV export plugin. The plugin creates a button with the grid data as csv inside an href tag.
http://angular-ui.github.io/ng-grid/
https://github.com/angular-ui/ng-grid/blob/2.x/plugins/ng-grid-csv-export.js
Updating links as the library got renamed:
Github link: https://github.com/angular-ui/ui-grid
Library page: http://ui-grid.info/
Documentation on csv export : http://ui-grid.info/docs/#/tutorial/206_exporting_data
Yes, I just solved the problem today.
Then you can choose the SDK like below :
Hope this helps you.
var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");
v$resource_limit view is so interesting for me in order to glance oracle sessions,processes..:
https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html
My problem was link----> problem1
I solved that problem with one simple command line
Install-Package EntityFramework-IncludePrerelease
After that, i needed to face with one more problem, something like:
"No context type was found in assembly"
I solve this really easy. This "No context" that mean you need to create class in "Model" folder in your app with suffix like DbContext ... like this MyDbContext. There you need to include some library using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Oceans.Models
{
public class MyDbContext:DbContext
{
public MyDbContext()
{
}
}
}
After that,i just needed this command line:
Enable-Migrations -ProjectName <YourProjectName> -ContextTypeName <YourContextName>
Since you declare sample
inside the anonymous function you pass to ready
, it is scoped to that function.
You then pass a string to setTimeout
which is eval
ed after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout
, using eval is inefficient and hard to debug.
setTimeout(sample,2000)
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
RUN
and ENTRYPOINT
are two different ways to execute a script.
RUN
means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.
ENTRYPOINT
means your image (which has not executed the script yet) will create a container, and runs that script.
In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh
is a good idea.
It should also start with a shebang (like #!/bin/sh
)
Considering your script (bootstrap.sh
: a couple of git config --global
commands), it would be best to RUN
that script once in your Dockerfile
, but making sure to use the right user (the global git config
file is %HOME%/.gitconfig
, which by default is the /root
one)
Add to your Dockerfile:
RUN /bootstrap.sh
Then, when running a container, check the content of /root/.gitconfig
to confirm the script was run.
Given $arrService = Get-Service -Name $ServiceName
, $arrService.Status
is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh()
when needed to renew the properties to current values.
MSDN ~ ServiceController.Refresh()
Refreshes property values by resetting the properties to their current values.
You can use AlarmManager in coop with notification mechanism Something like this:
Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}
It starts alarm.
public class ReminderBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(...)
.setContentTitle(..)
.setContentText(..);
Intent intentToFire = new Intent(context, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
}
}
Implementing the SearchView without the use of the menu.xml
file and open through button
In your Activity
we need to use the method of the onCreateOptionsMenu
method in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView
on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
Semantically there is no difference between these cases in LDAP.
According to Google Developers article, you can:
<script src="..." async>
or element.appendChild()
,For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition
Basic usage:
var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.
You can check whether this is your case quite easily: just connect to your server http://www.example.com:443. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.
Cheers!
Advanced way to check the exact word, that we need to find in a long string:
import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock"
for m in re.finditer(r"\bof\b", text):
if m.group(0):
print "Present"
else:
print "Absent"
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
Setting val('')
will empty the input field. So you would use this:
Clear the input field when the page loads:
$(function(){
$('#shares').val('');
});
All that the call to urlopen()
does (according to the docs) is return a file-like object. Once you have that, you need to call its read()
method to actually pull the JSON data across the network.
Something like:
jsonurl = urlopen(url)
text = json.loads(jsonurl.read())
print text
Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:
<style type="text/css">
body {
margin: 0px;
}
/*
* this is the same as writing
* body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
* I'm adding px here for clarity sake but the unit is not really needed if you have 0
* look into em, pt and % for other unit types
* the rules are always clockwise: top, right, bottom, left
*/
</style>
2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:
<link rel="stylesheet" type="text/css" href="style.css"/>
Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers
There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV
) file with the XChart library. Disclaimer: I'm the lead developer of the project.
In this example, two text files exist in ./CSV/CSVChartRows/
. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1
contains x
, y
, and error bar
data, whereas series2
contains just x
and y
, data.
1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5
1,56
2,34
3,12
4,26
public class CSVChartRows {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);
// Show it
new SwingWrapper(chart).displayChart();
}
}
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...)
and cola<string>::cola(...)
until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T>
also.)
The problem is caused by the fact that main.cpp
and cola.cpp
will be compiled separately first. In main.cpp
, the compiler will implicitly instantiate the template classes cola<float>
and cola<string>
because those particular instantiations are used in main.cpp
. The bad news is that the implementations of those member functions are not in main.cpp
, nor in any header file included in main.cpp
, and therefore the compiler can't include complete versions of those functions in main.o
. When compiling cola.cpp
, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float>
or cola<string>
. Remember, when compiling cola.cpp
, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>
, cola<char>
, cola<ostream>
, cola< cola<int> >
... and so on ...)
The two answers are:
cola.cpp
, which particular template classes will be required, forcing it to compile cola<float>
and cola<string>
.main.cpp
) uses the template class.At the end of cola.cpp
, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp
:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp
that it will explicitly compile all the code for the cola<float>
and cola<string>
classes. Similarly, nodo_colaypila.cpp
contains the implementations of the nodo_colaypila<...>
classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp
file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
The common answer is to move all the code from the implementation files cola.cpp
and nodo_colaypila.cpp
into cola.h
and nodo_colaypila.h
. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>
) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float>
and cola<string>
, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
#endif
at the end of nodo_colaypila.hnodo_colaypila<T>* ult, pri;
should be nodo_colaypila<T> *ult, *pri;
- both are pointers.nodo_colaypila.h
, not in this implementation file.You want to use a dict.
#!/usr/bin/env python
input = "this is a string"
d = {}
for c in input:
try:
d[c] += 1
except:
d[c] = 1
for k in d.keys():
print "%s: %d" % (k, d[k])
try this following snippet, its working fine.
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openfile1.FileName;
}
{
string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
OleDbConnection conn = new OleDbConnection(pathconn);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
MyDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch { }
}
I did this to be able to update the value of ngModel from the outside with Vanilla/jQuery:
function getScope(fieldElement) {
var $scope = angular.element(fieldElement).scope();
var nameScope;
var name = fieldElement.getAttribute('name');
if($scope) {
if($scope.form) {
nameScope = $scope.form[name];
} else if($scope[name]) {
nameScope = $scope[name];
}
}
return nameScope;
}
function setScopeValue(fieldElement, newValue) {
var $scope = getScope(fieldElement);
if($scope) {
$scope.$setViewValue(newValue);
$scope.$validate();
$scope.$render();
}
}
setScopeValue(document.getElementById("fieldId"), "new value");
you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide
Because its primary use is displaying numbers? If you want to round numbers, use Math.round()
with apropriate factors.
I'm using Moment JS. Is very helpful and easy to use.
var date = moment(); //Get the current date
date.format("YYYY-MM-DD"); //2014-07-10
I was facing the same issue while i was using JDK 1.8.0_05 64 bit and eclipse-jee-oxygen-3a-win32-x86_64 on Windows 64 bit Operating System.
Finally i resolved the issue by changing JDK version jdk1.8.0_05 to jdk1.8.0_172
Here is the complete procedure for IDEA IntelliJ 2019.3:
File > Project Structure
Under Project Settings > Modules
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
Apply changes.
I'm sure there's a more efficient way to do it, but I would probably do this:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
Initially it was to be a comma, however as the comma is often used as a decimal point it wouldnt be such good separator, hence others like the semicolon, mostly country dependant
http://en.wikipedia.org/wiki/Comma-separated_values#Lack_of_a_standard
From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script>
tag after the chart.js tag on your page), your charts begin to display values.
If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:
var myBarChart = new Chart(ctx, {
type: 'bar',
data: yourDataObject,
options: {
// other options
plugins: {
datalabels: {
anchor :'end',
align :'top',
// and if you need to format how the value is displayed...
formatter: function(value, context) {
return GetValueFormatted(value);
}
}
}
}
});
This has been asked before on Stack. See the following links:
Basically you just need to set up the thread with a stop function that sets a sentinel value that the thread will check. In your case, you'll have the something in your loop check the sentinel value to see if it's changed and if it has, the loop can break and the thread can die.
<form>
<div class="form-group">
<label for="nameLabel">Name</label>
<input id="name" name="name" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="PhoneLabel">Phone</label>
<input id="phone" name="phone" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="yearLabel">Year</label>
<input id="year" name="year" class="form-control" type="text" />
</div>
</form>
If you're doing an unusual import (e.g., it's an options file), try:
import inspect
print (inspect.getfile(inspect.currentframe()))
Note that this will return the absolute path to the file.
Move the session_start();
to top of the page always.
<?php
@ob_start();
session_start();
?>
Be careful if you replace URLs with "/" character.
An example of how to do it:
sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"
Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html
Just the simple oneliner without any additional permissions needed:
private void dialContactPhone(final String phoneNumber) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNumber, null)));
}
The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.
For instance:
echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7
Will result in output of:
2 3.4
-d sets the delimiter
-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7
.
If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout
value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.
For example:
// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;
This value can also be configured in your web.config
file in the httpRuntime
configuration element:
<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300"
... other configuration attributes ...
/>
Please note according to the MSDN documentation:
"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."
If you've already done this but are finding that your session is expiring then increase the
ASP.NET HttpSessionState.Timeout
value:
For example:
// Increase session timeout to thirty minutes
Session.Timeout = 30;
This value can also be configured in your web.config
file in the sessionState
configuration element:
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.
The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.
What about (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))
.
This is the same as 2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2)
.
If sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes]
.
You can't use 2*(1 << (8*sizeof(int)-2)) - 1
because it will overflow, but (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))
works.
Use the Windows API. Call GetForegroundWindow()
.
GetForegroundWindow()
will give you a handle (named hWnd
) to the active window.
Documentation: GetForegroundWindow function | Microsoft Docs
I modified the sample by dimarzionist. This version will only work with Enums and not let structs get through.
public static T ParseEnum<T>(string enumString)
where T : struct // enum
{
if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
throw new Exception("Type given must be an Enum");
try
{
return (T)Enum.Parse(typeof(T), enumString, true);
}
catch (Exception ex)
{
return default(T);
}
}
Merging using an extension method. It does not throw exception when there are duplicate keys, but replaces those keys with keys from the second dictionary.
internal static class DictionaryExtensions
{
public static Dictionary<T1, T2> Merge<T1, T2>(this Dictionary<T1, T2> first, Dictionary<T1, T2> second)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
var merged = new Dictionary<T1, T2>();
first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
return merged;
}
}
Usage:
Dictionary<string, string> merged = first.Merge(second);
I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
@( condition ? "true" : "false" )
use below class to download and load images in listview.It caches every images once download. Also loads images ad lazy loading.
package com.fudiyoxpress.images;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;
import com.fudiyoxpress.R;
import com.fudiyoxpress.config.Config;
import com.fudiyoxpress.twitter.ScaleBitmap;
public class ImageLoader {
// Initialize MemoryCache
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
Context C;
// Create Map (collection) to store image and image url in key value pair
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
C = context;
fileCache = new FileCache(context);
// Creates a thread pool that reuses a fixed number of
// threads operating off a shared unbounded queue.
executorService = Executors.newFixedThreadPool(5);
}
// default image show in list (Before online image download)
final int stub_id = R.drawable.restlogoplaceholder;
public void DisplayImage(String url, ImageView imageView, Context context,
boolean header_flag) {
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.restlogoplaceholder);
header_flag = false;
// Store image and url in Map
imageViews.put(imageView, url);
// Check image is stored in MemoryCache Map or not (see
// MemoryCache.java)
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
// if image is stored in MemoryCache Map then
// Show image in listview row
Bitmap b = ScaleBitmap
.getScaledBitmap(context, bitmap, header_flag);
imageView.setImageBitmap(b);
} else {
// queue Photo to download from url
queuePhoto(url, imageView, header_flag);
// Before downloading image show default image
imageView.setImageBitmap(ScaleBitmap.getScaledBitmap(context,
largeIcon, header_flag));
}
}
private void queuePhoto(String url, ImageView imageView, boolean header_flag) {
// Store image and url in PhotoToLoad object
PhotoToLoad p = new PhotoToLoad(url, imageView, header_flag);
// pass PhotoToLoad object to PhotosLoader runnable class
// and submit PhotosLoader runnable to executers to run runnable
// Submits a PhotosLoader runnable task for execution
executorService.submit(new PhotosLoader(p));
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public boolean b;
public PhotoToLoad(String u, ImageView i, boolean header_flag) {
url = u;
imageView = i;
b = header_flag;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
// Check if image already downloaded
if (imageViewReused(photoToLoad))
return;
// download image from web url
Bitmap bmp = getBitmap(photoToLoad.url);
// set image data in Memory Cache
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
// Get bitmap to display
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// Causes the Runnable bd (BitmapDisplayer) to be added to the
// message queue.
// The runnable will be run on the thread to which this handler
// is attached.
// BitmapDisplayer run method will call
handler.post(bd);
} catch (Throwable th) {
// th.printStackTrace();
}
}
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
// CHECK : if trying to decode file which not exist in cache return null
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download image file from web
try {
// // download the image
Bitmap bitmap = null;
URL imageURL = null;
try {
imageURL = new URL(Config.WEB_URL + "/ServeBlob?id=" + url);
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
// if(!(new File(imageURL.toString())).exists())
// {
// imageURL=new URL("");
// }
InputStream inputStream = connection.getInputStream();
// Constructs a new FileOutputStream that writes to
// file
// if file not exist then it will create file
OutputStream os = new FileOutputStream(f);
// See Utils class CopyStream method
// It will each pixel from input stream and
// write pixels to output stream (file)
Utils.CopyStream(inputStream, os);
os.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeStream(inputStream, null, options);
} catch (IOException e) {
// e.printStackTrace();
}
// Now file created and going to resize file with defined height
// Decodes image and scales it to reduce memory consumption
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE = 85;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
// Check url is already exist in imageViews MAP
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
// Show bitmap on UI
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(ScaleBitmap
.getScaledBitmap(C, bitmap, photoToLoad.b));
} else {
}
// photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
// Clear cache directory downloaded images and stored data in maps
memoryCache.clear();
fileCache.clear();
}
}
package com.fudiyoxpress.images;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
private static final String TAG = "MemoryCache";
//Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));
//current allocated size
private long size=0;
//max memory cache folder used to download images in bytes
private long limit = 1000000;
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
package com.fudiyoxpress.images;
import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
//Read byte from input stream
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
//Write byte from output stream
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
The organization of Morse code is a binary tree.
Just thought I'd throw this out there as well.
I haven't been able to test it in older browsers, but it works in the latest of the top 3. :)
Element.prototype.getOffsetTop = function() {
return ( this.parentElement )? this.offsetTop + this.parentElement.getOffsetTop(): this.offsetTop;
};
Element.prototype.getOffsetLeft = function() {
return ( this.parentElement )? this.offsetLeft + this.parentElement.getOffsetLeft(): this.offsetLeft;
};
Element.prototype.getOffset = function() {
return {'left':this.getOffsetLeft(),'top':this.getOffsetTop()};
};
those various ways of switch ...
# by index
switch(1, "one", "two")
## [1] "one"
# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"
# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"
# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
sudo apt-get install phpx.x-gd
sudo service apache2 restart
x.x is the versión php.
The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.
As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.
These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.
Late answer, but I found out that this is the simplest solution (if you don't use jQuery):
var myClasses = document.querySelectorAll('.my-class'),
i = 0,
l = myClasses.length;
for (i; i < l; i++) {
myClasses[i].style.display = 'none';
}
Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.
To back up my argument I submit the following.
onclick="location.href"
model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?
Add workbench.colorCustomizations
to user settings
"workbench.colorCustomizations": {
"terminal.background":"#FEFBEC",
"terminal.foreground":"#6E6B5E",
...
}
Check https://glitchbone.github.io/vscode-base16-term for some presets.
I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.
Set the window start style as maximized. Then, hide the minimize and maximize buttons.
in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection)
I always used the above solution without searching more after this. ;-)
However, today I came across something and thought of sharing it. :)
This feature is indeed available from API 1 and is called as ColorStateList, where we can supply a color to various states of Widgets (as we already know).
It is also very well documented, here.
If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.
Using "Compilers Principles, Techniques, & Tools, 2nd Ed." (WorldCat) by Aho, Lam, Sethi and Ullman, AKA the Purple Dragon Book,
Lexeme pg. 111
A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.
Token pg. 111
A token is a pair consisting of a token name and an optional attribute value. The token name is an abstract symbol representing a kind of lexical unit, e.g., a particular keyword, or sequence of input characters denoting an identifier. The token names are the input symbols that the parser processes.
Pattern pg. 111
A pattern is a description of the form that the lexemes of a token may take. In the case of a keyword as a token, the pattern is just the sequence of characters that form the keyword. For identifiers and some other tokens, the pattern is more complex structure that is matched by many strings.
Figure 3.2: Examplesof tokens pg.112
[Token] [Informal Description] [Sample Lexemes]
if characters i, f if
else characters e, l, s, e else
comparison < or > or <= or >= or == or != <=, !=
id letter followed by letters and digits pi, score, D2
number any numeric constant 3.14159, 0, 6.02e23
literal anything but ", surrounded by "'s "core dumped"
To better understand this relation to a lexer and parser we will start with the parser and work backwards to the input.
To make it easier to design a parser, a parser does not work with the input directly but takes in a list of tokens generated by a lexer. Looking at the token column in Figure 3.2 we see tokens such as if
, else
, comparison
, id
, number
and literal
; these are names of tokens. Typically with a lexer/parser a token is a structure that holds not only the name of the token, but the characters/symbols that make up the token and the start and end position of the string of characters that make up the token, with the start and end position being used for error reporting, highlighting, etc.
Now the lexer takes the input of characters/symbols and using the rules of the lexer converts the input characters/symbols into tokens. Now people who work with lexer/parser have their own words for things they use often. What you think of as a sequence of characters/symbols that make up a token are what people who use lexer/parsers call lexeme. So when you see lexeme, just think of a sequence of characters/symbols representing a token. In the comparison example, the sequence of characters/symbols can be different patterns such as <
or >
or else
or 3.14
, etc.
Another way to think of the relation between the two is that a token is a programming structure used by the parser that has a property called lexeme that holds the character/symbols from the input. Now if you look at most definitions of token in code you may not see lexeme as one of the properties of the token. This is because a token will more likely hold the start and end position of the characters/symbols that represent the token and the lexeme, sequence of characters/symbols can be derived from the start and end position as needed because the input is static.
While the built-in libs for XML parsing are quite good I am partial to lxml.
But for parsing RSS feeds, I'd recommend Universal Feed Parser, which can also parse Atom. Its main advantage is that it can digest even most malformed feeds.
Python 2.6 already includes a JSON parser, but a newer version with improved speed is available as simplejson.
With these tools building your app shouldn't be that difficult.
Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.
You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments
Firebug lite plugin in Safari extensions didn't work (it's made by slicefactory, I don't think it's offical). btw, #2 works for me!
Check out this bash cheatsheet, it can help alot.
To check the length of arguments passed in, you use "$#"
To use the array of arguments passed in, you use "$@"
An example of checking the length, and iterating would be:
myFunc() {
if [[ "$#" -gt 0 ]]; then
for arg in "$@"; do
echo $arg
done
fi
}
myFunc "$@"
This articled helped me, but was missing a few things for me and my situation. Hopefully this helps someone.
Adding to Rob?'s answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).
>>> f'{a*1000:,.2f}'
'10,123.40'
I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Deepankar Sinha
*/
public class GetList {
public List<String> stack;
static List<String> lnkFile;
static List<String> progName;
int index=-1;
public static void main(String args[]) throws IOException
{
//var-- progFile:Location of the file to be search.
String progFile="C:\\";
GetList obj=new GetList();
String temp=progFile;
int i;
while(!"&%@#".equals(temp))
{
File dir=new File(temp);
String[] directory=dir.list();
if(directory!=null){
for(String name: directory)
{
if(new File(temp+name).isDirectory())
obj.push(temp+name+"\\");
else
if(new File(temp+name).isFile())
{
try{
//".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
{
//obj.addFile(temp+name,name);
System.out.println(temp+name);
}
}catch(StringIndexOutOfBoundsException e)
{
//debug purpose
System.out.println("ERROR******"+temp+name);
}
}
}}
temp=obj.pop();
}
obj.display();
// for(int i=0;i<directory.length;i++)
// System.out.println(directory[i]);
}
public GetList() {
this.stack = new ArrayList<>();
this.lnkFile=new ArrayList<>();
this.progName=new ArrayList<>();
}
public void push(String dir)
{
index++;
//System.out.println("PUSH : "+dir+" "+index);
this.stack.add(index,dir);
}
public String pop()
{
String dir="";
if(index==-1)
return "&%@#";
else
{
dir=this.stack.get(index);
//System.out.println("POP : "+dir+" "+index);
index--;
}
return dir;
}
public void addFile(String name,String name2)
{
lnkFile.add(name);
progName.add(name2);
}
public void display()
{
GetList.lnkFile.stream().forEach((lnkFile1) -> {
System.out.println(lnkFile1);
});
}
}
I have a clearer proposal on automatic search in a DataGridView
this is an example
private void searchTb_TextChanged(object sender, EventArgs e)
{
try
{
(lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
"lename IS NOT NULL" :
String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
}
catch (Exception ex) {
MessageBox.Show(ex.StackTrace);
}
}
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
<p id="text" onclick="func()">
Click on text to change
</p>
<script>
function func()
{
document.getElementById("text").style.color="red";
document.getElementById("text").style.font="calibri";
}
</script>
Weirdly I previously had an error The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256
. There was an answer on Stackoverflow which required to add AWS_S3_REGION_NAME = 'eu-west-2' (your region)
, AWS_S3_SIGNATURE_VERSION = "s3v4
.
After doing that the previous error cleared but I ended up with this signature error again. Searched for answers until I ended up removing the AWS_S3_SIGNATURE_VERSION = "s3v4
Then it worked. Placed it here maybe it might help someone. I am using Django by the way.
To scroll to a specific element on your page, you can add a function into your jQuery(document).ready(function($){...})
as follows:
$("#fromTHIS").click(function () {
$("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
return true;
});
It works like a charm in all browsers. Adjust the speed according to your need.
Maybe .value_counts()
?
>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0 1
1 2
2 2
3 3
4 3
5 3
6 fred
7 1.8
8 1.8
>>> counts = my_series.value_counts()
>>> counts
3 3
2 2
1.8 2
fred 1
1 1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
Simply use the on click event for tab shown.
$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});
POJOS
with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS
.
May not be what is needed here but it's a very old question and the answer may help others. A tip I find useful with importing into Excel with a different separator is to open the file in a text editor and add a first line like:
sep=|
where | is the separator you wish Excel to use. Alternatively you can change the default separator in Windows but a bit long-winded:
Control Panel>Clock & region>Region>Formats>Additional>Numbers>List separator [change from comma to your preferred alternative]. That means Excel will also default to exporting CSVs using the chosen separator.
For a functional programming Ramda has a nice method for this. The same method works going from positive to negative and vice versa.
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
This is not relevant to this particular case because of the decimals, but may help people who google the heading. Integer fields convert fine to varchars, but floats change to scientific notation. A very quick way to change a float quickly if you do not have decimals is therefore to change the field first to an integer and then change it to a varchar.
If you're testing firebase app locally then you need to point functions to localhost
instead of cloud. By default, firebase serve
or firebase emulators:start
points the functions to server instead of localhost when you use it on your web app.
Add below script in html head after firebase init script:
<script>
firebase.functions().useFunctionsEmulator('http://localhost:5001')
</script>
Make sure to remove this snippet when deploying code to server.
The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString
examples below work.
$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"
switch ($someString) {
{"y","yes"} { "You entered Yes." }
Default { "You didn't enter Yes."}
}
Here is my $PSVersionTable
data.
Name Value
---- -----
PSVersion 5.1.17763.771
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.771
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
This is an old thread, but I ran into java.net.SocketException: Connection reset
yesterday.
The server-side application had its throttling settings changed to allow only 1 connection at a time! Thus, sometimes calls went through and sometimes not. I solved the problem by changing the throttling settings.
go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
go
test file in that package-run TestCaseFunc
Look at the jQuery unload function. It handles all the things.
https://api.jquery.com/unload/
The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
$(window).unload(
function(event) {
alert("navigating");
}
);
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
Agree with @Tillito, however in most cases it will foul SQL optimizer and it will not use right indexes.
It may be obvious for somebody, but I burned hours solving performance issues using Tillito solution. Lets say you have the table:
Create table OrderDetail
(
Id int primary key,
CustomerId int references Customer(Id),
Amount decimal default(0)
);
Create index ix_customer on OrderDetail(CustomerId);
and your view is something like this
Create view CustomerView
As
Select
IsNull(CustomerId, -1) as CustomerId, -- forcing EF to use it as key
Sum(Amount) as Amount
From OrderDetail
Group by CustomerId
Sql optimizer will not use index ix_customer and it will perform table scan on primary index, but if instead of:
Group by CustomerId
you use
Group by IsNull(CustomerId, -1)
it will make MS SQL (at least 2008) include right index into plan.
If
In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
In[3]: series # without nan
Out[3]:
0 True
2 False
dtype: object
# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement
# operator instead as in `lambda x : (-1*x)-1`
In[4]: ~series
Out[4]:
0 -2
2 -1
dtype: object
as a simple non-vectorized solution you can just, 1. check types2. inverse bools
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]:
Out[2]:
0 True
1 NaN
2 False
3 NaN
dtype: object
If you are trying to "checkout" a new remote branch (that exists only on the remote, but not locally), here's what you'll need:
git fetch origin
git checkout --track origin/<remote_branch_name>
This assumes you want to fetch from origin. If not, replace origin by your remote name.
Greedy will consume as much as possible. From http://www.regular-expressions.info/repeat.html we see the example of trying to match HTML tags with <.+>
. Suppose you have the following:
<em>Hello World</em>
You may think that <.+>
(.
means any non newline character and +
means one or more) would only match the <em>
and the </em>
, when in reality it will be very greedy, and go from the first <
to the last >
. This means it will match <em>Hello World</em>
instead of what you wanted.
Making it lazy (<.+?>
) will prevent this. By adding the ?
after the +
, we tell it to repeat as few times as possible, so the first >
it comes across, is where we want to stop the matching.
I'd encourage you to download RegExr, a great tool that will help you explore Regular Expressions - I use it all the time.
In my case ,I created a project and made its minSdkVersion=9
and targetSdkVersion=17
. I used automatically generated libs/android-support-v4.jar
. I also had to make use of ActionBarActivity
using android-support-v7-appcomapt.jar
. So I just copied the android-support-v7-appcompat.jar
file from android-sdk/extras/andrid/support/v7/appcompat/libs
folder and pasted it to my project libs
folder. And this caused the above error.
So basically,I needed to put android-support-v4.jar
file from android-sdk/extras/andrid/support/v7/appcompat/libs
as well to my project libs
folder. As per my knowledge the v7.jar
file had dependencies on v4.jar
file. So ,it needed it own v4.jar
file,instead of my project,automatically created v4.jar
file.
var index = array.indexOf('item');
if(index!=-1){
array.splice(index, 1);
}
had a similiar issue on a server but the SVN directory was very large , didn't want to delete and resync so I just made a copy of the files locally and then deleted them. When update succeeded and added files back in.
for me it is correct, in Excel spanish
=CONCATENAR(
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(16384,20479),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(32768,49151),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8)
)
in osx, i installed with brew, here is the setting that works for me
GOPATH="$HOME/my_go_work_space" //make sure you have this folder created
GOROOT="/usr/local/Cellar/go/1.10/libexec"
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
In my case, I had the following structure of a project:
When I was running the test, I kept receiving problems with auro-wiring both facade and kafka attributes - error came back with information about missing instances, even though the test and the API classes reside in the very same package. Apparently those were not scanned.
What actually helped was adding @Import annotation bringing the missing classes to Spring classpath and making them being instantiated.
I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.
create a class that extends HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String x = request.getMethod();
logger.info(x + "intercepted");
return true;
}
}
then Implement WebMvcConfigurer interface
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
EmployeeInterceptor employeeInterceptor ;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
}
}
You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).
The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).
Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.
Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );
startActivity(promptInstall);
To find the folder location, you can just run the app, open the task manager (CTRL-SHIFT-ESC), select the app and right-click|Open file location.
Another dirty but working workaround. Assumes you are on top level of your package.
import sys
from os.path import dirname, basename
if __package__ is None:
sys.path.append('..')
__package__ = basename(dirname(sys.argv[0]))
from . import your_module
The advantage vs another answer here is that you don't need to change imports which are autogenerated by IDE.
let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
userImageView.addGestureRecognizer(pictureTap)
userImageView.isUserInteractionEnabled = true
@objc func imageTapped() {
let imageView = userImageView
let newImageView = UIImageView(image: imageView?.image)
newImageView.frame = UIScreen.main.bounds
newImageView.backgroundColor = UIColor.black
newImageView.contentMode = .scaleAspectFit
newImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
self.navigationController?.isNavigationBarHidden = true
self.tabBarController?.tabBar.isHidden = true
}
It depends on what you mean with "empty".
When you attempt to get the value of a property on an object which has no property with that name, you will get the value undefined
.
That's what happens with sparse arrays: not all indices between 0
and array.length-1
exist.
So you could check if array[index] === undefined
.
However, the property index
could exist with an undefined
value. If you want to filter out this case, you can use the in
operator or hasOwnProperty
, as described in How do I check if an object has a property in JavaScript?
index in array;
array.hasOwnProperty(index);
If you want consider an existing property with an undefined
or null
value to not exist, you can use the loose comparison array[index] == undefined
or array[index] == null
.
If you know the array is not sparse, you could compare index
with array.length
. But to be safe, you may want to ensure that index
really is an array index, see Check if property name is array index
I recently encountered this problem while working on a contract project(deemed classified). The system in which I had to run the code did not have internet access, for security purposes of course, and so installing dependencies, using composer and npm, was becoming huge pain.
After much deliberation with my colleague, we decided to just wing it and copy paste our dependencies rather than doing composer install or npm install.
This led us to NOT add vendors and npm_modules in gitignore. This is when I encountered this problem.
Changed but not updated:
modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content)
I googled this a bit and found this helpful thread on SO. Not being too much of a pro in Git, and being a little intoxicated while working on it, I just searched for all the submodules in the vendors folder
find . -name ".git"
This gave me some 4-5 dependencies that had git on them. I removed all these .git folders and voila, it worked. I knows it's hack, and not a very geeky one anyways. O Gods of SO, please forgive me! Next time I promise to read up on gitlinks and obey O mighty Linus Tovalds.
mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.
found out it's possible with self.current_method
easily found at http://www.ruby-forum.com/topic/75258
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two
If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two
I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.
This method is also more extensible in the case where you may have 3 column levels.
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three
In Arch Linux using a UK keyboard and locale, I had the following error:
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = "en_US.utf8"
Exporting my locales in /etc/profile
didn't fix it.
I did however fix this by editing /etc/locale.gen
, also enabling the en_US.utf8
locale that perl
expected to find, and running local-gen
.
(I use pac-manager which uses a whole bunch of perl
modules from AUR, so reinstalling perl
in my particular case would be a nuisance.)
If you like to manually manage your profiles (mostly to clean up):
No longer supported ... you can also download Apple's iPhone Configuration Utility 3.5 for Mac OS X, it still has "Provisioning Profiles" and works with Xcode 5 -- it's now gone from Apples site but you can find an alternative download link in @suda's comment.
$each
will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}
I ran into this same issue but found out that there is a JSON encoder that can be used to move these objects between processes.
from pyVmomi.VmomiSupport import VmomiJSONEncoder
Use this to create your list:
jsonSerialized = json.dumps(pfVmomiObj, cls=VmomiJSONEncoder)
Then in the mapped function, use this to recover the object:
pfVmomiObj = json.loads(jsonSerialized)
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
The benefits of get() set() methods are as follows ..
Example:
private String personName;
private int personId;
public void setPersonName(String name) throws Exception{
if(!(name.equals("")||name=="")){
this.personName = name;
}
}
public String getPersonName(){
return this.personName;
}
public void setPersonId(int id) throws Exception{
this.personId = id;
}
public int getPersonId(){
return this.personId;
}
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
The default behaviour is false:
By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !
Well you seem to have mistaken them both for what they do.
$(window).height()
gets you an unit-less pixel value of the height of the (browser) window aka viewport. With respect to the web browsers the viewport here is visible portion of the canvas(which often is smaller than the document being rendered).
$(document).height()
returns an unit-less pixel value of the height of the document being rendered. However, if the actual document’s body height is less than the viewport height then it will return the viewport height instead.
Hope that clears things a little.
You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE
clause, and then UNION
them together:
select
'Test1', *
from
TABLE
Where
CCC='D' AND DDD='X' AND exists(select ...)
UNION
select
'Test2', *
from
TABLE
Where
CCC<>'D' AND DDD='X' AND exists(select ...)
This might be an issue, because you are going to effectively scan/seek on TABLE twice.
The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:
select
case
when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
end,
*
from
TABLE
Where
(CCC='D' AND DDD='X' AND exists(select ...)) or
(CCC<>'D' AND DDD='X' AND exists(select ...))
The catch here being that you will have to duplicate the filter conditions in the CASE
statement and the WHERE
statement.
For me the problem was that I was setting REQUESTS_CA_BUNDLE
in my .bash_profile
/Users/westonagreene/.bash_profile:
...
export REQUESTS_CA_BUNDLE=/usr/local/etc/openssl/cert.pem
...
Once I set REQUESTS_CA_BUNDLE
to blank (i.e. removed from .bash_profile
), requests
worked again.
export REQUESTS_CA_BUNDLE=""
The problem only exhibited when executing python requests
via a CLI (Command Line Interface). If I ran requests.get(URL, CERT)
it resolved just fine.
Mac OS Catalina (10.15.6).
Pyenv of 3.6.11.
Error message I was getting: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)
My answer elsewhere: https://stackoverflow.com/a/64151964/4420657
Copies a directory named html & all its contents to a destination directory in silent mode. If the destination directory is not present it will still create it.
@echo off
TITLE Copy Folder with Contents
set SOURCE=C:\labs
set DESTINATION=C:\Users\MyUser\Desktop\html
xcopy %SOURCE%\html\* %DESTINATION%\* /s /e /i /Y >NUL
/S Copies directories and subdirectories except empty ones.
/E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.
/I If destination does not exist and copying more than one file, assumes that destination must be a directory.
If you are completely sure HEAD is the good state:
git branch -f master HEAD
git checkout master
You probably can't push to origin, since your master has diverged from origin. If you are sure no one else is using the repo, you can force-push:
git push -f
Most useful if you are on a feature branch no one else is using.
looks like you have maven project and so resources are in classpath by
go for
getClass().getResource("classpath:storedProcedures.sql")
This method takes into account timezone issue and daylight saving time
function dayofyear(d) { // d is a Date object
var yn = d.getFullYear();
var mn = d.getMonth();
var dn = d.getDate();
var d1 = new Date(yn,0,1,12,0,0); // noon on Jan. 1
var d2 = new Date(yn,mn,dn,12,0,0); // noon on input date
var ddiff = Math.round((d2-d1)/864e5);
return ddiff+1;
}
(took from here)
See also this fiddle
1) Also you can use lateinit
If you sure do your initialization later on onCreate()
or elsewhere.
Use this
lateinit var left: Node
Instead of this
var left: Node? = null
2) And there is other way that use !!
end of variable when you use it like this
queue.add(left!!) // add !!
This should do what you're looking for:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
Usage:
echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g
Edit:
Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.
Examples:
Random number in a range
auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point
Random boolean
auto val = Random::get<bool>( ) // 50% to generate true
auto val = Random::get<bool>( 0.7 ) // 70% to generate true
Random value from a std::initilizer_list
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
Random iterator from iterator range or all container
auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator
auto it = Random::get( vec ); // return random iterator
And even more things ! Check out the github page:
I couldn't make any of the answers here to work. As a horrible hack, I store in local storage a timestamp when I change the route, and check at page initialization whether this timestamp is set and recent, in that case I don't trigger some initialization actions.
In controller:
window.localStorage['routeChangeWithoutReloadTimestamp'] = new Date().getTime();
$location.path(myURL);
In config:
.when(myURL, {
templateUrl: 'main.html',
controller:'MainCtrl',
controllerAs: 'vm',
reloadOnSearch: false,
resolve:
{
var routeChangeWithoutReloadTimestamp =
window.localStorage['routeChangeWithoutReloadTimestamp'];
var currentTimestamp = new Date().getTime();
if (!routeChangeWithoutReloadTimestamp ||
currentTimestamp - routeChangeWithoutReloadTimestamp >= 5000) {
//initialization code here
}
//reset the timestamp to trigger initialization when needed
window.localStorage['routeChangeWithoutReloadTimestamp'] = 0;
}
});
I used a timestamp rather than a boolean, just in case the code is interrupted before having a chance to reinit the value stored before changing route. The risk of collision between tabs is very low.
Is there any downside of leveraging mousedown
listener to modify the href
attribute with a new URL location and then let the browser figures out where it should redirect to?
It's working fine so far for me. Would like to know what the limitations are with this approach?
// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';
a.onmousedown = () => {
a.href = '/lol';
};
document.body.appendChild(a);
}
double a = 1.000001;
double b = 0.000001;
System.out.println( a.compareTo(b) );
Returns:
-1 : 'a' is numerically less than 'b'.
0 : 'a' is equal to 'b'.
1 : 'a' is greater than 'b'.
Data Coercion does not necessarily mean weakly typed because sometimes its syntacical sugar:
The example above of Java being weakly typed because of
String s = "abc" + 123;
Is not weakly typed example because its really doing:
String s = "abc" + new Integer(123).toString()
Data coercion is also not weakly typed if you are constructing a new object. Java is a very bad example of weakly typed (and any language that has good reflection will most likely not be weakly typed). Because the runtime of the language always knows what the type is (the exception might be native types).
This is unlike C. C is the one of the best examples of weakly typed. The runtime has no idea if 4 bytes is an integer, a struct, a pointer or a 4 characters.
The runtime of the language really defines whether or not its weakly typed otherwise its really just opinion.
EDIT: After further thought this is not necessarily true as the runtime does not have to have all the types reified in the runtime system to be a Strongly Typed system. Haskell and ML have such complete static analysis that they can potential ommit type information from the runtime.
suprised this doesn't have an answer using pathilib which was introduced in python 3.4
+
additionally, shutil updated in python 3.6
to accept a pathlib object more details in this PEP-0519
from pathlib import Path
src_path = '\tmp\files_to_move'
for each_file in Path(src_path).glob('*.*'): # grabs all files
trg_path = each_file.parent.parent # gets the parent of the folder
each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
from pathlib import Path
import shutil
src_path = '\tmp\files_to_move'
trg_path = '\tmp'
for src_file in Path(src_path).glob('*.*'):
shutil.copy(src_file, trg_path)
You can simply replace all \n
with <br/>
tag so that when page is displayed then it breaks line.
UPDATE table SET field = REPLACE(field, '\n', '<br/>')
Place your third party libraries in a separate repository and use submodules to associate them with the main project. Here is a walk-through:
http://git-scm.com/book/en/Git-Tools-Submodules
In deciding how to segment a repo I would usually decide based on how often I would modify them. If it is a third-party library and only changes you are making to it is upgrading to a newer version then you should definitely separate it from the main project.
CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.
You could use:
DELETE FROM tableName
where your_date_column < '2009-01-01';
but Keep in mind that the above is really
DELETE FROM tableName
where your_date_column < '2009-01-01 00:00:00';
Not
DELETE FROM tableName
where your_date_column < '2009-01-01 11:59';
Although the DATEADD
is probably the most transparrent way of doing this, it is worth noting
that simply getdate()-30
will also suffice.
Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:
SELECT *
FROM Results
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
The MultiByteToWideChar
answer that Charles Bailey gave is the correct one. Because LPCWSTR
is just a typedef for const WCHAR*
, widestr
in the example code there can be used wherever a LPWSTR
is expected or where a LPCWSTR
is expected.
One minor tweak would be to use std::vector<WCHAR>
instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring
instead of std::string
. If you want to work with the Windows TCHAR
type, you can use std::basic_string<TCHAR>
. Converting from std::wstring
to LPCWSTR
or from std::basic_string<TCHAR>
to LPCTSTR
is just a matter of calling c_str
. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar
(and its inverse WideCharToMultiByte
) comes into the picture.
Alternative: Check out the code in SVN to some folder
This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
strings.Find(s => s == "hello");
This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
private static bool FindHello(String s)
{
return s == "hello";
}
strings.Find(FindHello);
EDIT:
In C# 2.0, this could be done using the anonymous delegate syntax:
strings.Find(delegate(String s) { return s == "hello"; });
Lambda's significantly cleaned up that syntax.
It means assign the key to $user and the variable to $pass
When you assign an array, you do it like this
$array = array("key" => "value");
It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
According to the PHP Manual, the '=>' created key/value pairs.
Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.
And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:
$array = array("test" => "foo");
foreach($array as $key => $value)
{
echo $key . " : " . $value; // Echoes "test : foo"
}
foreach($array as $value)
{
echo $value; // Echoes "foo"
}
One thing to check that I just found is that it won't work if there are multiple elements with the same ID. It doesn't error if you try to do this, it just fails silently
You can execute commands in parallel with start
like this:
start "" ping myserver
start "" nslookup myserver
start "" morecommands
They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.
Hope this helps!
After you install the Android SDK in Eclipse
, it generates a debug signing certificate for you in a keystore called debug.keystore. The Eclipse plug-in uses this certificate to sign each application build that is generated.
Now, the problem with this debug certificate is that it is only valid for a year, or 365 days. If your Eclipse IDE uses an expired debug certificate, you will not be able to create and/or deploy an Android app
.
To fix this problem all you need to do is delete the debug.keystore file.
Go to Preferences
Android
Build
Default debug keystore
There you should see the folder where the file is located. Simply delete that file and you are good to go.
For more info. you can visit
http://developer.android.com/tools/publishing/app-signing.html
I had the same issue. I was using the "Power save mode", which prevents from compiling incrementally and showing compilation errors.
You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery
$('#toggle').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#sendNewSms').removeAttr('disabled'); //enable input
} else {
$('#sendNewSms').attr('disabled', true); //disable input
}
});