How do I add an "Add to Favorites" button or link on my website?
Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon
Trying to make some order:
it all works - all but the firefox bookmarking function.
for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.
The problem is that it takes its values from the calling <a ..>
tag: title as the bookmark name and href as the bookmark address.
so this is my code:
javascript:
$("#bookmarkme").click(function () {
var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
var name = "Snir's Homepage";
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
alert("In order to bookmark go to the homepage and press "
+ (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ?
'Command/Cmd' : 'CTRL') + "+D.")
}
else if (window.sidebar) { // Mozilla Firefox Bookmark
//important for firefox to add bookmarks - remember to check out the checkbox on the popup
$(this).attr('rel', 'sidebar');
//set the appropriate attributes
$(this).attr('href', url);
$(this).attr('title', name);
//add bookmark:
// window.sidebar.addPanel(name, url, '');
// window.sidebar.addPanel(url, name, '');
window.sidebar.addPanel('', '', '');
}
else if (window.external) { // IE Favorite
window.external.addFavorite(url, name);
}
return;
});
html:
<a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>
In internet explorer there is a different between 'addFavorite':
<a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a>
and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>
.
example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html
Important, in chrome we can't add bookmarks using js (aspnet-i):
http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf
PostgreSQL: How to change PostgreSQL user password?
TLDR:
On many systems, a user's account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.
Example:
ALTER USER "username.lastname" WITH PASSWORD 'password';
Rational:
Postgres is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically when providing a string you would use a single quote.
What is ROWS UNBOUNDED PRECEDING used for in Teradata?
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an
ending row.
Starting and ending rows might be fixed or relative to the
current row based on the following keywords:
- CURRENT ROW, the current row
- UNBOUNDED PRECEDING, all rows before the current row -> fixed
- UNBOUNDED FOLLOWING, all rows after the current row -> fixed
- x PRECEDING, x rows before the current row -> relative
- y FOLLOWING, y rows after the current row -> relative
Possible kinds of calculation include:
- Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
- One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
- Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
Example: Communication between Activity and Service using Messaging
Great tutorial, fantastic presentation. Neat, simple, short and very explanatory.
Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
method is no more. As trante stated here, good approach would be:
private static final int NOTIFICATION_ID = 45349;
private void showNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
Intent targetIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
_nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
_nManager.notify(NOTIFICATION_ID, builder.build());
}
@Override
public void onDestroy() {
super.onDestroy();
if (_timer != null) {_timer.cancel();}
_counter=0;
_nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
Log.i("PlaybackService", "Service Stopped.");
_isRunning = false;
}
Checked myself, everything works like a charm (activity and service names may differ from original).
How to use a link to call JavaScript?
Unobtrusive JavaScript, no library dependency:
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
</head>
<body>
<a id="mylink" href="http://www.google.com">linky</a>
</body>
</html>
Function stoi not declared
stoi
is a C++11 function. If you aren't using a compiler that understands C++11, this simply won't compile.
You can use a stringstream
instead to read the input:
stringstream ss(hours0);
ss >> hours;
How to merge rows in a column into one cell in excel?
For those who have Excel 2016 (and I suppose next versions), there is now directly the CONCAT function, which will replace the CONCATENATE function.
So the correct way to do it in Excel 2016 is :
=CONCAT(A1:A4)
which will produce :
Iamaboy
For users of olders versions of Excel, the other answers are relevant.
How to clear Route Caching on server: Laravel 5.2.37
For your case solution is :
php artisan cache:clear
php artisan route:cache
Optimizing Route Loading is a must on production :
If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:
php artisan route:cache
This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
Since this feature uses PHP serialization, you may only cache the
routes for applications that exclusively use controller based routes.
PHP is not able to serialize Closures.
Laravel 5 clear cache from route, view, config and all cache data from application
I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.
Reoptimized class loader:
php artisan optimize
Clear Cache facade value:
php artisan cache:clear
Clear Route cache:
php artisan route:cache
Clear View cache:
php artisan view:clear
Clear Config cache:
php artisan config:cache
Try/catch does not seem to have an effect
If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.
try {
$ErrorActionPreference = "Stop"; #Make all errors terminating
get-item filethatdoesntexist; # normally non-terminating
write-host "You won't hit me";
} catch{
Write-Host "Caught the exception";
Write-Host $Error[0].Exception;
}finally{
$ErrorActionPreference = "Continue"; #Reset the error action pref to default
}
Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.
function log([System.String] $text){write-host $text;}
function logException{
log "Logging current exception.";
log $Error[0].Exception;
}
function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
[System.Management.Automation.ScriptBlock] $catch,
[System.Management.Automation.ScriptBlock] $finally = $({})){
# Make all errors terminating exceptions.
$ErrorActionPreference = "Stop";
# Set the trap
trap [System.Exception]{
# Log the exception.
logException;
# Execute the catch statement
& $catch;
# Execute the finally statement
& $finally
# There was an exception, return false
return $false;
}
# Execute the scriptblock
& $try;
# Execute the finally statement
& $finally
# The following statement was hit.. so there were no errors with the scriptblock
return $true;
}
#execute your own try catch
mytrycatch {
gi filethatdoesnotexist; #normally non-terminating
write-host "You won't hit me."
} {
Write-Host "Caught the exception";
}
Android view pager with page indicator
You Can create a Linear layout containing an array of TextView (mDots).
To represent the textView as Dots provide this HTML source in your code .
refer my code .
I got this information from Youtube Channel TVAC Studio .
here the code : `
addDotsIndicator(0);
viewPager.addOnPageChangeListener(viewListener);
}
public void addDotsIndicator(int position)
{
mDots = new TextView[5];
mDotLayout.removeAllViews();
for (int i = 0; i<mDots.length ; i++)
{
mDots[i]=new TextView(this);
mDots[i].setText(Html.fromHtml("•")); //HTML for dots
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorAccent));
mDotLayout.addView(mDots[i]);
}
if(mDots.length>0)
{
mDots[position].setTextColor(getResources().getColor(R.color.orange));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
addDotsIndicator(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
};`
Create a custom View by inflating a layout?
Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.
What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.
http://developer.android.com/guide/topics/ui/custom-components.html
How do I write the 'cd' command in a makefile?
Like this:
target:
$(shell cd ....); \
# ... commands execution in this directory
# ... no need to go back (using "cd -" or so)
# ... next target will be automatically in prev dir
Good luck!
Among $_REQUEST, $_GET and $_POST which one is the fastest?
I only ever use _GET or _POST. I prefer to have control.
What I don't like about either code fragment in the OP is that they discard the information on which HTTP method was used. And that information is important for input sanitization.
For example, if a script accepts data from a form that's going to be entered into the DB then the form had better use POST (use GET only for idempotent actions). But if the script receives the input data via the GET method then it should (normally) be rejected. For me, such a situation might warrant writing a security violation to the error log since it's a sign somebody is trying something on.
With either code fragment in the OP, this sanitization wouldn't be possible.
java: use StringBuilder to insert at the beginning
Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder
How to Select a substring in Oracle SQL up to a specific character?
You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.
1 select 'ABC_blahblahblah' test_string,
2 instr('ABC_blahblahblah','_',1,1) position_underscore,
3 substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
4* from dual
SQL> /
TEST_STRING POSITION_UNDERSCORE RES
---------------- ------------------ ---
ABC_blahblahblah 4 ABC
Instr documentation
Susbtr Documentation
#pragma mark in Swift?
For those who are interested in using extensions vs pragma marks (as mentioned in the first comment), here is how to implement it from a Swift Engineer:
import UIKit
class SwiftTableViewController: UITableViewController {
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension SwiftTableViewController {
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView?.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell;
cell.textLabel.text = "Hello World"
return cell
}
}
It's also not necessarily the best practice, but this is how you do it if you like.
How To Check If A Key in **kwargs Exists?
You want
if 'errormessage' in kwargs:
print("found it")
To get the value of errormessage
if 'errormessage' in kwargs:
print("errormessage equals " + kwargs.get("errormessage"))
In this way, kwargs
is just another dict
. Your first example, if kwargs['errormessage']
, means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError
.
Your second example, if errormessage in kwargs:
, means "if kwargs
contains the element named by "errormessage
", and unless "errormessage
" is the name of a variable, you'll get a NameError
.
I should mention that dictionaries also have a method .get()
which accepts a default parameter (itself defaulting to None
), so that kwargs.get("errormessage")
returns the value if that key exists and None
otherwise (similarly kwargs.get("errormessage", 17)
does what you might think it does). When you don't care about the difference between the key existing and having None
as a value or the key not existing, this can be handy.
Map with Key as String and Value as List in Groovy
Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:
// Java syntax
Map<String,List> map1 = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1);
assert map1.get("abc") == list1;
// slightly less Java-esque
def map2 = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2
// typical Groovy
def map3 = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3
How to measure time elapsed on Javascript?
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
Python: Converting from ISO-8859-1/latin1 to UTF-8
For Python 3:
bytes(apple,'iso-8859-1').decode('utf-8')
I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.
How to prevent errno 32 broken pipe?
This might be because you are using two method for inserting data into database and this cause the site to slow down.
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email).save() <====
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
In above function, the error is where arrow is pointing. The correct implementation is below:
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
Eclipse error "Could not find or load main class"
I ran into this error today because I set up a hello world program and then cut and pasted a new program into the same file. To fix the problem of not finding hello world as the last was called I clicked Run-> Run Configurations and then under Main Class I clicked search and it found my new class name and replaced it with the correct new name in the text that I pasted. This is a newbie problem I know but it is also easy to fix. I hope this helps someone!
Douglas
C++ class forward declaration
In order for new T
to compile, T
must be a complete type. In your case, when you say new tile_tree_apple
inside the definition of tile_tree::tick
, tile_tree_apple
is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.
Something like:
class A
{
void f1();
void f2();
};
class B
{
void f3();
void f4();
};
inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}
When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!
JPA Query selecting only specific columns without using Criteria Query?
Projections
can be used to select only specific properties(columns) of an entity object.
From the docs
Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.
Define an interface with only the getters
you want.
interface CustomObject {
String getA(); // Actual property name is A
String getB(); // Actual property name is B
}
Now return CustomObject
from your repository like so :
public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
CustomObject findByObjectName(String name);
}
URLEncoder not able to translate space character
Am I using the wrong method? What is the correct method I should be using?
Yes, this method java.net.URLEncoder.encode wasn't made for converting " " to "20%" according to spec (source).
The space character " " is converted into a plus sign "+".
Even this is not the correct method, you can modify this to: System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));
have a nice day =).
Using :before CSS pseudo element to add image to modal
Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I'm not sure what you're doing to figure out if this carrot needs to be added or not, but you should get the overall idea:
$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");
How do you setLayoutParams() for an ImageView?
Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
Put text at bottom of div
Thanks @Harry the following code works for me:
.your-div{
vertical-align: bottom;
display: table-cell;
}
How to extract table as text from the PDF using Python?
If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py
with
import camelot
tables = camelot.read_pdf('foo.pdf')
You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.
tables.export('foo.csv', f='csv', compress=False)
Edit: tabula-py
appears roughly 6 times faster than camelot-py
so that should be used instead.
import camelot
import cProfile
import pstats
import tabula
cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt
cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt
print(time_tabula, time_camelot, time_camelot/time_tabula)
gave
1.8495559890000015 11.057014036000016 5.978199147125147
How to link to a <div> on another page?
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
Set Font Color, Font Face and Font Size in PHPExcel
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
animating addClass/removeClass with jQuery
Although, the question is fairly old, I'm adding info not present in other answers.
The OP is using stop() to stop the current animation as soon as the event completes. However, using the right mix of parameters with the function should help. eg. stop(true,true) or stop(true,false) as this affects the queued animations well.
The following link illustrates a demo that shows the different parameters available with stop() and how they differ from finish().
http://api.jquery.com/finish/
Although the OP had no issues using JqueryUI, this is for other users who may come across similar scenarios but cannot use JqueryUI/need to support IE7 and 8 too.
django change default runserver port
Create enviroment variable in your .bashrc
export RUNSERVER_PORT=8010
Create alias
alias runserver='django-admin runserver $RUNSERVER_PORT'
Im using zsh and virtualenvs wrapper. I put export in projects postactivate script and asign port for every project.
workon someproject
runserver
use std::fill to populate vector with increasing numbers
I've seen the answers with std::generate but you can also "improve" that by using static variables inside the lambda, instead of declaring a counter outside of the function or creating a generator class :
std::vector<int> vec;
std::generate(vec.begin(), vec.end(), [] {
static int i = 0;
return i++;
});
I find it a little more concise
Using custom fonts using CSS?
there's also an interesting tool called CUFON. There's a demonstration of how to use it in this blog
It's really simple and interesting. Also, it doesn't allow people to ctrl+c/ctrl+v the generated content.
redirect to current page in ASP.Net
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
QtCreator: No valid kits found
Though OP is asking about Windows, this error also occurs on Ubuntu Linux and Google lists this result first when you search for the error"QtCreator: No valid kits found".
On Ubuntu this is solved by running:
For Qt5:
sudo apt-get install qt5-default
For Qt4:
sudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui
This question is answered here and here, though those entries are less SEO-friendly...
Should try...catch go inside or outside a loop?
Performance: as Jeffrey said in his reply, in Java it doesn't make much difference.
Generally, for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not.
In your example you returned upon catching an exception. In that case, I'd put the try/catch around the loop. If you simply want to catch a bad value but carry on processing, put it inside.
The third way: You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop. Making the exception handling isolated to the loop itself!
class Parsing
{
public static Float MyParseFloat(string inputValue)
{
try
{
return Float.parseFloat(inputValue);
}
catch ( NumberFormatException e )
{
return null;
}
}
// .... your code
for(int i = 0; i < max; i++)
{
String myString = ...;
Float myNum = Parsing.MyParseFloat(myString);
if ( myNum == null ) return;
myFloats[i] = (float) myNum;
}
}
How to make a HTTP PUT request?
protected void UpdateButton_Click(object sender, EventArgs e)
{
var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
var bytes = Encoding.ASCII.GetBytes(values);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
UpdateResponseLabel.Text = "Update completed";
else
UpdateResponseLabel.Text = "Error in update";
}
Get current AUTO_INCREMENT value for any table
You can get all of the table data by using this query:
SHOW TABLE STATUS FROM `DatabaseName` WHERE `name` LIKE 'TableName' ;
You can get exactly this information by using this query:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
OPTION (RECOMPILE) is Always Faster; Why?
To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,
- Table Variables.
When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.
How to get Locale from its String representation in Java?
This answer may be a little late, but it turns out that parsing out the string is not as ugly as the OP assumed. I found it quite simple and concise:
public static Locale fromString(String locale) {
String parts[] = locale.split("_", -1);
if (parts.length == 1) return new Locale(parts[0]);
else if (parts.length == 2
|| (parts.length == 3 && parts[2].startsWith("#")))
return new Locale(parts[0], parts[1]);
else return new Locale(parts[0], parts[1], parts[2]);
}
I tested this (on Java 7) with all the examples given in the Locale.toString() documentation: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "zh_CN_#Hans", "zh_TW_#Hant-x-java", and "th_TH_TH_#u-nu-thai".
IMPORTANT UPDATE: This is not recommended for use in Java 7+ according to the documentation:
In particular, clients who parse the output of toString into language, country, and variant fields can continue to do so (although this is strongly discouraged), although the variant field will have additional information in it if script or extensions are present.
Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.
How do you implement a good profanity filter?
If you can do something like Digg/Stackoverflow where the users can downvote/mark obscene content... do so.
Then all you need to do is review the "naughty" users, and block them if they break the rules.
Iterating through a list to render multiple widgets in Flutter?
Basically when you hit 'return' on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a children of a widget
you can do something like this:
Widget getTextWidgets(List<String> strings)
{
List<Widget> list = new List<Widget>();
for(var i = 0; i < strings.length; i++){
list.add(new Text(strings[i]));
}
return new Row(children: list);
}
or even better, you can use .map() operator and do something like this:
Widget getTextWidgets(List<String> strings)
{
return new Row(children: strings.map((item) => new Text(item)).toList());
}
Select query to get data from SQL Server
SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
SqlCommand.ExecuteScalar Method
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
So to get no. of statements returned by SELECT statement you have to use ExecuteScalar method.
Reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
So try below code:
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
command.Parameters.AddWithValue("@zip","india");
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
}
}
conn.Close();
Calculating average of an array list?
Use a double for the sum, otherwise you are doing an integer division and you won't get any decimals:
private double calculateAverage(List <Integer> marks) {
if (marks == null || marks.isEmpty()) {
return 0;
}
double sum = 0;
for (Integer mark : marks) {
sum += mark;
}
return sum / marks.size();
}
or using the Java 8 stream API:
return marks.stream().mapToInt(i -> i).average().orElse(0);
How do I ignore files in Subversion?
SVN ignore
is easy to manage in TortoiseSVN. Open TortoiseSVN and right-click on file menu then select Add to ignore list.
This will add the files in the svn:ignore
property.
When we checking in the files then those file which is matched with svn:ignore
that will be ignored and will not commit.
In Visual Studio project we have added following files to ignore:
bin obj
*.exe
*.dll
*.pdb
*.suo
We are managing source code on SVN of Comparetrap using this method successfully
Returning JSON object from an ASP.NET page
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
CSS values using HTML5 data attribute
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
Changing element style attribute dynamically using JavaScript
It's almost correct.
Since the -
is a javascript operator, you can't really have that in property names. If you were setting, border
or something single-worded like that instead, your code would work just fine.
However, the thing you need to remember for padding-top
, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop
.
There are some other exceptions. JavaScript has some reserved words, so you can't set float
like that, for instance. Instead, in some browsers you need to use cssFloat
and in others styleFloat
. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...
Disable browser 'Save Password' functionality
I haven't had any issues using this method:
Use autocomplete="off", add a hidden password field and then another non-hidden one. The browser tries to auto complete the hidden one if it doesn't respect autocomplete="off"
How to add Drop-Down list (<select>) programmatically?
This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.
_x000D_
_x000D_
var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];_x000D_
_x000D_
var sEle = document.createElement('select');_x000D_
document.getElementsByTagName('body')[0].appendChild(sEle);_x000D_
_x000D_
for (var i = 0; i < array.length; ++i) {_x000D_
var oEle = document.createElement('option');_x000D_
_x000D_
if (i == 0) {_x000D_
oEle.setAttribute('disabled', 'disabled');_x000D_
oEle.setAttribute('selected', 'selected');_x000D_
} // end of if loop_x000D_
_x000D_
var oTxt = document.createTextNode(array[i]);_x000D_
oEle.appendChild(oTxt);_x000D_
_x000D_
document.getElementsByTagName('select')[0].appendChild(oEle);_x000D_
} // end of for loop
_x000D_
_x000D_
_x000D_
Is it safe to expose Firebase apiKey to the public?
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable.
Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase.
Go to https://console.developers.google.com/apis
and perfrom a security steup.
Test if number is odd or even
I did a bit of testing, and found that between mod, is_int
and the &
-operator, mod is the fastest, followed closely by the &-operator.
is_int
is nearly 4 times slower than mod.
I used the following code for testing purposes:
$number = 13;
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = ($number%2?true:false);
}
$after = microtime(true);
echo $after-$before." seconds mod<br>";
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = (!is_int($number/2)?true:false);
}
$after = microtime(true);
echo $after-$before." seconds is_int<br>";
$before = microtime(true);
for ($i=0; $i<100000; $i++) {
$test = ($number&1?true:false);
}
$after = microtime(true);
echo $after-$before." seconds & operator<br>";
The results I got were pretty consistent. Here's a sample:
0.041879177093506 seconds mod
0.15969395637512 seconds is_int
0.044223070144653 seconds & operator
A warning - comparison between signed and unsigned integer expressions
The primary issue is that underlying hardware, the CPU, only has instructions to compare two signed values or compare two unsigned values. If you pass the unsigned comparison instruction a signed, negative value, it will treat it as a large positive number. So, -1, the bit pattern with all bits on (twos complement), becomes the maximum unsigned value for the same number of bits.
8-bits: -1 signed is the same bits as 255 unsigned
16-bits: -1 signed is the same bits as 65535 unsigned
etc.
So, if you have the following code:
int fd;
fd = open( .... );
int cnt;
SomeType buf;
cnt = read( fd, &buf, sizeof(buf) );
if( cnt < sizeof(buf) ) {
perror("read error");
}
you will find that if the read(2) call fails due to the file descriptor becoming invalid (or some other error), that cnt will be set to -1. When comparing to sizeof(buf), an unsigned value, the if() statement will be false because 0xffffffff is not less than sizeof() some (reasonable, not concocted to be max size) data structure.
Thus, you have to write the above if, to remove the signed/unsigned warning as:
if( cnt < 0 || (size_t)cnt < sizeof(buf) ) {
perror("read error");
}
This just speaks loudly to the problems.
1. Introduction of size_t and other datatypes was crafted to mostly work,
not engineered, with language changes, to be explicitly robust and
fool proof.
2. Overall, C/C++ data types should just be signed, as Java correctly
implemented.
If you have values so large that you can't find a signed value type that works, you are using too small of a processor or too large of a magnitude of values in your language of choice. If, like with money, every digit counts, there are systems to use in most languages which provide you infinite digits of precision. C/C++ just doesn't do this well, and you have to be very explicit about everything around types as mentioned in many of the other answers here.
When should I use a List vs a LinkedList
My previous answer was not enough accurate.
As truly it was horrible :D
But now I can post much more useful and correct answer.
I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: https://github.com/ukushu/DataStructuresTestsAndOther.git
Short results:
Array need to use:
- So often as possible. It's fast and takes smallest RAM range for same amount information.
- If you know exact count of cells needed
- If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
- If needed high Random Access speed
List need to use:
- If needed to add cells to the end of list (often)
- If needed to add cells in the beginning/middle of the list (NOT OFTEN)
- If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
- If needed high Random Access speed
LinkedList need to use:
- If needed to add cells in the beginning/middle/end of the list (often)
- If needed only sequential access (forward/backward)
- If you need to save LARGE items, but items count is low.
- Better do not use for large amount of items, as it's use additional memory for links.
More details:
Interesting to know:
LinkedList<T>
internally is not a List in .NET. It's even does not implement IList<T>
. And that's why there are absent indexes and methods related to indexes.
LinkedList<T>
is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for LinkedList<T>
than for List<T>
or Array.
List<T>
in .Net is Java's alternative of ArrayList<T>
. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size < 85000 bytes -- this provides a very compact and fast-access representation in memory.
Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
String strip() for JavaScript?
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.
Send POST parameters with MultipartFormData using Alamofire, in iOS Swift
For Swift 4.2 / Alamofire 4.7.3
Alamofire.upload(multipartFormData: { multipart in
multipart.append(fileData, withName: "payload", fileName: "someFile.jpg", mimeType: "image/jpeg")
multipart.append("comment".data(using: .utf8)!, withName :"comment")
}, to: "endPointURL", method: .post, headers: nil) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { answer in
print("statusCode: \(answer.response?.statusCode)")
}
upload.uploadProgress { progress in
//call progress callback here if you need it
}
case .failure(let encodingError):
print("multipart upload encodingError: \(encodingError)")
}
}
Also you could take a look at CodyFire lib it makes API calls easier using Codable for everything.
Example for Multipart call using CodyFire
//Declare your multipart payload model
struct MyPayload: MultipartPayload {
var attachment: Attachment //or you could use just Data instead
var comment: String
}
// Prepare payload for request
let imageAttachment = Attachment(data: UIImage(named: "cat")!.jpeg(.high)!,
fileName: "cat.jpg",
mimeType: .jpg)
let payload = MyPayload(attachment: imageAttachment, comment: "Some text")
//Send request easily
APIRequest("endpoint", payload: payload)
.method(.post)
.desiredStatus(.created) //201 CREATED
.onError { error in
switch error.code {
case .notFound: print("Not found")
default: print("Another error: " + error.description)
}
}.onSuccess { result in
print("here is your decoded result")
}
//Btw normally it should be wrapped into an extension
//so it should look even easier API.some.upload(payload).onError{}.onSuccess{}
You could take a look at all the examples in lib's readme
Use of 'prototype' vs. 'this' in JavaScript?
I believe that @Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new
, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { this._instance_var = v; },
x: function() { alert(this._instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
Writing binary number system in C code
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
Iterating over JSON object in C#
This worked for me, converts to nested JSON to easy to read YAML
string JSONDeserialized {get; set;}
public int indentLevel;
private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
{
bool bSuccess = false;
indentLevel++;
foreach (string strKey in dict.Keys)
{
string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
JSONDeserialized+="\r\n" + strOutput;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
JSONDeserialized += strOutput + ",";
}
else if (oChild is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)oChild);
JSONDeserialized += "\r\n";
}
}
}
else
{
strOutput = o.ToString();
JSONDeserialized += strOutput;
}
}
indentLevel--;
return bSuccess;
}
usage
Dictionary<string, object> JSONDic = new Dictionary<string, object>();
JavaScriptSerializer js = new JavaScriptSerializer();
try {
JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
JSONDeserialized = "";
indentLevel = 0;
DisplayDictionary(JSONDic);
return JSONDeserialized;
}
catch (Exception)
{
return "Could not parse input JSON string";
}
Create a tar.xz in one command
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
- tar.gz and tar.xz are not the same; xz provides better compression.
- Don't use pipe
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.
Intellij reformat on file save
I set it to automatically clean up on check-in, which is usually good enough for me. If something is too ugly, I'll just hit the shortcut (Ctrl-Alt-L, Return). And I see they have an option for auto-formatting pasted code, although I've never used that.
Interview Question: Merge two sorted singly linked lists without creating new nodes
Iteration can be done as below. Complexity = O(n)
public static LLNode mergeSortedListIteration(LLNode nodeA, LLNode nodeB) {
LLNode mergedNode ;
LLNode tempNode ;
if (nodeA == null) {
return nodeB;
}
if (nodeB == null) {
return nodeA;
}
if ( nodeA.getData() < nodeB.getData())
{
mergedNode = nodeA;
nodeA = nodeA.getNext();
}
else
{
mergedNode = nodeB;
nodeB = nodeB.getNext();
}
tempNode = mergedNode;
while (nodeA != null && nodeB != null)
{
if ( nodeA.getData() < nodeB.getData())
{
mergedNode.setNext(nodeA);
nodeA = nodeA.getNext();
}
else
{
mergedNode.setNext(nodeB);
nodeB = nodeB.getNext();
}
mergedNode = mergedNode.getNext();
}
if (nodeA != null)
{
mergedNode.setNext(nodeA);
}
if (nodeB != null)
{
mergedNode.setNext(nodeB);
}
return tempNode;
}
Sticky Header after scrolling down
Here is a JS fiddle http://jsfiddle.net/ke9kW/1/
As the others say, set the header to fixed, and start it with display: none
then jQuery
$(window).scroll(function () {
if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
$('header').addClass('open');
$('header').slideDown();
} else if ( $(this).scrollTop() <= 200 ) {
$('header').removeClass('open');
$('header').slideUp();
}
});
where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory
Force index use in Oracle
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
MetadataException when using Entity Framework Entity Connection
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
Execute another jar in a Java program
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
@echo off
start /min C:\path\to\jarprogram.jar
Why is it string.join(list) instead of list.join(string)?
It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.
For example:
'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'
Using something other than strings will raise the following error:
TypeError: sequence item 0: expected str instance, int found
How to checkout in Git by date?
To keep your current changes
You can keep your work stashed away, without commiting it, with git stash
. You
would than use git stash pop
to get it back. Or you can (as carleeto said) git commit
it to a separate branch.
Checkout by date using rev-parse
You can checkout a commit by a specific date using rev-parse
like this:
git checkout 'master@{1979-02-26 18:30:00}'
More details on the available options can be found in the git-rev-parse
.
As noted in the comments this method uses the reflog to find the commit in your history. By default these entries expire after 90 days. Although the syntax for using the reflog is less verbose you can only go back 90 days.
Checkout out by date using rev-list
The other option, which doesn't use the reflog, is to use rev-list
to get the commit at a particular point in time with:
git checkout `git rev-list -n 1 --first-parent --before="2009-07-27 13:37" master`
Note the --first-parent if you want only your history and not versions brought in by a merge. That's what you usually want.
Calling a Function defined inside another function in Javascript
The scoping is correct as you've noted. However, you are not calling the inner
function anywhere.
You can do either:
function outer() {
// when you define it this way, the inner function will be accessible only from
// inside the outer function
function inner() {
alert("hi");
}
inner(); // call it
}
Or
function outer() {
this.inner = function() {
alert("hi");
}
}
<input type="button" onclick="(new outer()).inner();" value="ACTION">?
Passing multiple parameters with $.ajax url
Why are you combining GET and POST? Use one or the other.
$.ajax({
type: 'post',
data: {
timestamp: timestamp,
uid: uid
...
}
});
php:
$uid =$_POST['uid'];
Or, just format your request properly (you're missing the ampersands for the get parameters).
url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
Bootstrap modal: is not a function
I added a modal dialog in jsp and tried to open it with javascript in jsx and hit the same error: "...modal is not a function"
In my case, simply by adding the missing import to the jsx solved the problem.
`import "./../bower/bootstrap/js/modal.js"; // or import ".../bootstrap.min.js"`
LINQ Orderby Descending Query
Just to show it in a different format that I prefer to use for some reason:
The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
How to update maven repository in Eclipse?
If Maven update snapshot doesn't work and if you have Spring Tooling, one interesting way is to remove
- Right-click on your project then Maven > Disable Maven Nature
- Right-click on your project then Spring Tools > Update Maven Dependencies
- After "BUILD SUCCESS", Right-click on your project then Configure > Convert Maven Project
Note: Maven update snapshot sometimes stops working if you use anything else i.e. eclipse:eclipse or Spring Tooling
How to remove files that are listed in the .gitignore but still on the repository?
I can't say it's an appropriate solution but you can try this.
Steps
- I am hoping that you have already cloned your repo.
- Now copy the file somewhere outside of your project.
- Add that filename with a location in gitigonre file.
- Remove that file from your local project.
- Push your code to remote origin.
- And now add that copied file into your project it'll be ignored.
This is just a hack solution if you want to maintain the history and don't to create mass in it.
If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side
How to set the JDK Netbeans runs on?
I had this message too because today i decided to relocate my different jdk in the same directory. I have decided to uninstall all through program manager of window. After that, of course i had the message below.
"Cannot locate java installation in specified jdkhome C:\Program Files (x86)\Java\jdk1.7.0_60 Do you want to try to use default version ?"
A new install of the jdk does not resolve the problem. Ok you can configure that in menu Tool > java platforms but in my case i had to fix my netbeans.conf
i had the line below
netbeans_jdkhome="C:\Program Files\Java\jdk1.7.0_60"
and i replace it by
netbeans_jdkhome="C:\devtools\Java\jdk1.8.0_25"
how to fix java.lang.IndexOutOfBoundsException
This error happens because your list lstpp
is empty (Nothing at index 0). So either there is a bug in your getResult()
function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).
Rails migration for change column
Just generate migration:
rails g migration change_column_to_new_from_table_name
Update migration like this:
class ClassName < ActiveRecord::Migration
change_table :table_name do |table|
table.change :column_name, :data_type
end
end
and finally
rake db:migrate
Creating Accordion Table with Bootstrap
For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified this example to do so here: http://jsfiddle.net/QLfMU/116/
How to create a bash script to check the SSH connection?
I feel like you're trying to solve the wrong problem here. Shouldn't you be trying to make the ssh daemons more stable? Try running something like monit, which will check to see if the daemon is running and restart it if it isn't (giving you time to find the root problem behind sshd shutting down on you). Or is the network service troublesome? Try looking at man ifup
. Does the Whole Damn Thing just like to shut down on you? Well, that's a bigger problem ... try looking at your logs (start with syslog) to find hardware failures or services that are shutting your boxen down (maybe a temperature monitor?).
Making your scripts fault tolerant is great, but you might also want to make your boxen fault tolerant.
How to loop through key/value object in Javascript?
Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty()
method. This is generally a good idea when using for...in
loops:
var user = {};
function setUsers(data) {
for (var k in data) {
if (data.hasOwnProperty(k)) {
user[k] = data[k];
}
}
}
Cannot set property 'display' of undefined
I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.
In this code we add multiple styles in an element:
_x000D_
_x000D_
let_x000D_
element = document.querySelector('span')_x000D_
, cssStyle = (el, styles) => {_x000D_
for (var property in styles) {_x000D_
el.style[property] = styles[property];_x000D_
}_x000D_
}_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_
Flutter plugin not installed error;. When running flutter doctor
If you are using VSCode then navigate to extensions and search for flutter.Then simply install it and must take care that you have already installed dart there and after that if it doesn't work then copy your flutter bin path that you can locate at C/'flutter-SDK-path'/bin.then copy it and add it to environment variable and add it to that path so,you can easily be able to access flutter.I hope it works.
If you are using Android Studio then may already stated article help you.
And make sure that you have latest versions of SDKs and Android Studio or VSCode.so that versions can't introduce any error.
Hope it work.
How to save password when using Subversion from the console
I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config
does not help to store the password.
The password was successfully saved after removing this folder (just in case renaming):
%USERPROFILE%\AppData\Roaming\Subversion\auth
Environment:
Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.
How to get the changes on a branch in Git
What you want to see is the list of outgoing commits. You can do this using
git log master..branchName
or
git log master..branchName --oneline
Where I assume that "branchName" was created as a tracking branch of "master".
Similarly, to see the incoming changes you can use:
git log branchName..master
Map enum in JPA with fixed values?
I would do the folowing:
Declare separetly the enum, in it´s own file:
public enum RightEnum {
READ(100), WRITE(200), EDITOR (300);
private int value;
private RightEnum (int value) { this.value = value; }
@Override
public static Etapa valueOf(Integer value){
for( RightEnum r : RightEnum .values() ){
if ( r.getValue().equals(value))
return r;
}
return null;//or throw exception
}
public int getValue() { return value; }
}
Declare a new JPA entity named Right
@Entity
public class Right{
@Id
private Integer id;
//FIElDS
// constructor
public Right(RightEnum rightEnum){
this.id = rightEnum.getValue();
}
public Right getInstance(RightEnum rightEnum){
return new Right(rightEnum);
}
}
You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)
import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
*
*
*/
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{
@Override //this method shoudn´t be used, but I implemented anyway, just in case
public Integer convertToDatabaseColumn(RightEnum attribute) {
return attribute.getValue();
}
@Override
public RightEnum convertToEntityAttribute(Integer dbData) {
return RightEnum.valueOf(dbData);
}
}
The Authority entity:
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
// the **Entity** to map :
private Right right;
// the **Enum** to map (not to be persisted or updated) :
@Column(name="COLUMN1", insertable = false, updatable = false)
@Convert(converter = RightEnumConverter.class)
private RightEnum rightEnum;
}
By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using
autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example
And if you need to compare, you can use:
authority.getRight().equals( RightEnum.READ ); //for example
Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.
However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).
Let´s see.
The RightEnum:
public enum RightEnum {
READ(100), WRITE(200), EDITOR (300);
private int value;
private RightEnum (int value) {
try {
this.value= value;
final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
field.setAccessible(true);
field.set(this, value);
} catch (Exception e) {//or use more multicatch if you use JDK 1.7+
throw new RuntimeException(e);
}
}
@Override
public static Etapa valueOf(Integer value){
for( RightEnum r : RightEnum .values() ){
if ( r.getValue().equals(value))
return r;
}
return null;//or throw exception
}
public int getValue() { return value; }
}
and the Authority entity
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
// the **Enum** to map (to be persisted or updated) :
@Column(name="COLUMN1")
@Enumerated(EnumType.ORDINAL)
private RightEnum rightEnum;
}
In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.
I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.
Save PL/pgSQL output from PostgreSQL to a CSV file
I had to use the \COPY because I received the error message:
ERROR: could not open file "/filepath/places.csv" for writing: Permission denied
So I used:
\Copy (Select address, zip From manjadata) To '/filepath/places.csv' With CSV;
and it is functioning
MySQL WHERE: how to write "!=" or "not equals"?
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
Python division
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example:
Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Change key pair for ec2 instance
Alternate solution. If you have the only access on server. In that case don't remove pem file from AWS console. Just remove pem access key from sudo nano ~/.ssh/authroized_keys
and add your system public ssh key. Now you have the access ssh [email protected]
How to get sp_executesql result into a variable?
Here's something you can try
DECLARE @SqlStatement NVARCHAR(MAX) = ''
,@result XML
,@DatabaseName VARCHAR(100)
,@SchemaName VARCHAR(10)
,@ObjectName VARCHAR(200);
SELECT @DatabaseName = 'some database'
,@SchemaName = 'some schema'
,@ObjectName = 'some object (Table/View)'
SET @SqlStatement = '
SELECT @result = CONVERT(XML,
STUFF( ( SELECT *
FROM
(
SELECT TOP(100)
*
FROM ' + QUOTENAME(@DatabaseName) +'.'+ QUOTENAME(@SchemaName) +'.' + QUOTENAME(@ObjectName) + '
) AS A1
FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
), 1, 0, '''')
)
';
EXEC sp_executesql @SqlStatement,N'@result XML OUTPUT', @result = @result OUTPUT;
SELECT DISTINCT
QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM @result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName
Using GregorianCalendar with SimpleDateFormat
SimpleDateFormat.format()
method takes a Date
as a parameter. You can get a Date
from a Calendar
by calling its getTime()
method:
public static String format(GregorianCalendar calendar) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
fmt.setCalendar(calendar);
String dateFormatted = fmt.format(calendar.getTime());
return dateFormatted;
}
Also note that the months start at 0, so you probably meant:
int month = Integer.parseInt(splitDate[1]) - 1;
Get random boolean in Java
You can use the following for an unbiased result:
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!
If you want to give more probability to your result to be true (or false) you can adjust the above as following!
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
Check if space is in a string
There are a lot of ways to do that :
t = s.split(" ")
if len(t) > 1:
print "several tokens"
To be sure it matches every kind of space, you can use re module :
import re
if re.search(r"\s", your_string):
print "several words"
react native get TextInput value
User in the init of class:
constructor() {
super()
this.state = {
email: ''
}
}
Then in some function:
handleSome = () => {
console.log(this.state.email)
};
And in the input:
<TextInput onChangeText={(email) => this.setState({email})}/>
pull out p-values and r-squared from a linear regression
r-squared: You can return the r-squared value directly from the summary object summary(fit)$r.squared
. See names(summary(fit))
for a list of all the items you can extract directly.
Model p-value: If you want to obtain the p-value of the overall regression model,
this blog post outlines a function to return the p-value:
lmp <- function (modelobject) {
if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
f <- summary(modelobject)$fstatistic
p <- pf(f[1],f[2],f[3],lower.tail=F)
attributes(p) <- NULL
return(p)
}
> lmp(fit)
[1] 1.622665e-05
In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same.
Coefficient p-values: If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:
summary(fit)$coefficients[,4]
Alternatively, you can grab the p-value of coefficients from the anova(fit)
object in a similar fashion to the summary object above.
Error inflating when extending a class
in my case I added such cyclic resource:
<drawable name="above_shadow">@drawable/above_shadow</drawable>
then changed to
<drawable name="some_name">@drawable/other_name</drawable>
and it worked
CodeIgniter -> Get current URL relative to base url
I don't know if there is such a function, but with $this->uri->uri_to_assoc() you get an associative array from the $_GET parameters.
With this, and the controller you are in, you know how the URL looks like.
In you above URL this would mean you would be in the controller dropbox and the array would be something like this:
array("derrek" => "shopredux", "ahahaha" => "hihihi");
With this you should be able to make such a function on your own.
BASH Syntax error near unexpected token 'done'
There's a way you can get this problem without having mixed newline problems (at least, in my shell, which is GNU bash v4.3.30):
#!/bin/bash
# foo.sh
function foo() {
echo "I am quoting a thing `$1' inside a function."
}
while [ "$input" != "y" ]; do
read -p "Hit `y' to continue: " -n 1 input
echo
done
foo "What could possibly go wrong?"
$ ./foo.sh
./foo.sh: line 11: syntax error near unexpected token `done'
./foo.sh: line 11: `done'
This is because bash expands backticks inside double-quoted strings (see the bash manual on quoting and command substitution), and before finding a matching backtick, will interpret any additional double quotes as part of the command substitution:
$ echo "Command substitution happens inside double-quoted strings: `ls`"
Command substitution happens inside double-quoted strings: foo.sh
$ echo "..even with double quotes: `grep -E "^foo|wrong" foo.sh`"
..even with double quotes: foo "What could possibly go wrong?"
You can get around this by escaping the backticks in your string with a backslash, or by using a single-quoted string.
I'm not really sure why this only gives the one error message, but I think it has to do with the function definition:
#!/bin/bash
# a.sh
function a() {
echo "Thing's `quoted'"
}
a
while true; do
echo "Other `quote'"
done
#!/bin/bash
# b.sh
echo "Thing's `quoted'"
while true; do
echo "Other `quote'"
done
$ ./a.sh
./a.sh: line 10: syntax error near unexpected token `done'
./a.sh: line 10: `done'
$ ./b.sh
./b.sh: command substitution: line 6: unexpected EOF while looking for matching `''
./b.sh: command substitution: line 9: syntax error: unexpected end of file
Thing's quote'
./b.sh: line 7: syntax error near unexpected token `done'
./b.sh: line 7: `done'
CSS-moving text from left to right
I am not sure if this is the correct solution but I have achieved this
by redefining .marquee class just after animation CSS.
Check below:
<style>
#marquee-wrapper{
width:700px;
display:block;
border:1px solid red;
}
div.marquee{
width:100px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s;
-moz-animation:myfirst 5s; /* Firefox */
}
@-moz-keyframes myfirst /* Firefox */{
0% {background:red; left:0px; top:0px;}
100% {background:red; left:100%; top:0px}
}
div.marquee{
left:700px; top:0px
}
</style>
<!-- HTMl COde -->
<p><b>Note:</b> This example does not work in Internet Explorer and Opera.</p>
<div id="marquee-wrapper">
<div class="marquee"></div>
Flask Download a File
You need to make sure that the value you pass to the directory
argument is an absolute path, corrected for the current location of your application.
The best way to do this is to configure UPLOAD_FOLDER
as a relative path (no leading slash), then make it absolute by prepending current_app.root_path
:
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
return send_from_directory(directory=uploads, filename=filename)
It is important to reiterate that UPLOAD_FOLDER
must be relative for this to work, e.g. not start with a /
.
A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.
Understanding the set() function
Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.
Here's an example of a set changing order after a lot of values are added and then removed:
>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
s.remove(v)
>>> print(s)
{1, 6, 8}
This is implementation dependent though, and so you should not rely upon it.
Read all contacts' phone numbers in android
Code to get contact name (Ascending order) and number
For more reference: show contact in listview
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
React Native Responsive Font Size
import { Dimensions } from 'react-native';
const { width, fontScale } = Dimensions.get("window");
const styles = StyleSheet.create({
fontSize: idleFontSize / fontScale,
});
fontScale
get scale as per your device.
Convert php array to Javascript
For a multidimensional array in PHP4 you can use the following addition to the code posted by Udo G:
function js_str($s) {
return '"'.addcslashes($s, "\0..\37\"\\").'"';
}
function js_array($array, $keys_array) {
foreach ($array as $key => $value) {
$new_keys_array = $keys_array;
$new_keys_array[] = $key;
if(is_array($value)) {
echo 'javascript_array';
foreach($new_keys_array as $key) {
echo '["'.$key.'"]';
}
echo ' = new Array();';
js_array($value, $new_keys_array);
} else {
echo 'javascript_array';
foreach($new_keys_array as $key) {
echo '["'.$key.'"]';
}
echo ' = '.js_str($value).";";
}
}
}
echo 'var javascript_array = new Array();';
js_array($php_array, array());
System.Runtime.InteropServices.COMException (0x800A03EC)
Try this as it worked for me...
- Go to "Start" -> "Run" and enter "dcomcnfg"
- This will bring up the component services window, expand out "Console Root" -> "Computers" -> "DCOM Config"
- Find "Microsoft Excel Application" in the list of components.
- Right click on the entry and select "Properties"
- Go to the "Identity" tab on the properties dialog.
- Select "The interactive user."
courtesy of Last paragraph mentioned in here
Only on Firefox "Loading failed for the <script> with source"
Today I ran into the exact same problem while working on a progressive web app (PWA) page and deleting some cache and service worker data for that page from Firefox. The dev console reported that none of the 4 Javascript files on the page would load anymore. The problem persisted in Safe mode, so it was not an add-on issue. The same script files loaded fine from other web pages on the same website. No amount of clearing the Firefox cache or wiping web page data from Firefox would help, nor would rebooting the Windows 10 PC. Chrome all the time worked fine on the problem page. In the end I did a restore of the entire Firefox profile folder from a day-old backup, and the problem was immediately gone, so it was not a problem with my PWA app. Apparently something in Firefox got corrupted.
Swift 3: Display Image from URL
let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")
self.myactivityindecator.startAnimating()
let urlString = url
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url)
{
(data, response, error) in
if error != nil {
print("Failed fetching image:", error!)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("error")
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)
let myimageview = UIImageView(image: image)
print(myimageview)
self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()
}
}.resume()
Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?
The other clean solution if you don't want to pop all stack entries...
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_container, fragmentInstance).addToBackStack(null).commit();
This will clean the stack first and then load a new fragment, so at any given point you'll have only single fragment in stack
What is the difference between .NET Core and .NET Standard Class Library project types?
When should we use one over the other?
The decision is a trade-off between compatibility and API access.
Use a .NET Standard library when you want to increase the number of applications that will be compatible with your library, and you are okay with a decrease in the .NET API surface area your library can access.
Use a .NET Core library when you want to increase the .NET API surface area your library can access, and you are okay with allowing only .NET Core applications to be compatible with your library.
For example, a library that targets .NET Standard 1.3 will be compatible with applications that target .NET Framework 4.6, .NET Core 1.0, Universal Windows Platform 10.0, and any other platform that supports .NET Standard 1.3. The library will not have access to some parts of the .NET API, though. For instance, the Microsoft.NETCore.CoreCLR
package is compatible with .NET Core, but not with .NET Standard.
What is the difference between Class Library (.NET Standard) and Class Library (.NET Core)?
Compatibility: Libraries that target .NET Standard will run on any .NET Standard compliant runtime, such as .NET Core, .NET Framework, Mono/Xamarin. On the other hand, libraries that target .NET Core can only run on the .NET Core runtime.
API Surface Area: .NET Standard libraries come with everything in NETStandard.Library
, whereas .NET Core libraries come with everything in Microsoft.NETCore.App
. The latter includes approximately 20 additional libraries, some of which we can add manually to our .NET Standard library (such as System.Threading.Thread
) and some of which are not compatible with the .NET Standard (such as Microsoft.NETCore.CoreCLR
).
Also, .NET Core libraries specify a runtime and come with an application model. That's important, for instance, to make unit test class libraries runnable.
Why do both exist?
Ignoring libraries for a moment, the reason that .NET Standard exists is for portability; it defines a set of APIs that .NET platforms agree to implement. Any platform that implements a .NET Standard is compatible with libraries that target that .NET Standard. One of those compatible platforms is .NET Core.
Coming back to libraries, the .NET Standard library templates exist to run on multiple runtimes (at the expense of API surface area). Conversely, the .NET Core library templates exist to access more API surface area (at the expense of compatibility) and to specify a platform against which to build an executable.
Here is an interactive matrix that shows which .NET Standard supports which .NET implementation(s) and how much API surface area is available.
instanceof Vs getClass( )
Do you want to match a class exactly, e.g. only matching FileInputStream
instead of any subclass of FileInputStream
? If so, use getClass()
and ==
. I would typically do this in an equals
, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.
Otherwise, use instanceof
. Note that with getClass()
you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException
, whereas instanceof
will just return false
if the first operand is null.
Personally I'd say instanceof
is more idiomatic - but using either of them extensively is a design smell in most cases.
Get records with max value for each group of grouped SQL results
My solution works only if you need retrieve only one column, however for my needs was the best solution found in terms of performance (it use only one single query!):
SELECT SUBSTRING_INDEX(GROUP_CONCAT(column_x ORDER BY column_y),',',1) AS xyz,
column_z
FROM table_name
GROUP BY column_z;
It use GROUP_CONCAT in order to create an ordered concat list and then I substring to only the first one.
How to handle back button in activity
This is a simple way of doing something.
@Override
public void onBackPressed() {
// do what you want to do when the "back" button is pressed.
startActivity(new Intent(Activity.this, MainActivity.class));
finish();
}
I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.
How to set or change the default Java (JDK) version on OS X?
First find out where do you store the environment variables-
- emacs
- bash_profile
- zshrc file
Steps to Set up the environment variable :-
Download the jdk from JAVA
install it by double click
Now set-up environment variables in your file
a. For emacs.profile you can use this link OR see the screenshot below
b. For ZSH profile setup -
1. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
2. source ~/.zshrc - Restart zshrc to reflect the changes.
3. echo $JAVA_HOME - make sure path is set up properly
----> /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
4. java -version
--> java version "1.8.0_112" Java(TM) SE Runtime Environment (build 1.8.0_112-b16)Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)
All set Now you can easily upgrade or degrade the JAVA version..
Encoding as Base64 in Java
Google Guava is another choice to encode and decode Base64 data:
POM configuration:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<type>jar</type>
<version>14.0.1</version>
</dependency>
Sample code:
String inputContent = "Hello Vi?t Nam";
String base64String = BaseEncoding.base64().encode(inputContent.getBytes("UTF-8"));
// Decode
System.out.println("Base64:" + base64String); // SGVsbG8gVmnhu4d0IE5hbQ==
byte[] contentInBytes = BaseEncoding.base64().decode(base64String);
System.out.println("Source content: " + new String(contentInBytes, "UTF-8")); // Hello Vi?t Nam
Image.open() cannot identify image file - Python?
In my case.. I already had "from PIL import Image" in my code.
The error occurred for me because the image file was still in use (locked) by a previous operation in my code. I had to add a small delay or attempt to open the file in append mode in a loop, until that did not fail. Once that did not fail, it meant the file was no longer in use and I could continue and let PIL open the file. Here are the functions I used to check if the file is in use and wait for it to be available.
def is_locked(filepath):
locked = None
file_object = None
if os.path.exists(filepath):
try:
buffer_size = 8
# Opening file in append mode and read the first 8 characters.
file_object = open(filepath, 'a', buffer_size)
if file_object:
locked = False
except IOError as message:
locked = True
finally:
if file_object:
file_object.close()
return locked
def wait_for_file(filepath):
wait_time = 1
while is_locked(filepath):
time.sleep(wait_time)
Correct way to initialize empty slice
The two alternative you gave are semantically identical, but using make([]int, 0)
will result in an internal call to runtime.makeslice (Go 1.14).
You also have the option to leave it with a nil
value:
var myslice []int
As written in the Golang.org blog:
a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.
A nil
slice will however json.Marshal()
into "null"
whereas an empty slice will marshal into "[]"
, as pointed out by @farwayer.
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
Forward request headers from nginx proxy server
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
How to make a rest post call from ReactJS code?
you can install superagent
npm install superagent --save
then for make post call to server
import request from "../../node_modules/superagent/superagent";
request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});
How do I use Maven through a proxy?
For details of setting up a proxy for Maven, see the mini guide.
Essentially you need to ensure the proxies section in either the global settings ([maven install]/conf/settings.xml
), or user settings (${user.home}/.m2/settings.xml
) is configured correctly. It is better to do this in your user settings to avoid storing the password in plain text in a public location.
Maven 2.1 introduced password encryption, but I've not got round to checking if the encryption applies for the proxy settings as well as repository passwords (don't see why it wouldn't though).
For info, there is a commented-out proxy configuration in your settings.xml and instructions on how to modify it.
From the mini-guide, your settings should look something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
[...]
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
[...]
</settings>
Random numbers with Math.random() in Java
A better approach is:
int x = rand.nextInt(max - min + 1) + min;
Your formula generates numbers between min
and min + max
.
Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
int x = (int)(Math.random() * max) + min;
System.out.println(x);
if (x < min || x >= max) { break; }
}
Result:
10
16
13
21 // Oops!!
See it online here: ideone
Get content uri from file path in android
You can use these two ways based on use
Uri uri = Uri.parse("String file location");
or
Uri uri = Uri.fromFile(new File("string file location"));
I have tried both ways and both works.
Playing HTML5 video on fullscreen in android webview
Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView
will get it working on API level 21+
if (Build.VERSION.SDK_INT >= 21) {
videoViewContainer.setBackgroundColor(Color.BLACK);
((ViewGroup) webView.getParent()).addView(videoViewContainer);
webView.scrollTo(0,0); // centers full screen view
} else {
activityNonVideoView.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
activityVideoView.addView(videoViewContainer,vg);
activityVideoView.setVisibility(View.VISIBLE);
}
You will also need to reflect the changes in onHideCustomView
QString to char* conversion
Maybe
my_qstring.toStdString().c_str();
or safer, as Federico points out:
std::string str = my_qstring.toStdString();
const char* p = str.c_str();
It's far from optimal, but will do the work.
How to get request url in a jQuery $.get/ajax request
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
proper way to sudo over ssh
Another way is to use the -t
switch to ssh
:
ssh -t user@server "sudo script"
See man ssh
:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary screen-based programs on a remote machine, which can be
very useful, e.g., when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
What is the difference between XAMPP or WAMP Server & IIS?
WAMP is an acronym for Windows (OS), Apache (web-server), MySQL (database), PHP (language).
XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. There are also other WAMPs such as UniformServer. And there are commercial WAMPs such as WampDeveloper (what I use).
Their differences are in the format/structure of the package, the configurations, and the included management applications.
IIS is a web-server application just like Apache is, except it's made by Microsoft and is Windows only (Apache runs on both Windows and Linux). IIS is also more geared towards using ASP.NET (vs. PHP) and "SQL Server" (vs. MySQL), though it can use PHP and MySQL too.
Escape invalid XML characters in C#
As the way to remove invalid XML characters I suggest you to use XmlConvert.IsXmlChar method. It was added since .NET Framework 4 and is presented in Silverlight too. Here is the small sample:
void Main() {
string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
content = RemoveInvalidXmlChars(content);
Console.WriteLine(IsValidXmlString(content)); // True
}
static string RemoveInvalidXmlChars(string text) {
var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();
return new string(validXmlChars);
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
And as the way to escape invalid XML characters I suggest you to use XmlConvert.EncodeName method. Here is the small sample:
void Main() {
const string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
string encoded = XmlConvert.EncodeName(content);
Console.WriteLine(IsValidXmlString(encoded)); // True
string decoded = XmlConvert.DecodeName(encoded);
Console.WriteLine(content == decoded); // True
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
Update:
It should be mentioned that the encoding operation produces a string with a length which is greater or equal than a length of a source string. It might be important when you store a encoded string in a database in a string column with length limitation and validate source string length in your app to fit data column limitation.
How can I change the version of npm using nvm?
Changing npm versions on linux based OSs isn't a straight forward one command process yet. I have done following to switch back to older version of npm. This should work to get any version of npm working. First install the version of npm you want to use:
sudo npm install -g [email protected]
Remove the sym link in /usr/local/bin/
sudo rm /usr/local/bin/npm
Recreate the sym link using the desired version of npm you have installed
sudo ln -s /usr/bin/[email protected] /usr/local/bin/npm
Show pop-ups the most elegant way
- Create a 'popup' directive and apply it to the container of the popup content
- In the directive, wrap the content in a absolute position div along with the mask div below it.
- It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
- Create and bind a boolean flag to controller. This flag will control visibility.
- Create scope variables that bond to OK / Cancel functions etc.
Editing to add a high level example (non functional)
<div id='popup1-content' popup='showPopup1'>
....
....
</div>
<div id='popup2-content' popup='showPopup2'>
....
....
</div>
.directive('popup', function() {
var p = {
link : function(scope, iElement, iAttrs){
//code to wrap the div (iElement) with a abs pos div (parentDiv)
// code to add a mask layer div behind
// if the parent is already there, then skip adding it again.
//use jquery ui to make it dragable etc.
scope.watch(showPopup, function(newVal, oldVal){
if(newVal === true){
$(parentDiv).show();
}
else{
$(parentDiv).hide();
}
});
}
}
return p;
});
Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type
Two solutions:
1- if the type of the target column is [nvarchar] it should be change to [varchar]
2- Add a "Derived Column" component to the SSIS package and add a new column with the following expression:
(DT_WSTR, «length») [ColumnName]
Length is the length of the column in the target table and ColumnName is the name of the column in the target table.
finally at the mapping part you should use this new added column instead of the original column.
How to change language of app when user selects language?
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.locale = locale;
preferences.setLocalePref(langCode);
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState)
in onCreate
.