setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error
In your Activity.java
import android.support.v7.widget.Toolbar
instead of android.widget.Toolbar
:
import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
public class rutaActivity extends AppCompactActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ruta);
getSupportActionBar().hide();//Ocultar ActivityBar anterior
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar); //NO PROBLEM !!!!
Update:
If you are using androidx, replace
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
with newer imports
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
remove all special characters in java
Your problem is that the indices returned by match.start()
correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c
every time, these indices become incorrect.
The best approach to solve this is to use replaceAll
, for example:
System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));
How to get the cell value by column name not by index in GridView in asp.net
Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.
public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
{
for (int i = 0; i < gridView.Columns.Count ; i++)
{
if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
{
return i;
}
}
return -1;
}
What are the differences among grep, awk & sed?
Short definition:
grep
: search for specific terms in a file
#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"
$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"
Now awk
and sed
are completly different than grep
.
awk
and sed
are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).
awk
is mostly used for data extraction and reporting. sed
is a stream editor
Each one of them has its own functionality and specialties.
Example
Sed
$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'
Awk
$ awk '{print $2}' file.txt
# this will print the second column of file.txt
Basic awk
usage:
Compute sum/average/max/min/etc. what ever you may need.
$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average: 30
I recommend that you read this book: Sed & Awk: 2nd Ed.
It will help you become a proficient sed/awk user on any unix-like environment.
Purpose of __repr__ method?
This is explained quite well in the Python documentation:
repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__()
method.
So what you're seeing here is the default implementation of __repr__
, which is useful for serialization and debugging.
Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?
Found these docu on the google docu pages:
- row --- int --- top row of the range
- column --- int--- leftmost column of the range
- optNumRows --- int --- number of rows in the range.
- optNumColumns --- int --- number of columns in the range
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns();
Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
IF - ELSE IF - ELSE Structure in Excel
Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:
=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))
Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?
In case you have to keep PYTHONPATH for both python2 and python3, you can write alias statements to set the proper PYTHONPATH in your bash_profile:
Hardcode your PYTHONPATH2, and PYTHONPATH3 variables in your ~/.bash_profile, and add the following aliases at the end of it:
alias python='export PYTHONPATH=${PYTHONPATH2};python'
alias python3='export PYTHONPATH=${PYTHONPATH3};python3'
My python
(refers to python2) as I use python2 more often.
Scrolling a div with jQuery
There's a plug-in for this if you don't want to write a bare-bones implementation yourself. It's called "scrollTo" (link). It allows you to perform programmed scrolling to certain points, or use values like -= 10px
for continuous scrolling.
ScrollTo jQuery Plug-in
Removing time from a Date object?
The correct class to use for a date without time of day is LocalDate
. LocalDate
is a part of java.time, the modern Java date and time API.
So the best thing you can do is if you can modify the getStartDate
method you are using to return a LocalDate
:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("en-IE"));
LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
String dateString = d.format(dateFormatter);
System.out.println(dateString);
Example output:
21/03/2012
If you cannot change the getStartDate
, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date
that you get (I assume java.util.Date
):
d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
LocalDate dateWithoutTime = d.toInstant()
.atZone(ZoneId.of("Asia/Kolkata"))
.toLocalDate();
Please insert the time zone that was assumed for the Date
. You may use ZoneId.systemDefault()
for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.
The java.util.Date
class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date
, Calendar
, SimpleDateFormat
and DateFormat
. Recognizing that they were poorly designed. Furthermore, a Date
despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).
Link: Oracle tutorial: Date Time explaining how to use java.time
.
Javascript close alert box
As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.
How do I refresh the page in ASP.NET? (Let it reload itself by code)
The only correct way that I could do page refresh was through JavaScript, many of top .NET answers failed for me.
Response.Write("<script type='text/javascript'> setTimeout('location.reload(true); ', timeout);</script>");
Put the above code in button click event or anywhere you want to force page refresh.
Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>
The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
Unit testing with Spring Security
You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).
cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.
It could work like following:
public class MyUserDetails implements UserDetails {
// this is your custom UserDetails implementation to serve as a principal
// implement the Spring methods and add your own methods as appropriate
}
public class MyUserHolder {
public static MyUserDetails getUserDetails() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
return (MyUserDetails) a.getPrincipal();
}
}
}
public class MyUserAwareController {
MyUserDetails currentUser;
public void setCurrentUser(MyUserDetails currentUser) {
this.currentUser = currentUser;
}
// controller code
}
Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:
<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="controller" class="MyUserAwareController">
<property name="currentUser" ref="userDetails"/>
<!-- other props -->
</bean>
Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:
protected void setUp() {
// existing init code
MyUserDetails user = new MyUserDetails();
// set up user as you wish
controller.setCurrentUser(user);
}
Hope this helps!
HTML text-overflow ellipsis detection
The e.offsetWidth < e.scrollWidth
solution is not always working.
And if you want to use pure JavaScript, I recommend to use this:
(typescript)
public isEllipsisActive(element: HTMLElement): boolean {
element.style.overflow = 'initial';
const noEllipsisWidth = element.offsetWidth;
element.style.overflow = 'hidden';
const ellipsisWidth = element.offsetWidth;
if (ellipsisWidth < noEllipsisWidth) {
return true;
} else {
return false;
}
}
Comparing strings by their alphabetical order
Take a look at the String.compareTo
method.
s1.compareTo(s2)
From the javadocs:
The result is a negative integer if
this String object lexicographically
precedes the argument string. The
result is a positive integer if this
String object lexicographically
follows the argument string. The
result is zero if the strings are
equal; compareTo returns 0 exactly
when the equals(Object) method would
return true.
javascript close current window
Works only in Google Chrome with self.close();
. Tested in v48.
window.close()
won't do what you want as the documentation for it clearly states that scripts may close only the windows that were opened by it.
100% height minus header?
If your browser supports CSS3, try using the CSS element Calc()
height: calc(100% - 65px);
you might also want to adding browser compatibility options:
height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */
also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622
Converting between datetime and Pandas Timestamp objects
You can use the to_pydatetime method to be more explicit:
In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)
In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)
It's also available on a DatetimeIndex:
In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')
In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
datetime.datetime(2011, 1, 11, 0, 0),
datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)
How to handle button clicks using the XML onClick within Fragments
Best solution IMHO:
in fragment:
protected void addClick(int id) {
try {
getView().findViewById(id).setOnClickListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onClick(View v) {
if (v.getId()==R.id.myButton) {
onMyButtonClick(v);
}
}
then in Fragment's onViewStateRestored:
addClick(R.id.myButton);
How to add a linked source folder in Android Studio?
Just in case anyone is interested, heres a complete Java module gradle file that correctly generates and references the built artefacts
within an Android multi module application
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "net.ltgt.gradle:gradle-apt-plugin:0.15"
}
}
apply plugin: "net.ltgt.apt"
apply plugin: "java-library"
apply plugin: "idea"
idea {
module {
sourceDirs += file("$buildDir/generated/source/apt/main")
testSourceDirs += file("$buildDir/generated/source/apt/test")
}
}
dependencies {
// Dagger 2 and Compiler
compile "com.google.dagger:dagger:2.15"
apt "com.google.dagger:dagger-compiler:2.15"
compile "com.google.guava:guava:24.1-jre"
}
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
SQL - Create view from multiple tables
Are you using MySQL
or PostgreSQL
?
You want to use JOIN syntax, not UNION. For example, using INNER JOIN:
CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)
However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).
UITableview: How to Disable Selection for Some Rows but Not Others
Use this to make the cell look like it is disabled and non-selectable:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Important: note that this is only a styling property, and does not actually disable the cell. In order to do that, you have to check for selectionStyle
in your didSelectRowAtIndexPath:
delegate implementation:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(cell.selectionStyle == UITableViewCellSelectionStyleNone) {
return;
}
// do your cell selection handling here
}
JVM option -Xss - What does it do exactly?
It indeed sets the stack size on a JVM.
You should touch it in either of these two situations:
- StackOverflowError (the stack size is greater than the limit), increase the value
- OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.
The latter usually comes when your Xss is set too large - then you need to balance it (testing!)
How do I read the source code of shell commands?
cd ~ && apt-get source coreutils && ls -d coreutils*
You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo
assuming your downloading to a location you own.
how to fire event on file select
<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>
onFileChange(e) {
//upload file and then delete it from input
self.$refs.inputFile.value = ''
}
What is the javascript filename naming convention?
The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.
As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).
So the answer, like so many, is "it depends" or "it's up to you."
The one rule you should follow is to be consistent in the convention you choose.
Resetting Select2 value in dropdown with reset button
Sometimes I want to reset Select2 but I can't without change() method. So my solution is :
function resetSelect2Wrapper(el, value){
$(el).val(value);
$(el).select2({
minimumResultsForSearch: -1,
language: "fr"
});
}
Using :
resetSelect2Wrapper("#mySelectId", "myValue");
Communicating between a fragment and an activity - best practices
I am using Intents to communicate actions back to the main activity. The main activity is listening to these by overriding onNewIntent(Intent intent). The main activity translates these actions to the corresponding fragments for example.
So you can do something like this:
public class MainActivity extends Activity {
public static final String INTENT_ACTION_SHOW_FOO = "show_foo";
public static final String INTENT_ACTION_SHOW_BAR = "show_bar";
@Override
protected void onNewIntent(Intent intent) {
routeIntent(intent);
}
private void routeIntent(Intent intent) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case INTENT_ACTION_SHOW_FOO:
// for example show the corresponding fragment
loadFragment(FooFragment);
break;
case INTENT_ACTION_SHOW_BAR:
loadFragment(BarFragment);
break;
}
}
}
Then inside any fragment to show the foo fragment:
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(INTENT_ACTION_SHOW_FOO);
// Prevent activity to be re-instantiated if it is already running.
// Instead, the onNewEvent() is triggered
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getContext().startActivity(intent);
MySQL the right syntax to use near '' at line 1 error
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
LINQ select in C# dictionary
One way would be to first flatten the list with a SelectMany
:
subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));
How to remove word wrap from textarea?
The following CSS based solution works for me:
<html>
<head>
<style type='text/css'>
textarea {
white-space: nowrap;
overflow: scroll;
overflow-y: hidden;
overflow-x: scroll;
overflow: -moz-scrollbars-horizontal;
}
</style>
</head>
<body>
<form>
<textarea>This is a long line of text for testing purposes...</textarea>
</form>
</body>
</html>
Finish an activity from another activity
That you can do, but I think you should not break the normal flow of activity. If you want to finish you activity then you can simply send a broadcast from your activity B to activity A.
Create a broadcast receiver before starting your activity B:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equals("finish_activity")) {
finish();
// DO WHATEVER YOU WANT.
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));
Send broadcast from activity B to activity A when you want to finish activity A from B
Intent intent = new Intent("finish_activity");
sendBroadcast(intent);
I hope it will work for you...
What is the point of WORKDIR on Dockerfile?
You can think of WORKDIR
like a cd
inside the container (it affects commands that come later in the Dockerfile, like the RUN
command). If you removed WORKDIR
in your example above, RUN npm install
wouldn't work because you would not be in the /usr/src/app
directory inside your container.
I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY
is a relative path, so if you move your Dockerfile you may need to update those COPY
commands.
Convert Java String to sql.Timestamp
You could use Timestamp.valueOf(String)
. The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...]
, so you might need to change the field separators in your incoming string.
Then again, if you're going to do that then you could just parse it yourself and use the setNanos
method to store the microseconds.
CodeIgniter: Load controller within controller
Just to add more information to what Zain Abbas said:
Load the controller that way, and use it like he said:
$this->load->library('../controllers/instructor');
$this->instructor->functioname();
Or you can create an object and use it this way:
$this->load->library('../controllers/your_controller');
$obj = new $this->your_controller();
$obj->your_function();
Hope this can help.
What's the maximum value for an int in PHP?
Ah I found it: 232 - 1 (2147483647)
http://au2.php.net/int
Integer overflow
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
<?php
$large_number = 2147483647;
var_dump($large_number);
// output: int(2147483647)
$large_number = 2147483648;
var_dump($large_number);
// output: float(2147483648)
What is float in Java?
In JAVA, values like:
- 8.5
- 3.9
- (and so on..)
Is assumed as double and not float.
You can also perform a cast in order to solve the problem:
float b = (float) 3.5
;
Another solution:
float b = 3.5f
;
What is ViewModel in MVC?
I didn't read all the posts but every answer seems to be missing one concept that really helped me "get it"...
If a Model is akin to a database Table, then a ViewModel is akin to a database View - A view typically either returns small amounts of data from one table, or, complex sets of data from multiple tables (joins).
I find myself using ViewModels to pass info into a view/form, and then transfering that data into a valid Model when the form posts back to the controller - also very handy for storing Lists(IEnumerable).
The application has stopped unexpectedly: How to Debug?
- From the Home screen, press the Menu key.
- List item
- Touch Settings.
- Touch Applications.
- Touch Manage Applications.
- Touch All.
- Select the application that is having issues.
- Touch Clear data and Clear cache if they are available. This resets the app as if it was new, and may delete personal data stored in the app.
Excel VBA Check if directory exists error
To be certain that a folder exists (and not a file) I use this function:
Public Function FolderExists(strFolderPath As String) As Boolean
On Error Resume Next
FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
On Error GoTo 0
End Function
It works both, with \
at the end and without.
How to get the input from the Tkinter Text Widget?
In order to obtain the string in a Text
widget one can simply use get
method defined for Text
which accepts 1 to 2 arguments as start
and end
positions of characters, text_widget_object.get(start, end=None)
. If only start
is passed and end
isn't passed it returns only the single character positioned at start
, if end
is passed as well, it returns all characters in between positions start
and end
as string.
There are also special strings, that are variables to the underlying Tk. One of them would be "end"
or tk.END
which represents the variable position of the very last char in the Text
widget. An example would be to returning all text in the widget, with text_widget_object.get('1.0', 'end')
or text_widget_object.get('1.0', 'end-1c')
if you don't want the last newline character.
Demo
See below demonstration that selects the characters in between the given positions with sliders:
try:
import tkinter as tk
except:
import Tkinter as tk
class Demo(tk.LabelFrame):
"""
A LabeFrame that in order to demonstrate the string returned by the
get method of Text widget, selects the characters in between the
given arguments that are set with Scales.
"""
def __init__(self, master, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self.start_arg = ''
self.end_arg = None
self.position_frames = dict()
self._create_widgets()
self._layout()
self.update()
def _create_widgets(self):
self._is_two_args = tk.Checkbutton(self,
text="Use 2 positional arguments...")
self.position_frames['start'] = PositionFrame(self,
text="start='{}.{}'.format(line, column)")
self.position_frames['end'] = PositionFrame( self,
text="end='{}.{}'.format(line, column)")
self.text = TextWithStats(self, wrap='none')
self._widget_configs()
def _widget_configs(self):
self.text.update_callback = self.update
self._is_two_args.var = tk.BooleanVar(self, value=False)
self._is_two_args.config(variable=self._is_two_args.var,
onvalue=True, offvalue=False)
self._is_two_args['command'] = self._is_two_args_handle
for _key in self.position_frames:
self.position_frames[_key].line.slider['command'] = self.update
self.position_frames[_key].column.slider['command'] = self.update
def _layout(self):
self._is_two_args.grid(sticky='nsw', row=0, column=1)
self.position_frames['start'].grid(sticky='nsew', row=1, column=0)
#self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
self.text.grid(sticky='nsew', row=2, column=0,
rowspan=2, columnspan=2)
_grid_size = self.grid_size()
for _col in range(_grid_size[0]):
self.grid_columnconfigure(_col, weight=1)
for _row in range(_grid_size[1] - 1):
self.grid_rowconfigure(_row + 1, weight=1)
def _is_two_args_handle(self):
self.update_arguments()
if self._is_two_args.var.get():
self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
else:
self.position_frames['end'].grid_remove()
def update(self, event=None):
"""
Updates slider limits, argument values, labels representing the
get method call.
"""
self.update_sliders()
self.update_arguments()
def update_sliders(self):
"""
Updates slider limits based on what's written in the text and
which line is selected.
"""
self._update_line_sliders()
self._update_column_sliders()
def _update_line_sliders(self):
if self.text.lines_length:
for _key in self.position_frames:
self.position_frames[_key].line.slider['state'] = 'normal'
self.position_frames[_key].line.slider['from_'] = 1
_no_of_lines = self.text.line_count
self.position_frames[_key].line.slider['to'] = _no_of_lines
else:
for _key in self.position_frames:
self.position_frames[_key].line.slider['state'] = 'disabled'
def _update_column_sliders(self):
if self.text.lines_length:
for _key in self.position_frames:
self.position_frames[_key].column.slider['state'] = 'normal'
self.position_frames[_key].column.slider['from_'] = 0
_line_no = int(self.position_frames[_key].line.slider.get())-1
_max_line_len = self.text.lines_length[_line_no]
self.position_frames[_key].column.slider['to'] = _max_line_len
else:
for _key in self.position_frames:
self.position_frames[_key].column.slider['state'] = 'disabled'
def update_arguments(self):
"""
Updates the values representing the arguments passed to the get
method, based on whether or not the 2nd positional argument is
active and the slider positions.
"""
_start_line_no = self.position_frames['start'].line.slider.get()
_start_col_no = self.position_frames['start'].column.slider.get()
self.start_arg = "{}.{}".format(_start_line_no, _start_col_no)
if self._is_two_args.var.get():
_end_line_no = self.position_frames['end'].line.slider.get()
_end_col_no = self.position_frames['end'].column.slider.get()
self.end_arg = "{}.{}".format(_end_line_no, _end_col_no)
else:
self.end_arg = None
self._update_method_labels()
self._select()
def _update_method_labels(self):
if self.end_arg:
for _key in self.position_frames:
_string = "text.get('{}', '{}')".format(
self.start_arg, self.end_arg)
self.position_frames[_key].label['text'] = _string
else:
_string = "text.get('{}')".format(self.start_arg)
self.position_frames['start'].label['text'] = _string
def _select(self):
self.text.focus_set()
self.text.tag_remove('sel', '1.0', 'end')
self.text.tag_add('sel', self.start_arg, self.end_arg)
if self.end_arg:
self.text.mark_set('insert', self.end_arg)
else:
self.text.mark_set('insert', self.start_arg)
class TextWithStats(tk.Text):
"""
Text widget that stores stats of its content:
self.line_count: the total number of lines
self.lines_length: the total number of characters per line
self.update_callback: can be set as the reference to the callback
to be called with each update
"""
def __init__(self, master, update_callback=None, *args, **kwargs):
tk.Text.__init__(self, master, *args, **kwargs)
self._events = ('<KeyPress>',
'<KeyRelease>',
'<ButtonRelease-1>',
'<ButtonRelease-2>',
'<ButtonRelease-3>',
'<Delete>',
'<<Cut>>',
'<<Paste>>',
'<<Undo>>',
'<<Redo>>')
self.line_count = None
self.lines_length = list()
self.update_callback = update_callback
self.update_stats()
self.bind_events_on_widget_to_callback( self._events,
self,
self.update_stats)
@staticmethod
def bind_events_on_widget_to_callback(events, widget, callback):
"""
Bind events on widget to callback.
"""
for _event in events:
widget.bind(_event, callback)
def update_stats(self, event=None):
"""
Update self.line_count, self.lines_length stats and call
self.update_callback.
"""
_string = self.get('1.0', 'end-1c')
_string_lines = _string.splitlines()
self.line_count = len(_string_lines)
del self.lines_length[:]
for _line in _string_lines:
self.lines_length.append(len(_line))
if self.update_callback:
self.update_callback()
class PositionFrame(tk.LabelFrame):
"""
A LabelFrame that has two LabelFrames which has Scales.
"""
def __init__(self, master, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._layout()
def _create_widgets(self):
self.line = SliderFrame(self, orient='vertical', text="line=")
self.column = SliderFrame(self, orient='horizontal', text="column=")
self.label = tk.Label(self, text="Label")
def _layout(self):
self.line.grid(sticky='ns', row=0, column=0, rowspan=2)
self.column.grid(sticky='ew', row=0, column=1, columnspan=2)
self.label.grid(sticky='nsew', row=1, column=1)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(1, weight=1)
class SliderFrame(tk.LabelFrame):
"""
A LabelFrame that encapsulates a Scale.
"""
def __init__(self, master, orient, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self.slider = tk.Scale(self, orient=orient)
self.slider.pack(fill='both', expand=True)
if __name__ == '__main__':
root = tk.Tk()
demo = Demo(root, text="text.get(start, end=None)")
with open(__file__) as f:
demo.text.insert('1.0', f.read())
demo.text.update_stats()
demo.pack(fill='both', expand=True)
root.mainloop()
How to unmount a busy device
Niche Answer:
If you have a zfs pool on that device, at least when it's a file-based pool, lsof
will not show the usage. But you can simply run
sudo zpool export mypoo
and then unmount.
How do I force git to use LF instead of CR+LF under windows?
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
Why is @font-face throwing a 404 error on woff files?
I tried a ton of things around permissions, mime types, etc, but for me it ended up being that the web.config had removed the Static file handler in IIS, and then explicitly added it back in for directories that would have static files. As soon as I added a location node for my directory and added the handler back, the requests stopped getting 404s.
Plot multiple lines in one graph
Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:
tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)
tab<-t(tab)
plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
Hibernate: "Field 'id' doesn't have a default value"
In my case,
I altered that offending tables and the field "id" in question I made it AUTO_INCREMENT, I still need to figure out why on deployment time it was not making it "AUTO_INCREMENT" so that I have to do it by myself!
LaTeX source code listing like in professional books
I am happy with the listings
package:
Here is how I configure it:
\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}
I use it like this:
\begin{lstlisting}[caption=Caption example.,
label=a_label,
float=t]
// Insert the code here
\end{lstlisting}
sh: 0: getcwd() failed: No such file or directory on cited drive
In my case nothing above has worked. After banging my head against the wall for a while I've found out, that I've destroyed the /etc/passwd
entries by running a custom-made-linux-server-setup-bash-script which worked well previously, but this time the regex within the "sed" command erased all the existing entries :D
After copy pasting the default entries from another working linux server I could finally restart sshd.
So don't forget to backup the original /etc/passwd
file before applying any regex replacements on it :)
How do I force my .NET application to run as administrator?
The detailed steps are as follow.
- Add application manifest file to solution
- Change application setting to "app.manifest"
- Update tag of "requestedExecutionLevel" to requireAdministrator.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
Table Height 100% inside Div element
Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!
How to echo xml file in php
You can use the asXML method
echo $xml->asXML();
You can also give it a filename
$xml->asXML('filename.xml');
How do I use CREATE OR REPLACE?
If you are doing in code then first check for table in database
by using query
SELECT table_name
FROM user_tables
WHERE table_name = 'XYZ'
if record found then truncate table otherwise create Table
Work like Create or Replace.
ggplot combining two plots from different data.frames
The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.
Like this:
ggplot() +
geom_line(data=Data1, aes(x=A, y=B), color='green') +
geom_line(data=Data2, aes(x=C, y=D), color='red')
instead of
ggplot(data=Data1, aes(x=A, y=B), color='green') +
geom_line() +
geom_line(data=Data2, aes(x=C, y=D), color='red')
More info here
Capture Video of Android's Screen
I guess screencast is no go cause of tegra 2 incompatibility, i already tried it,but no whey!
So i tried using Z-ScreeNRecorder from market,installed it on my LG Optimus 2x, but it record's only blank screen,i tried for 5min. and there i get 5min. of blank screen file of 6mb size... so there is no point trying until they release some peace of software that is compatible with tegra2 chipset!
Truncate string in Laravel blade templates
In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.
While in Laravel 7 up, you can use the Str::limit helper.
//For Laravel to Laravel 7
{{ Illuminate\Support\Str::limit($post->title, 20, $end='...') }}
How to create a batch file to run cmd as administrator
This Works for me in Windows 7 to 10 with parameters, when kick starting app or file from anywhere (including browser) and also when accessing file from anywhere. Replace (YOUR BATCH SCRIPT HERE anchor) with your code. This solution May Help :)
@echo off
call :isAdmin
if %errorlevel% == 0 (
goto :run
) else (
echo Requesting administrative privileges...
goto :UACPrompt
)
exit /b
:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b
:run
<YOUR BATCH SCRIPT HERE>
exit /b
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
I keep getting "Uncaught SyntaxError: Unexpected token o"
I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.
I was accessing the iframe data like this:
$('#load-file-iframe').contents().text()
which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to
$('#load-file-iframe').contents().find('body').text()
once I noticed some garbage in the HTML response.
Long story short check your raw HTML response data and you might turn something up.
How do I convert from int to Long in Java?
I have this little toy, that also deals with non generic interfaces.
I'm OK with it throwing a ClassCastException if feed wrong (OK and happy)
public class TypeUtil {
public static long castToLong(Object o) {
Number n = (Number) o;
return n.longValue();
}
}
How to sort a file in-place
You can use file redirection to redirected the sorted output:
sort input-file > output_file
Or you can use the -o
, --output=FILE
option of sort to indicate the same input and output file:
sort -o file file
Without repeating the filename (with bash brace expansion)
sort -o file{,}
?? Note: A common mistake is to try to redirect the output to the same input file
(e.g. sort file > file
). This does not work as the shell is making the redirections (not the sort(1) program) and the input file (as being the output also) will be erased just before giving the sort(1) program the opportunity of reading it.
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
I too faced the same problem in Angular 6. I solved the issue by using below code. Add the code in component.ts file.
import { HttpHeaders } from '@angular/common/http';
headers;
constructor() {
this.headers = new HttpHeaders();
this.headers.append('Access-Control-Allow-Headers', 'Authorization');
}
getData() {
this.http.get(url,this.headers). subscribe (res => {
// your code here...
})}
How to extract custom header value in Web API message handler?
To further expand on @neontapir's solution, here's a more generic solution that can apply to HttpRequestMessage or HttpResponseMessage equally and doesn't require hand coded expressions or functions.
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
public static class HttpResponseMessageExtensions
{
public static T GetFirstHeaderValueOrDefault<T>(
this HttpResponseMessage response,
string headerKey)
{
var toReturn = default(T);
IEnumerable<string> headerValues;
if (response.Content.Headers.TryGetValues(headerKey, out headerValues))
{
var valueString = headerValues.FirstOrDefault();
if (valueString != null)
{
return (T)Convert.ChangeType(valueString, typeof(T));
}
}
return toReturn;
}
}
Sample usage:
var myValue = response.GetFirstHeaderValueOrDefault<int>("MyValue");
How to add a progress bar to a shell script?
Here is how it might look
Uploading a file
[##################################################] 100% (137921 / 137921 bytes)
Waiting for a job to complete
[######################### ] 50% (15 / 30 seconds)
Simple function that implements it
You can just copy-paste it to your script. It does not require anything else to work.
PROGRESS_BAR_WIDTH=50 # progress bar length in characters
draw_progress_bar() {
# Arguments: current value, max value, unit of measurement (optional)
local __value=$1
local __max=$2
local __unit=${3:-""} # if unit is not supplied, do not display it
# Calculate percentage
if (( $__max < 1 )); then __max=1; fi # anti zero division protection
local __percentage=$(( 100 - ($__max*100 - $__value*100) / $__max ))
# Rescale the bar according to the progress bar width
local __num_bar=$(( $__percentage * $PROGRESS_BAR_WIDTH / 100 ))
# Draw progress bar
printf "["
for b in $(seq 1 $__num_bar); do printf "#"; done
for s in $(seq 1 $(( $PROGRESS_BAR_WIDTH - $__num_bar ))); do printf " "; done
printf "] $__percentage%% ($__value / $__max $__unit)\r"
}
Usage example
Here, we upload a file and redraw the progress bar at each iteration. It does not matter what job is actually performed as long as we can get 2 values: max value and current value.
In the example below the max value is file_size
and the current value is supplied by some function and is called uploaded_bytes
.
# Uploading a file
file_size=137921
while true; do
# Get current value of uploaded bytes
uploaded_bytes=$(some_function_that_reports_progress)
# Draw a progress bar
draw_progress_bar $uploaded_bytes $file_size "bytes"
# Check if we reached 100%
if [ $uploaded_bytes == $file_size ]; then break; fi
sleep 1 # Wait before redrawing
done
# Go to the newline at the end of upload
printf "\n"
glm rotate usage in Opengl
GLM has good example of rotation : http://glm.g-truc.net/code.html
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
glm::mat4(1.0f),
glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
ViewTranslate,
Rotate.y,
glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
ViewRotateX,
Rotate.x,
glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
glm::mat4(1.0f),
glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
Delete commits from a branch in Git
git rebase -i HEAD~2
Here '2' is the number of commits you want to rebase.
'git rebase -i HEAD`
if you want to rebase all the commits.
Then you will be able to choose one of these options.
p, pick = use commit
r, reword = use commit, but edit the commit message
e, edit = use commit, but stop for amending
s, squash = use commit, but meld into previous commit
f, fixup = like "squash", but discard this commit's log message
x, exec = run command (the rest of the line) using shell
d, drop = remove commit
These lines can be re-ordered; they are executed from top to bottom.
If you remove a line here THAT COMMIT WILL BE LOST.
However, if you remove everything, the rebase will be aborted.
Note that empty commits are commented out
You can simply remove that commit using option "d" or Removing a line that has your commit.
Difference between volatile and synchronized in Java
volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1;
int geti1() {return i1;}
volatile int i2;
int geti2() {return i2;}
int i3;
synchronized int geti3() {return i3;}
geti1()
accesses the value currently stored in i1
in the current thread.
Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updated i1
in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1
, for thread1 to have a value of 2 for i1
and for thread2 to have a value of 3 for i1
if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
On the other hand, geti2()
effectively accesses the value of i2
from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.
There are two differences between volitile and synchronized.
Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3()
does the following:
- The thread acquires the lock on the monitor for object this .
- The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
- The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
- (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
- The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html
How to save a list as numpy array in python?
Here is a more complete example:
import csv
import numpy as np
with open('filename','rb') as csvfile:
cdl = list( csv.reader(csvfile,delimiter='\t'))
print "Number of records = " + str(len(cdl))
#then later
npcdl = np.array(cdl)
Hope this helps!!
Prevent jQuery UI dialog from setting focus to first textbox
Just figured this out while playing around.
I found with these solutions to remove focus, caused the ESC key to stop working (ie close the dialog) when first going into the Dialog.
If the dialog opens and you immediately press ESC, it won't close the dialog (if you have that enabled), because the focus is on some hidden field or something, and it is not getting keypress events.
The way I fixed it was to add this to the open event to remove the focus from the first field instead:
$('#myDialog').dialog({
open: function(event,ui) {
$(this).parent().focus();
}
});
This sets focus to the dialog box, which is not visible, and then the ESC key works.
How to download source in ZIP format from GitHub?
Updated July 2016
As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:
If you don't see the button:
- Make sure you've selected <> Code tab from right side navigation menu, or
- Repo may not have a zip prepared. Add
/archive/master.zip
to the end of the repository URL and to generate a zipfile of the master branch:
http://github.com/user/repository/
-to->
http://github.com/user/repository/archive/master.zip
to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master
in the URL above with the name of the branch or tag.
Unable to connect PostgreSQL to remote database using pgAdmin
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.
Note: I use Ubuntu 11.04 and PostgreSQL 8.4.
You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:
listen_addresses = '*'
PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:
host all all 0.0.0.0/0 md5
This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .
When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.
Flexbox: center horizontally and vertically
diplay: flex;
for it's container and margin:auto;
for it's item works perfect.
NOTE: You have to setup the width
and height
to see the effect.
_x000D_
_x000D_
#container{_x000D_
width: 100%; /*width needs to be setup*/_x000D_
height: 150px; /*height needs to be setup*/_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
margin: auto; /*These will make the item in center*/_x000D_
background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="item">CENTER</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
What is JSON and why would I use it?
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
- Update (ten years later): Don't do this, use JSON.parse
C# MessageBox dialog result
Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.
var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
case DialogResult.Yes:
SaveChanges();
break;
case DialogResult.No:
Rollback();
break;
default:
break;
}
Angular2 Material Dialog css, dialog size
I think you need to use /deep/
, because your CSS may not see your modal class. For example, if you want to customize .modal-dialog
/deep/.modal-dialog {
width: 75% !important;
}
But this code will modify all your modal-windows, better solution will be
:host {
/deep/.modal-dialog {
width: 75% !important;
}
}
Best practice for storing and protecting private API keys in applications
One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:
// "the real string is: "mypassword" ";
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
return Utils.decode(Utils
.decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
Decompiled source code of a proguarded app is this:
public String c()
{
return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.
/**
* @param input
* @return decoded string
*/
public static String decode(String input) {
// Receiving side
String text = "";
try {
byte[] data = Decoder.decode(input);
text = new String(data, "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error";
}
Decompiled version:
public static String a(String paramString)
{
try
{
str = new String(a.a(paramString), "UTF-8");
return str;
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
{
localUnsupportedEncodingException.printStackTrace();
String str = "Error";
}
}
}
and you can find so many encryptor classes with a little search in google.
How do I correctly upgrade angular 2 (npm) to the latest version?
If you are looking like me for just updating your project to the latest these is what works form me since Angular 6:
Open the console on your project folder: If you type: ng update
then you will get the below message:
We analyzed your package.json, there are some packages to update:
Name Version Command to update
--------------------------------------------------------------------------------
@angular/cli 7.0.7 -> 7.2.2 ng update @angular/cli
@angular/core 7.0.4 -> 7.2.1 ng update @angular/core
There might be additional packages that are outdated.
Run "ng update --all" to try to update all at the same time.
So I usually go straight and do:
ng update --all
Finally you can check your new version:
ng version
Angular CLI: 7.2.2
Node: 8.12.0
OS: win32 x64
Angular: 7.2.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.12.2
@angular-devkit/build-angular 0.12.2
@angular-devkit/build-optimizer 0.12.2
@angular-devkit/build-webpack 0.12.2
@angular-devkit/core 7.2.2
@angular-devkit/schematics 7.2.2
@angular/cli 7.2.2
@ngtools/webpack 7.2.2
@schematics/angular 7.2.2
@schematics/update 0.12.2
rxjs 6.3.3
typescript 3.2.4
webpack 4.28.4
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.]
Does Python have a ternary conditional operator?
Unfortunately, the
(falseValue, trueValue)[test]
solution doesn't have short-circuit behaviour; thus both falseValue
and trueValue
are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue
and falseValue
could be methods and have side-effects).
One solution to this would be
(lambda: falseValue, lambda: trueValue)[test]()
(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties.
And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least ?ython 2.5 (IMHO not a problem anymore) and not being prone to "trueValue
-evaluates-to-false" errors.
What are these attributes: `aria-labelledby` and `aria-hidden`
HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.
Accessible Rich Internet Applications (ARIA) defines ways to make Web
content and Web applications (especially those developed with Ajax and
JavaScript) more accessible to people with disabilities.
To be precise for your question, here is what your attributes are called as ARIA attribute states and model
aria-labelledby
: Identifies the element (or elements) that labels the current element.
aria-hidden (state)
: Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented
by the author.
Selecting/excluding sets of columns in pandas
You can either Drop the columns you do not need OR Select the ones you need
# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)
# Select the ones you want
df1 = df[['a','d']]
How do I test axios in Jest?
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
File actions.test.js:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: '[email protected]',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: '[email protected]',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
How to obtain a Thread id in Python?
I created multiple threads in Python, I printed the thread objects, and I printed the id using the ident
variable. I see all the ids are same:
<Thread(Thread-1, stopped 140500807628544)>
<Thread(Thread-2, started 140500807628544)>
<Thread(Thread-3, started 140500807628544)>
How to pass model attributes from one Spring MVC controller to another controller?
I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.
the main idea for the flash scope is to store data from one controller till next redirect in second controller
Please refer to my answer on the custom scope question:
Spring MVC custom scope bean
The only thing that is missing in this code is the following xml configuration:
<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list><ref bean="flashScopeInterceptor"/></list>
</property>
</bean>
How to get date and time from server
Try this -
<?php
date_default_timezone_set('Asia/Kolkata');
$timestamp = time();
$date_time = date("d-m-Y (D) H:i:s", $timestamp);
echo "Current date and local time on this server is $date_time";
?>
Java: How to set Precision for double value?
You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.
You will have to convert into a decimal radix, either via BigDecimal
or DecimalFormat
, depending on what you want to do with the value later.
See also my answer to this question for a refutation of the inevitable *100/100 answers.
Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs
Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.
Why does the static
change the performance?
The line in question:
uint64_t size = atol(argv[1])<<20;
Short Answer
I would look at the assembly generated for accessing size
and see if there are extra steps of pointer indirection involved for the non-static version.
Long Answer
Since there is only one copy of the variable whether it was declared static
or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.
Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static
? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.
When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.
Cannot find vcvarsall.bat when running a Python script
THIS IS AN UP TO DATE ANSWER FOR WINDOWS USERS - VERY SIMPLE SOLUTION.
As pointed out by other, the problem is that python/cython etc. tries to find the same compiler they were built from, but this compiler does not exist on the computer. Most of the time, this compiler is a version of visual studio (2008, 2010 or 2013), but either such a compiler is not installed, or a newer version is installed and the system prevents from installing an older one. So, the solution is simple:
1) look at C:\Program Files (x86) and see if there is an installed version of Microsoft visual studio, and if it is newer than the version from which Python has been built. If not, install(/update to) the version from which Python has been built (see previous answers), or even a newest version and follow the next step.
2)If a newest version of Microsoft visual studio is already installed, we have to make Python/cython etc. believe that it is the version from which it has been built. And this is very simple: go to the the system environment variables and create the following variables, if they do not exist:
VS100COMNTOOLS
VS110COMNTOOLS
VS120COMNTOOLS
VS140COMNTOOLS
And set the field of these variables to
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools" (if visual studio 2008 is installed), or
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools" (if visual studio 2010 is installed) or
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools" (if visual studio 2013 is installed) or
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools" (if visual studio 2015 is installed).
This solution works for 32 bit versions of python. It may also work for 64 bit version but I've not tested; most probably, for 64 bit versions, the following additional steps must be performed:
3)add the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC" to the %PATH% environment variable (change the number of the version of visual studio according to you version).
4) from the command line, run "vcvarsall.bat x86_amd64"
That's all.
Binding ComboBox SelectedItem using MVVM
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
How to print a query string with parameter values when using Hibernate
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/system.log" />
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="200MB" />
<param name="MaxBackupIndex" value="100" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %d{Z} [%t] %-5p (%F:%L) - %m%n" />
</layout>
</appender>
<appender name="journaldev-hibernate" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/project.log" />
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="200MB" />
<param name="MaxBackupIndex" value="50" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %d{Z} [%t] %-5p (%F:%L) - %m%n" />
</layout>
</appender>
<logger name="com.journaldev.hibernate" additivity="false">
<level value="DEBUG" />
<appender-ref ref="journaldev-hibernate" />
</logger>
<logger name="org.hibernate" additivity="false">
<level value="INFO" />
<appender-ref ref="FILE" />
</logger>
<logger name="org.hibernate.type" additivity="false">
<level value="TRACE" />
<appender-ref ref="FILE" />
</logger>
<root>
<priority value="INFO"></priority>
<appender-ref ref="FILE" />
</root>
Back button and refreshing previous activity
If you want to refresh previous activity, this solution should work:
In previous activity where you want to refresh:
@Override
public void onRestart()
{
super.onRestart();
// do some stuff here
}
Can't stop rails server
If you are using a more modern version of Rails and it uses Puma as the web server, you can run the following command to find the stuck Puma process:
ps aux | grep puma
It will result in output similar to this:
85923 100.0 0.8 2682420 131324 s004 R+ 2:54pm 3:27.92 puma 3.12.0 (tcp://0.0.0.0:3010) [my-app]
92463 0.0 0.0 2458404 1976 s008 S+ 3:09pm 0:00.00 grep puma
You want the process that is not referring to grep
. In this case, the process ID is 85923.
I can then run the following command to kill that process:
kill -9 85923
How can I dynamically add items to a Java array?
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array
and arraylist
.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
- Convert array to an arraylist
- Add element to the arrayList
- Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
Difference between try-catch and throw in java
try - Add sensitive code
catch - to handle exception
finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block
throw - To handover our created exception to JVM manually. Used to throw customized exception
throws - To delegate the responsibility of exception handling to caller method or main method.
How do I remove the "extended attributes" on a file in Mac OS X?
Use the xattr
command. You can inspect the extended attributes:
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine
and use the -d
option to delete one extended attribute:
$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
you can also use the -c
option to remove all extended attributes:
$ xattr -c s.7z
$ xattr s.7z
xattr -h
will show you the command line options, and xattr has a man page.
Time in milliseconds in C
The standard C library provides timespec_get
. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.
#include <stdio.h>
#include <inttypes.h>
#include <time.h>
int64_t millis()
{
struct timespec now;
timespec_get(&now, TIME_UTC);
return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}
int main(void)
{
printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}
Unlike clock
, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep
.
How to define static property in TypeScript interface
Though static keyword not supported in interface in Typescript
but we can achieve it by creating a function interface
that has static member.
In my following code I have created a function interface Factory
that has two static members serialNumber
and printSerial.
// factory is a function interface
interface Factory<T> {
(name: string, age: number): T;
//staic property
serialNumber: number;
//static method
printSrial: () => void;
}
class Dog {
constructor(public name: string, public age: number) { }
}
const dogFactory: Factory<Dog> = (name, age) => {
return new Dog(name, age);
}
// initialising static members
dogFactory.serialNumber = 1234;
dogFactory.printSrial = () => console.log(dogFactory.serialNumber);
//instance of Dog that DogFactory creates
const myDog = dogFactory("spike", 3);
//static property that returns 1234
console.log(dogFactory.serialNumber)
//static method that prints the serial 1234
dogFactory.printSrial();
Synchronous request in Node.js
You could do this using my Common Node library:
function get(url) {
return new (require('httpclient').HttpClient)({
method: 'GET',
url: url
}).finish().body.read().decodeToString();
}
var a = get('www.example.com/api_1.php'),
b = get('www.example.com/api_2.php'),
c = get('www.example.com/api_3.php');
How do I customize Facebook's sharer.php
What you are talking about is the preview image and text that Facebook extracts when you share a link. Facebook uses the Open Graph Protocol to get this data.
Essentially, all you'll have to do is place these og:meta
tags on the URL that you want to share -
<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
<meta property="og:site_name" content="IMDb"/>
<meta property="fb:admins" content="USER_ID"/>
<meta property="og:description"
content="A group of U.S. Marines, under command of
a renegade general, take over Alcatraz and
threaten San Francisco Bay with biological
weapons."/>
As you can see there are both an image property and a description. When you make changes to your pages og:meta
tags, you can test these changes using the Facebook Debugger. It will tell you if you have made any mistakes (and how to fix them!)
In Angular, how to pass JSON object/array into directive?
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
Unit tests vs Functional tests
UNIT TESTING
Unit testing includes testing of smallest unit of code which usually are functions or methods. Unit testing is mostly done by developer of unit/method/function, because they understand the core of a function. The main goal of the developer is to cover code by unit tests.
It has a limitation that some functions cannot be tested through unit tests. Even after the successful completion of all the unit tests; it does not guarantee correct operation of the product. The same function can be used in few parts of the system while the unit test was written only for one usage.
FUNCTIONAL TESTING
It is a type of Black Box testing where testing will be done on the functional aspects of a product without looking into the code. Functional testing is mostly done by a dedicated Software tester. It will include positive, negative and BVA techniques using un standardized data for testing the specified functionality of product. Test coverage is conducted in an improved manner by functional tests than by unit tests. It uses application GUI for testing, so it’s easier to determine what exactly a specific part of the interface is responsible for rather to determine what a code is function responsible for.
m2eclipse error
The following steps worked for me:
- Close Eclipse.
- Navigate to user home directory. (For example: "C:\Users\YourUserName.m2")
- Delete the "repository" folder.
- Re-open Eclipse.
- Click on the Maven project that has an issue and go to "Project" --> "Clean".
- Right-click on the project and go to "Maven" --> "Update Project...".
- Close Eclipse.
- Open Eclipse.
- Click on the project folder in the "Project Explorer" window (usually on the left).
- Hit the "F5" key a few times to Refresh your project.
- Done!
These steps worked for me in Eclipse Luna. Please let me know if I can help further.
How to fix corrupted git repository?
Before trying any of the fixes described on this page, I would advise to make a copy of your repo and work on this copy only. Then at the end if you can fix it, compare it with the original to ensure you did not lose any file in the repair process.
Another alternative which worked for me was to reset the git head and index to its previous state using:
git reset --keep
You can also do the same manually by opening the Git GUI and selecting each "Staged changes" and click on "Unstage the change". When everything is unstaged, you should now be able to compress your database, check your database and commit.
I also tried the following commands but they did not work for me, but they might for you depending on the exact issue you have:
git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all
Finally, to avoid this problem of synchronization damaging your git index (which can happen with DropBox, SpiderOak, or any other cloud disk), you can do the following:
- Convert your
.git
folder into a single "bundle" git file by using: git bundle create my_repo.git --all
, then it should work just the same as before, but since everything is in a single file you won't risk the synchronization damaging your git repo anymore.
- Disable instantaneous synchronization: SpiderOak allows you to set the scheduling for checking changes to "automatic" (which means that it is as soon as possible, being monitoring file changes thanks to the OS notifications). This is bad because it will start to upload changes as soon as you are doing a change, and then download the change, so it might erase the latest changes you were just doing. A solution to fix this issue is to set the changes monitoring delay to 5 minutes or more. This also fixes issues with instant saving note taking applications (such as Notepad++).
Using an Alias in a WHERE clause
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A, table_b B
WHERE .identifier = B.identifier
HAVING MONTH_NO > UPD_DATE
VB.NET - How to move to next item a For Each Loop?
Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").
At least with "continue for" the programmer knows the code goes directly to the top of the loop.
For purists though, something like this is best since it is pure "non-spaghetti" code.
Dim bKeepGoing as Boolean
For Each I As Item In Items
bKeepGoing = True
If I = x Then
bKeepGoing = False
End If
if bKeepGoing then
' Do something
endif
Next
For ease of coding though, "Continue For" is OK. (Good idea to comment it though).
Using "Continue For"
For Each I As Item In Items
If I = x Then
Continue For 'skip back directly to top of loop
End If
' Do something
Next
How do I filter date range in DataTables?
Using other posters code with some tweaks:
<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
<tbody>
<tr>
<td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$(function() {
var oTable = $('#tbAD').DataTable({
"oLanguage": {
"sSearch": "Filter Data"
},
"iDisplayLength": -1,
"sPaginationType": "full_numbers",
"pageLength": 50,
});
$("#datepicker_from").datepicker();
$("#datepicker_to").datepicker();
$('#datepicker_from').change(function (e) {
oTable.draw();
});
$('#datepicker_to').change(function (e) {
oTable.draw();
});
$('#datepicker_clear_lnk').click(function (e) {
oTable.draw();
});
});
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
var startDate = new Date(data[9]).setHours(0,0,0,0);
if (min == null && max == null) { return true; }
if (min == null && startDate <= max) { return true; }
if (max == null && startDate >= min) { return true; }
if (startDate <= max && startDate >= min) { return true; }
return false;
}
);
});
</script>
Angularjs - Pass argument to directive
<button my-directive="push">Push to Go</button>
app.directive("myDirective", function() {
return {
restrict : "A",
link: function(scope, elm, attrs) {
elm.bind('click', function(event) {
alert("You pressed button: " + event.target.getAttribute('my-directive'));
});
}
};
});
here is what I did
I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push"
And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive')
.
Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)
Up to Android 7.1 (SDK 25)
Until Android 7.1 you will get it with:
Build.SERIAL
From Android 8 (SDK 26)
On Android 8 (SDK 26) and above, this field will return UNKNOWN
and must be accessed with:
Build.getSerial()
which requires the dangerous permission
android.permission.READ_PHONE_STATE
.
From Android Q (SDK 29)
Since Android Q using Build.getSerial()
gets a bit more complicated by requiring:
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
(which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE
permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.
See Android SDK reference
Best Practice for Unique Device Identifier
If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString();
and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID
which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.
How to format a java.sql Timestamp for displaying?
java.sql.Timestamp
extends java.util.Date
. You can do:
String s = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);
Or to also include time:
String s = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);
regular expression for anything but an empty string
You can do one of two things:
- match against
^\s*$
; a match means the string is "empty"
^
, $
are the beginning and end of string anchors respectively
\s
is a whitespace character
*
is zero-or-more repetition of
- find a
\S
; an occurrence means the string is NOT "empty"
\S
is the negated version of \s
(note the case difference)
\S
therefore matches any non-whitespace character
References
Related questions
TypeScript: Creating an empty typed container array
I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.
I had
return [];
where []
was Criminal[]
type.
Neither return: Criminal[] [];
nor return []: Criminal[];
worked for me.
At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.
For thoroughness I'll report this solution in my answer too:
let temp: Criminal[] = [];
return temp;
Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:
return <Criminal[]>[];
Hope this will help future readers!
mysql update query with sub query
Thanks, I didn't have the idea of an UPDATE with INNER JOIN.
In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.
UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
FROM PicksPoints
WHERE UserCompetitionID is not NULL
-- put the join condition INSIDE the subquery :
AND CompetitionID = Competition.CompetitionID
group by CompetitionID
) -- no table alias
should do the trick for every record of Competition.
To be noticed :
The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.
Since SELECT id, COUNT(*) GROUP BY id
will only count for existing values of ids,
whereas a SELECT COUNT(*)
will always return a value, being 0 if no records are selected.
This may, or may not, be a problem for you.
0-aware version of mellamokb query would be :
Update Competition as C
LEFT join (
select CompetitionId, count(*) as NumberOfTeams
from PicksPoints as p
where UserCompetitionID is not NULL
group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)
In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.
Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu
System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here
The socket plugin checks whether the socket user name (the operating
system user name) matches the MySQL user name specified by the client
program to the server, and permits the connection only if the names
match.
Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.
About the method to achieve that, I recommend this instead.
Send values from one form to another form
Declare a public string in form1
public string getdata;
In button of form1
form2 frm= new form2();
this.hide();
form2.show();
To send data to form1
you can try any event and code following in that event
form1 frm= new form1();
form1.getdata="some string to be sent to form1";
Now after closing of form2
and opening of form1
, you can use returned data in getdata
string.
Ignore fields from Java object dynamically while sending as JSON from Spring MVC
I've solved using only @JsonIgnore
like @kryger has suggested.
So your getter will become:
@JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set @JsonIgnore
of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty
annotation to your field:
@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
Find the line number where a specific word appears with "grep"
Use grep -n
to get the line number of a match.
I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:
sed -n '10,$ { /regex/ { =; p; } }' file
To get only the line numbers, you could use
grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'
Or you could simply use sed:
sed -n '/regex/=' file
Combining the two sed commands, you get:
sed -n '10,$ { /regex/= }' file
Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time
Additionally, how do I retrieve the number of days of a given month?
Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:
var y= 2010, m= 11; // December 2010 - trap: months are 0-based in JS
var next= Date.UTC(y, m+1); // timestamp of beginning of following month
var end= new Date(next-1); // date for last second of this month
var lastday= end.getUTCDate(); // 31
In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds
instead of getSeconds()
, and Date.UTC
to get a timestamp from a UTC date, rather than new Date(y, m)
, so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.
if condition in sql server update query
Since you're using SQL 2008:
UPDATE
table_Name
SET
column_A
= CASE
WHEN @flag = '1' THEN @new_value
ELSE 0
END + column_A,
column_B
= CASE
WHEN @flag = '0' THEN @new_value
ELSE 0
END + column_B
WHERE
ID = @ID
If you were using SQL 2012:
UPDATE
table_Name
SET
column_A = column_A + IIF(@flag = '1', @new_value, 0),
column_B = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
ID = @ID
How do I use a char as the case in a switch-case?
public class SwitCase {
public static void main (String[] args){
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); //get the first char.
switch(hi){
case 'a': System.out.println("a");
}
}
}
Sass calculate percent minus px
Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.
You need to use calc()
instead. Check browser compatibility on Can I use...
.foo {
height: calc(25% - 5px);
}
If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):
$a: 25%;
$b: 5px;
.foo {
width: calc(#{$a} - #{$b});
}
Return current date plus 7 days
If it's 7 days from now that you're looking for, just put:
$date = strtotime("+7 day", time());
echo date('M d, Y', $date);
Invalid character in identifier
Similar to the previous answers, the problem is some character (possibly invisible) that the Python interpreter doesn't recognize. Because this is often due to copy-pasting code, re-typing the line is one option.
But if you don't want to re-type the line, you can paste your code into this tool or something similar (Google "show unicode characters online"), and it will reveal any non-standard characters. For example,
s=' values ??= list(analysis.values ??())'
becomes
s=' values U+200B U+200B?? = list(analysis.values U+200B U+200B ??())'
You can then delete the non-standard characters from the string.
How to run crontab job every week on Sunday
10 * * * Sun
Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday.
How to get day of the month?
It is simplified a lot in version Java 8. I have given some util methods below.
To get the day of the month in the format of int
for the given day, month, and year.
public static int findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.of(year, month, day).getDayOfMonth());
return LocalDate.of(year, month, day).getDayOfMonth();
}
To get current day of the month in the format of int
.
public static int findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth());
return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth();
}
To get the day of the week in the format of String
for the given day, month, and year.
public static String findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.of(year, month, day).getDayOfWeek());
return LocalDate.of(year, month, day).getDayOfWeek().toString();
}
To get current day of the week in the format of String
.
public static String findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata"))..getDayOfWeek());
return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfWeek().toString();
}
HTTP error 403 in Python 3 Web Scraping
"This is probably because of mod_security or some similar server security feature which blocks known
spider/bot
user agents (urllib uses something like python urllib/3.3.0, it's easily detected)" - as already mentioned by Stefano Sanfilippo
from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
The web_byte is a byte object returned by the server and the content type present in webpage is mostly utf-8.
Therefore you need to decode web_byte using decode method.
This solves complete problem while I was having trying to scrap from a website using PyCharm
P.S -> I use python 3.4
EL access a map value by Integer key
Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter.
In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.
One way to get around this is to do something like this.
<c:set var="longKey" value="${param.selectedIndex + 0}"/>
This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.
Then, continue as usual with something like
${map[longKey]}
How to checkout in Git by date?
Going further with the rev-list
option, if you want to find the most recent merge commit from your master branch into your production branch (as a purely hypothetical example):
git checkout `git rev-list -n 1 --merges --first-parent --before="2012-01-01" production`
I needed to find the code that was on the production servers as of a given date. This found it for me.
Check if a number is a perfect square
import math
def is_square(n):
sqrt = math.sqrt(n)
return (sqrt - int(sqrt)) == 0
A perfect square is a number that can be expressed as the product of two equal integers. math.sqrt(number)
return a float
. int(math.sqrt(number))
casts the outcome to int
.
If the square root is an integer, like 3, for example, then math.sqrt(number) - int(math.sqrt(number))
will be 0, and the if
statement will be False
. If the square root was a real number like 3.2, then it will be True
and print "it's not a perfect square".
It fails for a large non-square such as 152415789666209426002111556165263283035677490.
How to get error information when HttpWebRequest.GetResponse() fails
HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
{
//Perform necessary action based on response
}
myHttpresponse.Close();
Increasing nesting function calls limit
This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:
xdebug.max_nesting_level = 200
or in your PHP code:
ini_set('xdebug.max_nesting_level', 200);
As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.
Difference between string object and string literal
A String literal is a Java language concept. This is a String literal:
"a String literal"
A String object is an individual instance of the java.lang.String
class.
String s1 = "abcde";
String s2 = new String("abcde");
String s3 = "abcde";
All are valid, but have a slight difference. s1
will refer to an interned String object. This means, that the character sequence "abcde"
will be stored at a central place, and whenever the same literal "abcde"
is used again, the JVM will not create a new String object but use the reference of the cached String.
s2
is guranteed to be a new String object, so in this case we have:
s1 == s2 // is false
s1 == s3 // is true
s1.equals(s2) // is true
Read file content from S3 bucket with boto3
You might also consider the smart_open
module, which supports iterators:
from smart_open import smart_open
# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
print(line.decode('utf8'))
and context managers:
with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
for line in s3_source:
print(line.decode('utf8'))
s3_source.seek(0) # seek to the beginning
b1000 = s3_source.read(1000) # read 1000 bytes
Find smart_open
at https://pypi.org/project/smart_open/
Alternative for frames in html5 using iframes
Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows.
Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:
Template File
<html>
<head>
<title>{insert script variable for title}</title>
</head>
<body>
<div class="menu">
{menu items inserted here by server-side scripting}
</div>
<div class="main-content">
{main content inserted here by server-side scripting}
</div>
</body>
</html>
If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.
But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.
You could emulate your example like this:
Frames Example
<html>
<head>
<title>Frames Test</title>
<style>
.menu {
float:left;
width:20%;
height:80%;
}
.mainContent {
float:left;
width:75%;
height:80%;
}
</style>
</head>
<body>
<iframe class="menu" src="menu.html"></iframe>
<iframe class="mainContent" src="events.html"></iframe>
</body>
</html>
There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.