WPF Binding to parent DataContext
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
Convert ascii value to char
To convert an int
ASCII value to character you can also use:
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
dropdownlist set selected value in MVC3 Razor
To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");
Javascript find json value
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag
The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.
See this explanation from Mike Williams' Google Maps API v2 tutorial:
If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's
because the div tries to be a percentage of the size of the <body>
, but by default the <body>
has an indeterminate
height.
There are ways to determine the height of the screen and use that number of pixels as the height of the map div,
but a simple alternative is to change the <body>
so that its height is 100% of the page. We can do this by
applying style="height:100%" to both the <body>
and the <html>
. (We have to do it to both, otherwise the
<body>
tries to be 100% of the height of the document, and the default for that is an indeterminate height.)
Add the 100% size to html and body in your css
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
Add it inline to any divs that don't have an id:
<body>
<div style="height:100%; width: 100%;">
<div id="map-canvas"></div>
</div>
</body>
Creating folders inside a GitHub repository without using Git
After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.
When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.
For example, if I would like to create the file filename.md
in a series of sub-folders, I can do this (taken from the GitHub blog):
Get a list of URLs from a site
do wget -r -l0 www.oldsite.com
Then just find www.oldsite.com
would reveal all urls, I believe.
Alternatively, just serve that custom not-found page on every 404 request!
I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.
Interpreting "condition has length > 1" warning from `if` function
Just adding a point to the whole discussion as to why this warning comes up (It wasn't clear to me before). The reason one gets this is as mentioned before is because 'a' in this case is a vector and the inequality 'a>0' produces another vector of TRUE and FALSE (where 'a' is >0 or not).
If you would like to instead test if any value of 'a>0', you can use functions - 'any' or 'all'
Best
The ResourceConfig instance does not contain any root resource classes
Your resource package should contain at least one pojo which is either annotated with @Path
or have at least one method annotated with @Path
or a request method designator, such as @GET
, @PUT
, @POST
, or @DELETE
. Resource methods are methods of a resource class annotated with a request method designator. This resolved my issue...
Embedding VLC plugin on HTML page
I found this:
<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2" width="100%"
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>
I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...
and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object
Another thing to check is that the address for the video file is correct....
How to add a button dynamically in Android?
Try this:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);
How to delete last item in list?
If I understood the question correctly, you can use the slicing notation to keep everything except the last item:
record = record[:-1]
But a better way is to delete the item directly:
del record[-1]
Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)
Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).
Do you have to put Task.Run in a method to make it async?
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
- The
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.
- Any type that follows a certain pattern can be awaitable. The most common awaitable types are
Task
and Task<T>
.
So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
Getting multiple keys of specified value of a generic Dictionary?
Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had
var greek = new Dictionary<int, string> { { 1, "Alpha" }, { 2, "Alpha" } };
What would you expect to get for greek.WhatDoIPutHere("Alpha")
?
Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or IEnumerable<T>
)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?
Personally I'd go for an enumerable, like so:
IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)
{
if (dict == null)
{
throw new ArgumentNullException("dict");
}
return dict.Keys.Where(k => dict[k] == val);
}
var keys = greek.KeysFromValue("Beta");
int exceptionIfNotExactlyOne = greek.KeysFromValue("Beta").Single();
How to find Google's IP address?
On Windows, open command prompt and type tracert google.com
and press enter, or on Linux, open terminal and type nslookup google.com
and press enter:
Server: 127.0.1.1
Address: 127.0.1.1#53
Non-authoritative answer:
Name: google.com
Address: 74.125.236.199
Name: google.com
Address: 74.125.236.201
Name: google.com
Address: 74.125.236.194
Name: google.com
Address: 74.125.236.198
Name: google.com
Address: 74.125.236.206
Name: google.com
Address: 74.125.236.193
Name: google.com
Address: 74.125.236.196
Name: google.com
Address: 74.125.236.192
Name: google.com
Address: 74.125.236.197
Name: google.com
Address: 74.125.236.195
Name: google.com
Address: 74.125.236.200
Select DataFrame rows between two dates
With my testing of pandas
version 0.22.0
you can now answer this question easier with more readable code by simply using between
.
# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})
Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:
# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)
0 False
1 False
2 False
3 False
4 False
# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]
dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02
Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
This method is also faster than the previously mentioned isin
method:
%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
%%timeit -n 5
df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:
# already create the mask THEN time the function
start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)
%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
What is offsetHeight, clientHeight, scrollHeight?
My descriptions for the three:
- offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's
position: absolute
descendents)
- clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
- scrollHeight: How much space is needed to see all of the element's content/descendents (including
position: absolute
ones) without scrolling.
Then there is also:
Fastest way to update 120 Million records
In general, recommendation are next:
- Remove or just Disable all INDEXES, TRIGGERS, CONSTRAINTS on the table;
- Perform COMMIT more often (e.g. after each 1000 records that were updated);
- Use select ... into.
But in particular case you should choose the most appropriate solution or their combination.
Also bear in mind that sometime index could be useful e.g. when you perform update of non-indexed column by some condition.
Random word generator- Python
Solution for Python 3
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
How do I resize a Google Map with JavaScript after it has loaded?
First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point.
The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.
We need to Update the GoogleMapHelper to fix the issue
Need to add the below script in setCenterMap function
google.maps.event.trigger({$id}, \"resize\");
And need the include below code in JavaScript
google.maps.event.addListenerOnce({$id}, 'idle', function(){
setCenterMap(new google.maps.LatLng({$this->defaultLatitude},
{$this->defaultLongitude}));
});
How to submit a form when the return key is pressed?
IMO, this is the cleanest answer:
_x000D_
_x000D_
<form action="" method="get">_x000D_
Name: <input type="text" name="name"/><br/>_x000D_
Pwd: <input type="password" name="password"/><br/>_x000D_
<div class="yourCustomDiv"/>_x000D_
<input type="submit" style="display:none"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_
Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.
It has been noted that display:none will cause IE to ignore the input. I created a new JSFiddle example that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from StriplingWarrior.
"Insufficient Storage Available" even there is lot of free space in device memory
If you have root, delete all of the folders on the path:
/data/app-lib/
And then restart your device.
I had this issue many times, and this fix worked for me each time. It even has an XDA thread.
I write all folders, because if there is a problem with one app, there is a good chance you have this issue with other apps too. Plus, it's annoying to find just the folders of the problematic app/s .
Using FileUtils in eclipse
FileUtils
is class from apache org.apache.commons.io
package, you need to download org.apache.commons.io.jar
and then configure that jar
file in your class path.
How can I insert data into a MySQL database?
Here is OOP:
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
Drop multiple columns in pandas
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
jQuery Set Select Index
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");
# Set element by text
$("#select").val("option Text").attr("selected", "selected");
when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected');
for remove previous selects .
# Set element by value
$("#select").val("2");
# Get selected text
$("#select").children("option:selected").text(); # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes
# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();
# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));
# Select First Option
$("#select option:first");
# Select Last Item
$("#select option:last").remove();
# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");
# Remove an item
$("#select option:eq(0)").remove();
Display all post meta keys and meta values of the same post ID in wordpress
As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.
It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:
$meta_values = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];
//OR if you do enum style
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0];
As the print_r(meta_values);
gives:
Array
(
[_edit_lock] => Array
(
[0] => 1579542560:1
)
[_edit_last] => Array
(
[0] => 1
)
[example_field] => Array
(
[0] => 13
)
)
Hope that helps someone, go make a ruckus!
What does "Changes not staged for commit" mean
You have to use git add to stage them, or they won't commit. Take it that it informs git which are the changes you want to commit.
git add -u :/
adds all modified file changes to the stage
git add * :/
adds modified and any new files (that's not gitignore'ed) to the stage
How to return the output of stored procedure into a variable in sql server
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)
To this:
declare @t table(id int)
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)
The following artifacts could not be resolved: javax.jms:jms:jar:1.1
I also faced the same issue when I started using following maven dependency version for log4j (1.2.15) in my project.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
Following error was thrown at me.
The following artifacts could not be resolved: javax.jms:jms:jar:1.1, com.sun.jdmk:jmxtools:jar:1.2.1, com.sun.jmx:jmxri:jar:1.2.1: Could not transfer artifact javax.jms:jms:jar:1.1 from/to java.net (https://maven-repository.dev.java.net/nonav/repository): Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available connector factories: BasicRepositoryConnectorFactory: Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available layout factories: Maven2RepositoryLayoutFactory: Unsupported repository layout legacy -> [Help 1]
I started using following log4j (1.2.17) version and it helped me solve this issue without any configurations related fixes.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Difference between <span> and <div> with text-align:center;?
It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one.
Install Firebug at Firefox and check the style attributes your span or div object has.
Return content with IHttpActionResult for non-OK response
A more detailed example with support of HTTP code not defined in C# HttpStatusCode
.
public class MyController : ApiController
{
public IHttpActionResult Get()
{
HttpStatusCode codeNotDefined = (HttpStatusCode)429;
return Content(codeNotDefined, "message to be sent in response body");
}
}
Content
is a virtual method defined in abstract class ApiController
, the base of the controller. See the declaration as below:
protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);
Angular ngClass and click event for toggling class
Angular6 using the renderer2 without any variables and a clean template:
template:
<div (click)="toggleClass($event,'testClass')"></div>
in ts:
toggleClass(event: any, class: string) {
const hasClass = event.target.classList.contains(class);
if(hasClass) {
this.renderer.removeClass(event.target, class);
} else {
this.renderer.addClass(event.target, class);
}
}
One could put this in a directive too ;)
Lost connection to MySQL server during query?
Multiprocessing and Django DB don't play well together.
I ended up closing Django DB connection first thing in the new process.
So that one will have no references to the connection used by the parent.
from multiprocessing import Pool
multi_core_arg = [[1,2,3], [4,5,6], [7,8,9]]
n_cpu = 4
pool = Pool(n_cpu)
pool.map(_etl_, multi_core_arg)
pool.close()
pool.join()
def _etl_(x):
from django.db import connection
connection.close()
print(x)
OR
Process.start()
calls a function which starts with
Some other suggest to use
from multiprocessing.dummy import Pool as ThreadPool
It solved my (2013, Lost connection) problem, but thread use GIL, when doing IO, to will release it when IO finish.
Comparatively, Process spawn a group of workers that communication each other, which may be slower.
I recommend you to time it.
A side tips is to use joblib which is backed by scikit-learn project.
some performance result shows it out perform the native Pool().. although it leave the responsibility to coder to verify the true run time cost.
How to set java.net.preferIPv4Stack=true at runtime?
you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.
set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true
You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.
How to generate a random integer number from within a range
For those who understand the bias problem but can't stand the unpredictable run-time of rejection-based methods, this series produces a progressively less biased random integer in the [0, n-1]
interval:
r = n / 2;
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
r = (rand() * n + r) / (RAND_MAX + 1);
...
It does so by synthesising a high-precision fixed-point random number of i * log_2(RAND_MAX + 1)
bits (where i
is the number of iterations) and performing a long multiplication by n
.
When the number of bits is sufficiently large compared to n
, the bias becomes immeasurably small.
It does not matter if RAND_MAX + 1
is less than n
(as in this question), or if it is not a power of two, but care must be taken to avoid integer overflow if RAND_MAX * n
is large.
Post values from a multiple select
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
Singleton: How should it be used
I still don't get why a singleton has to be global.
I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.
I don't see why this functionality would be bad.
how to convert integer to string?
NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];
Update for new Objective-C syntax:
NSArray *myArray = @[@1, @2, @3];
Those two declarations are identical from the compiler's perspective.
if you're just wanting to use an integer in a string for putting into a textbox or something:
int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];
How to save DataFrame directly to Hive?
You can create an in-memory temporary table and store them in hive table using sqlContext.
Lets say your data frame is myDf. You can create one temporary table using,
myDf.createOrReplaceTempView("mytempTable")
Then you can use a simple hive statement to create table and dump the data from your temp table.
sqlContext.sql("create table mytable as select * from mytempTable");
java.math.BigInteger cannot be cast to java.lang.Integer
As we see from the javaDoc, BigInteger
is not a subclass of Integer
:
java.lang.Object java.lang.Object
java.lang.Number java.lang.Number
java.math.BigInteger java.lang.Integer
And that's the reason why casting from BigInteger
to Integer
is impossible.
Casting of java primitives will do some conversion (like casting from double
to int
) while casting of types will never transform classes.
Linking to a specific part of a web page
First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"
Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id"
Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated.
But instead of
> http://url.to.site/index.html#target
You would put
> http://storedomain.com/target
For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235
for my hyperlink.
Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores.
If you want to link to something other than your homepage you would put
> http://mystore-classifier.com/pagename/#BlockID
I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!
How to set conditional breakpoints in Visual Studio?
Visual Studio provides lots of options for conditional breakpoints:
To set any of these you
- Set a breakpoint.
- Right-Click over the breakpoint, and in the popup menu you select an option that suites you.
These options are as follows:
- You can set a condition, based on a code expression that you supply (select Condition from the popup menu). For instance, you can specify that
foo == 8
or some other expression.
- You can make breakpoints trigger after they have been hit a certain number of times. (select Hit Count from the popup menu). This is a fun option to play with as you actually aren't limited to breaking on a certain hit count, but you have options for a few other scenarios as well. I'll leave it to you to explore the possibilities.
- You can Set filters on the Process ID, thread ID, and machine name (select Filter from the popup menu)
How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
Hide/Show Action Bar Option Menu Item for different fragments
To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:
Lets say you want the save
button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu
method of the Fragment where you view the items:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.findItem(R.id.action_save_item).setVisible(false);
}
}
NOTE: For this to work, you need the onCreate()
method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true)
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Might not be the best option, but it works and it's simple.
what is an illegal reflective access
There is an Oracle article I found regarding Java 9 module system
By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.
As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible
for JDK8 and JDK9 are instructive. Specifically, JDK9 added
This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:
- C and D are in the same module.
- The member is public and D is public in a package that the module containing D exports to at least the module containing C.
- The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
- D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.
which highlights the significance of modules and their exports (in Java 9)
How to get a matplotlib Axes instance to plot to?
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
Error : Index was outside the bounds of the array.
public int[] posStatus;
public UsersInput()
{
//It means postStatus will contain 9 elements from index 0 to 8.
this.posStatus = new int[9];
}
int intUsersInput = 0;
if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?
{
posStatus[intUsersInput-1] += 1; //set it to 1
}
How can I trim leading and trailing white space?
Another related problem occurs if you have multiple spaces in between inputs:
> a <- " a string with lots of starting, inter mediate and trailing whitespace "
You can then easily split this string into "real" tokens using a regular expression to the split
argument:
> strsplit(a, split=" +")
[[1]]
[1] "" "a" "string" "with" "lots"
[6] "of" "starting," "inter" "mediate" "and"
[11] "trailing" "whitespace"
Note that if there is a match at the beginning of a (non-empty) string, the first element of the output is ‘""’, but if there is a match at the end of the string, the output is the same as with the match removed.
What is the difference between a 'closure' and a 'lambda'?
It's as simple as this: lambda is a language construct, i.e. simply syntax for anonymous functions; a closure is a technique to implement it -- or any first-class functions, for that matter, named or anonymous.
More precisely, a closure is how a first-class function is represented at runtime, as a pair of its "code" and an environment "closing" over all the non-local variables used in that code. This way, those variables are still accessible even when the outer scopes where they originate have already been exited.
Unfortunately, there are many languages out there that do not support functions as first-class values, or only support them in crippled form. So people often use the term "closure" to distinguish "the real thing".
How to read until EOF from cin in C++
You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.
#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>
int main()
{
// don't skip the whitespace while reading
std::cin >> std::noskipws;
// use stream iterators to copy the stream to a string
std::istream_iterator<char> it(std::cin);
std::istream_iterator<char> end;
std::string results(it, end);
std::cout << results;
}
character count using jquery
For length including white-space:
$("#id").val().length
For length without white-space:
$("#id").val().replace(/ /g,'').length
For removing only beginning and trailing white-space:
$.trim($("#test").val()).length
For example, the string " t e s t "
would evaluate as:
//" t e s t "
$("#id").val();
//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7
Here is a demo using all of them.
"No rule to make target 'install'"... But Makefile exists
Could you provide a whole makefile?
But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
Class 'DOMDocument' not found
After a long time suffering from it in PHPunit...
For those using namespace, which is very common with Frameworks or CMS, a good check in addition to seeing if php-xml is installed and active, is to remember to declare the DOMDocument after the namespace:
namespace YourNameSpace\YourNameSpace;
use DOMDocument; //<--- here, check this!
pandas get column average/mean
You can easily follow the following code
import pandas as pd
import numpy as np
classxii = {'Name':['Karan','Ishan','Aditya','Anant','Ronit'],
'Subject':['Accounts','Economics','Accounts','Economics','Accounts'],
'Score':[87,64,58,74,87],
'Grade':['A1','B2','C1','B1','A2']}
df = pd.DataFrame(classxii,index = ['a','b','c','d','e'],columns=['Name','Subject','Score','Grade'])
print(df)
#use the below for mean if you already have a dataframe
print('mean of score is:')
print(df[['Score']].mean())
Difference between jar and war in Java
From Java Tips: Difference between ear jar and war files:
These files are simply zipped files
using the java jar tool. These files are
created for different purposes. Here
is the description of these files:
.jar files: The .jar files contain
libraries, resources and
accessories files like property files.
.war files: The war file contains
the web application that can be
deployed on any servlet/jsp
container. The .war file contains jsp,
html, javascript and other files
necessary for the development of web
applications.
Official Sun/Oracle descriptions:
Wikipedia articles:
How to validate array in Laravel?
The below code working for me on array coming from ajax call .
$form = $request->input('form');
$rules = array(
'facebook_account' => 'url',
'youtube_account' => 'url',
'twitter_account' => 'url',
'instagram_account' => 'url',
'snapchat_account' => 'url',
'website' => 'url',
);
$validation = Validator::make($form, $rules);
if ($validation->fails()) {
return Response::make(['error' => $validation->errors()], 400);
}
Find all CSV files in a directory using Python
I had to get csv
files that were in subdirectories, therefore, using the response from tchlpr I modified it to work best for my use case:
import os
import glob
os.chdir( '/path/to/main/dir' )
result = glob.glob( '*/**.csv' )
print( result )
String Concatenation using '+' operator
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
FormData.append("key", "value") is not working
You say it's not working. What are you expecting to happen?
There's no way of getting the data out of a FormData
object; it's just intended for you to use to send data along with an XMLHttpRequest
object (for the send
method).
Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormData
in addition to just stuffing data into it. See the accepted answer for more info.
How to get the filename without the extension in Java?
My solution needs the following import.
import java.io.File;
The following method should return the desired output string:
private static String getFilenameWithoutExtension(File file) throws IOException {
String filename = file.getCanonicalPath();
String filenameWithoutExtension;
if (filename.contains("."))
filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1, filename.lastIndexOf('.'));
else
filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1);
return filenameWithoutExtension;
}
Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
Trim characters in Java
it appears that there is no ready to use java api that makes that but you can write a method to do that for you.
this link might be usefull
laravel-5 passing variable to JavaScript
The best way for me was to put it in a hidden div in php blade
<div hidden id="token">{{$token}}</div>
then call it in javascript as a constant to avoid undefined var errors
const token = document.querySelector('div[id=token]').textContent
// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k
How to prevent custom views from losing state across screen orientation changes
Easy with kotlin
@Parcelize
class MyState(val superSavedState: Parcelable?, val loading: Boolean) : View.BaseSavedState(superSavedState), Parcelable
class MyView : View {
var loading: Boolean = false
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
return MyState(superState, loading)
}
override fun onRestoreInstanceState(state: Parcelable?) {
val myState = state as? MyState
super.onRestoreInstanceState(myState?.superSaveState ?: state)
loading = myState?.loading ?: false
//redraw
}
}
How do I copy items from list to list without foreach?
Easy to map different set of list by linq without for loop
var List1= new List<Entities1>();
var List2= new List<Entities2>();
var List2 = List1.Select(p => new Entities2
{
EntityCode = p.EntityCode,
EntityId = p.EntityId,
EntityName = p.EntityName
}).ToList();
Python, how to read bytes from file and save it?
Here's how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.
in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()
out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()
We can do this more succinctly by using the with
keyboard to handle closing the file.
with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
out_file.write(in_file.read())
If you don't want to store the entire file in memory, you can transfer it in pieces.
piece_size = 4096 # 4 KiB
with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
while True:
piece = in_file.read(piece_size)
if piece == "":
break # end of file
out_file.write(piece)
Bootstrap 4 datapicker.js not included
You can use this and then you can add just a class
form from bootstrap.
(does not matter which version)
<div class="form-group">
<label >Begin voorverkoop periode</label>
<input type="date" name="bday" max="3000-12-31"
min="1000-01-01" class="form-control">
</div>
<div class="form-group">
<label >Einde voorverkoop periode</label>
<input type="date" name="bday" min="1000-01-01"
max="3000-12-31" class="form-control">
</div>
Listening for variable changes in JavaScript
Using Prototype
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
var c = document.getElementById('console');_x000D_
c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var myVar = 123;_x000D_
_x000D_
Object.defineProperty(this, 'varWatch', {_x000D_
get: function () { return myVar; },_x000D_
set: function (v) {_x000D_
myVar = v;_x000D_
print('Value changed! New value: ' + v);_x000D_
}_x000D_
});_x000D_
_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_
Other example
_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
var c = document.getElementById('console');_x000D_
c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var varw = (function (context) {_x000D_
return function (varName, varValue) {_x000D_
var value = varValue;_x000D_
_x000D_
Object.defineProperty(context, varName, {_x000D_
get: function () { return value; },_x000D_
set: function (v) {_x000D_
value = v;_x000D_
print('Value changed! New value: ' + value);_x000D_
}_x000D_
});_x000D_
};_x000D_
})(window);_x000D_
_x000D_
varw('varWatch'); // Declare_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);_x000D_
_x000D_
print('---');_x000D_
_x000D_
varw('otherVarWatch', 123); // Declare with initial value_x000D_
print(otherVarWatch);_x000D_
otherVarWatch = 789;_x000D_
print(otherVarWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_
How to install a gem or update RubyGems if it fails with a permissions error
This will fix the issue on MacOS Mojave and Catalina in a clean way:
brew install ruby
Then set GEM_HOME
to your user directory. On the terminal:
Bash
:
echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc
echo 'export GEM_HOME=$HOME/gems' >> ~/.bashrc
echo 'export PATH=$HOME/gems/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
OR if on Zsh
:
echo '# Install Ruby Gems to ~/gems' >> ~/.zshrc
echo 'export GEM_HOME=$HOME/gems' >> ~/.zshrc
echo 'export PATH=$HOME/gems/bin:$PATH' >> ~/.zshrc
source ~/.zshrc
join list of lists in python
This is known as flattening, and there are a LOT of implementations out there:
How about this, although it will only work for 1 level deep nesting:
>>> x = [["a","b"], ["c"]]
>>> for el in sum(x, []):
... print el
...
a
b
c
From those links, apparently the most complete-fast-elegant-etc implementation is the following:
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
Selecting distinct values from a JSON
Underscore.js is great for this kind of thing. You can use _.countBy()
to get the counts per name
:
data = [{"id":11,"name":"ajax","subject":"OR","mark":63},
{"id":12,"name":"javascript","subject":"OR","mark":63},
{"id":13,"name":"jquery","subject":"OR","mark":63},
{"id":14,"name":"ajax","subject":"OR","mark":63},
{"id":15,"name":"jquery","subject":"OR","mark":63},
{"id":16,"name":"ajax","subject":"OR","mark":63},
{"id":20,"name":"ajax","subject":"OR","mark":63}]
_.countBy(data, function(data) { return data.name; });
Gives:
{ajax: 4, javascript: 1, jquery: 2}
For an array of the keys just use _.keys()
_.keys(_.countBy(data, function(data) { return data.name; }));
Gives:
["ajax", "javascript", "jquery"]
Apache redirect to another port
This might be an old question, but here's what I did:
In a .conf file loaded by apache:
<VirtualHost *:80>
ServerName something.com
ProxyPass / http://localhost:8080/
</VirtualHost>
Explanation: Listen on all requests to the local machine's port 80. If I requested "http://something.com/somethingorother
", forward that request to "http://localhost:8080/somethingorother
". This should work for an external visitor because, according to the docs, it maps the remote request to the local server's space.
I'm running Apache 2.4.6-2ubuntu2.2, so I'm not sure how the "-2ubuntu2.2" affects the wider applicability of this answer.
After you make these changes, add the needed modules and restart apache
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
How to override !important?
Overriding the !important modifier
- Simply add another CSS rule with
!important
, and give the selector a higher specificity (adding an additional tag, id or class to the selector)
- add a CSS rule with the same selector at a later point than the existing one (in a tie, the last one defined wins).
Some examples with a higher specificity (first is highest/overrides, third is lowest):
table td {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}
Or add the same selector after the existing one:
td {height: 50px !important;}
Disclaimer:
It's almost never a good idea to use !important
. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important
modifiers to override it, and it limits the options for overriding it via JavaScript.
But, it's useful to know how to override it, if you sometimes have to.
Interfaces — What's the point?
Interfaces are for applying connection between different classes. for example, you have a class for car and a tree;
public class Car { ... }
public class Tree { ... }
you want to add a burnable functionality for both classes. But each class have their own ways to burn. so you simply make;
public class Car : IBurnable
{
public void Burn() { ... }
}
public class Tree : IBurnable
{
public void Burn() { ... }
}
ReactJS: Maximum update depth exceeded error
that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on
this line at your code
{<td><span onClick={this.toggle()}>Details</span></td>}
you need to make onClick
refer to this.toggle
not calling it
to fix the issue do this
{<td><span onClick={this.toggle}>Details</span></td>}
'list' object has no attribute 'shape'
firstly u have to import numpy library (refer code for making a numpy array)
shape
only gives the output only if the variable is attribute of numpy library .in other words it must be a np.array or any other data structure of numpy.
Eg.
`>>> import numpy
>>> a=numpy.array([[1,1],[1,1]])
>>> a.shape
(2, 2)`
how to use html2canvas and jspdf to export to pdf in a proper and simple way
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
Cannot make a static reference to the non-static method
There are some good answers already with explanations of why the mixture of the non-static Context
method getText()
can't be used with your static final String
.
A good question to ask is: why do you want to do this? You are attempting to load a String
from your strings
resource, and populate its value into a public static
field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context
into your other classes and call context.getText(R.string.TTT)
from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity
:
NonActivity.doStuff(this);
This will allow you to access your String
resource without needing to use a public static
field.
How to retrieve checkboxes values in jQuery
function updateTextArea() {
var allVals = $('#c_b :checked').map(function() {
return $(this).val();
}).get();
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Selecting fields from JSON output
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
Why is the minidlna database not being refreshed?
MiniDLNA uses inotify
, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.
The notify_interval
(notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval
(ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify
functionality.
This is how it looks in my /etc/minidlna.conf
:
# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes
Make sure that inotify is enabled in your kernel.
If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.
Proper usage of Optional.ifPresent()
You can use method reference like this:
user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);
Method ifPresent()
get Consumer
object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user
.
Or if this method doSomethingWithUser
is in the User
class and it is not static
, you can use method reference like this:
user.ifPresent(this::doSomethingWithUser);
How can I display a pdf document into a Webview?
Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.
Solution after API 21
Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap.
I've never used it but is seems easy enough.
Solution for any api level
Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.
Use this code to download and open the PDF
public class PdfOpenHelper {
public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
Observable.fromCallable(new Callable<File>() {
@Override
public File call() throws Exception {
try{
URL url = new URL(pdfUrl);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
File dir = new File(activity.getFilesDir(), "/shared_pdf");
dir.mkdir();
File file = new File(dir, "temp.pdf");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<File>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(File file) {
String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);
Intent shareIntent = new Intent(Intent.ACTION_VIEW);
shareIntent.setDataAndType(uriToFile, "application/pdf");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(shareIntent);
}
}
});
}
}
For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.
Here is how you implement it:
In your Manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Finally create a file_paths.xml file in the resources foler
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="shared_pdf" path="shared_pdf"/>
</paths>
Hope this helps =)
How do I plot in real-time in a while loop using matplotlib?
show
is probably not the best choice for this. What I would do is use pyplot.draw()
instead. You also might want to include a small time delay (e.g., time.sleep(0.05)
) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at a time.
Python object.__repr__(self) should be an expression?
It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction
class that contains two integers, a numerator and denominator, your __repr__()
method would look like this:
# in the definition of Fraction class
def __repr__(self):
return "Fraction(%d, %d)" % (self.numerator, self.denominator)
Assuming that the constructor takes those two values.
Change div height on button click
Look at to vwphillips' post from 03-06-2010, 03:35 PM in
http://www.codingforums.com/archive/index.php/t-190887.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function Div(id,ud) {
var div=document.getElementById(id);
var h=parseInt(div.style.height)+ud;
if (h>=1){
div.style.height = h + "em"; // I'm using "em" instead of "px", but you can use px like measure...
}
}
</script>
</head>
<body>
<div>
<input type="button" value="+" onclick="Div('my_div', 1);">
<input type="button" value="-" onclick="Div('my_div', -1);"></div>
</div>
<div id="my_div" style="height: 1em; width: 1em; overflow: auto;"></div>
</body>
</html>
This worked for me :)
Best regards!
TABLOCK vs TABLOCKX
Big difference, TABLOCK
will try to grab "shared" locks, and TABLOCKX
exclusive locks.
If you are in a transaction and you grab an exclusive lock on a table, EG:
SELECT 1 FROM TABLE WITH (TABLOCKX)
No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.
TABLOCK
only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED
(default). If your isolation level is higher, for example: SERIALIZABLE
, shared locks are held until the end of a transaction.
Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK
). However, if transaction A
holds a shared lock on a table, transaction B
will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.
Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).
In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.
In general you would not use TABLOCK
or TABLOCKX
unless you absolutely needed it for some edge case.
"git rm --cached x" vs "git reset head --? x"?
There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.
When you do something like git add file
you add it to the index. And when you commit it, you add it to the tree as well.
It will probably help you to know the three more common flags in git reset
:
git reset [--<mode>
] [<commit>
]
This form resets the current branch head to <commit>
and possibly
updates the index (resetting it to the tree of <commit>
) and the
working tree depending on <mode>
, which must be one of the
following:
--soft
Does not touch the index file nor the working tree at all (but resets
the head to <commit>
, just like all modes do). This leaves all your
changed files "Changes to be committed", as git status would put it.
--mixed
Resets the index but not the working tree (i.e., the changed files
are preserved but not marked for commit) and reports what has not been
updated. This is the default action.
--hard
Resets the index and working tree. Any changes to tracked files in
the working tree since <commit>
are discarded.
Now, when you do something like git reset HEAD
, what you are actually doing is git reset HEAD --mixed
and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add
). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add
was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD
is the exact opposite of git add
.
git rm
, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached
, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add
was used to add a new (previously untracked) file, then git rm --cached
is the exact opposite of git add
(and is pretty much identical to git reset HEAD
).
Git 2.25 introduced a new command for these cases, git restore
, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.
C++ Boost: undefined reference to boost::system::generic_category()
You could come across another problem. After installing Boost on the Linux Mint I've had the same problem. Linking -lboost_system
or -lboost_system-mt
haven't worked because library have had name libboost_system.so.1.54.0
.
So the solution is to create symbolic link to the original file. In my case
sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.54.0 /usr/lib/libboost_system.so
For more information see this question.
Bundling data files with PyInstaller (--onefile)
Slight modification to the accepted answer.
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
Why can't decimal numbers be represented exactly in binary?
you know integer numbers right? each bit represent 2^n
2^4=16
2^3=8
2^2=4
2^1=2
2^0=1
well its the same for floating point(with some distinctions) but the bits represent 2^-n
2^-1=1/2=0.5
2^-2=1/(2*2)=0.25
2^-3=0.125
2^-4=0.0625
Floating point binary representation:
sign Exponent Fraction(i think invisible 1 is appended to the fraction )
B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0
PHPMyAdmin Default login password
I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )
Anyway, coming to the solution, this is what I was required to do:
su -
gedit /etc/phpMyAdmin/config.inc.php
if not found... try phpmyadmin - all small caps.
gedit /etc/phpmyadmin/config.inc.php
Locate
$cfg['Servers'][$i]['AllowNoPassword']
and set it to:
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
Save it.
PHP compare two arrays and get the matched values not the difference
OK.. We needed to compare a dynamic number of product names...
There's probably a better way... but this works for me...
... because....Strings are just Arrays of characters.... :>}
// Compare Strings ... Return Matching Text and Differences with Product IDs...
// From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";
$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";
$ProductNames = array(
$productID1 => $productName1,
$productID2 => $productName2
);
function compareNames($ProductNames){
// Convert NameStrings to Arrays...
foreach($ProductNames as $id => $product_name){
$Package1[$id] = explode(" ",$product_name);
}
// Get Matching Text...
$Matching = call_user_func_array('array_intersect', $Package1 );
$MatchingText = implode(" ",$Matching);
// Get Different Text...
foreach($Package1 as $id => $product_name_chunks){
$Package2 = array($product_name_chunks,$Matching);
$diff = call_user_func_array('array_diff', $Package2 );
$DifferentText[$id] = trim(implode(" ", $diff));
}
$results[$MatchingText] = $DifferentText;
return $results;
}
$Results = compareNames($ProductNames);
print_r($Results);
// Gives us this...
[EcoPlus Premio Jet]
[abc123] => 600
[xyz789] => 800
How can I get the number of days between 2 dates in Oracle 11g?
Or you could have done this:
select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') from dual
This returns a NUMBER of whole days:
SQL> create view v as
2 select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') diff
3 from dual;
View created.
SQL> select * from v;
DIFF
----------
29
SQL> desc v
Name Null? Type
---------------------- -------- ------------------------
DIFF NUMBER(38)
What difference does .AsNoTracking() make?
The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.
git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up
I had the same issue. But in my case it was due to my branch's name. The branch's name automatically set in my GitHub repo as main instead of master.
git pull origin master (did not work).
I confirmed in GitHub if the name of the branch was actually master and found the the actual name was main. so the commands below worked for me.
git pull origin main
On design patterns: When should I use the singleton?
On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.
One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.
Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."
I'm sure there are other valid reasons as well. Alex Miller, in "Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices.
Read more at Singleton I love you, but you're bringing me down.
jQuery send HTML data through POST
If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).
Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
This function will convert in both directions:
12 to 24 hour or 24 to 12 hour
function toggle24hr(time, onoff){
if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
time[0] = Number(time[0])
if(onoff){//convert to 24 hour:
if((pm && time[0]!=12)) time[0] += 12
else if(!pm && time[0]==12) time[0] = '00' //handle midnight
if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
}else{ //convert to 12 hour:
pm = time[0]>=12
if(!time[0]) time[0]=12 //handle midnight
else if(pm && time[0]!=12) time[0] -= 12
}
return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}
Here's some examples:
//convert to 24 hour:
toggle24hr('12:00am') //returns 00:00
toggle24hr('2:00pm') //returns 14:00
toggle24hr('8:00am') //returns 08:00
toggle24hr('12:00pm') //returns 12:00
//convert to 12 hour:
toggle24hr('14:00') //returns 2:00pm
toggle24hr('08:00') //returns 8:00am
toggle24hr('12:00') //returns 12:00pm
toggle24hr('00:00') //returns 12:00am
//you can also force a specific format like this:
toggle24hr('14:00',1) //returns 14:00
toggle24hr('14:00',0) //returns 2:00pm
RuntimeWarning: invalid value encountered in divide
To prevent division by zero you could pre-initialize the output 'out' where the div0 error happens, eg np.where
does not cut it since the complete line is evaluated regardless of condition.
example with pre-initialization:
a = np.arange(10).reshape(2,5)
a[1,3] = 0
print(a) #[[0 1 2 3 4], [5 6 7 0 9]]
a[0]/a[1] # errors at 3/0
out = np.ones( (5) ) #preinit
np.divide(a[0],a[1], out=out, where=a[1]!=0) #only divide nonzeros else 1
javax.persistence.NoResultException: No entity found for query
You mentioned getting the result list from the Query, since you don't know that there is a UniqueResult (hence the exception) you could use list and check the size?
if (query.list().size() == 1)
Since you're not doing a get() to get your unique object a query will be executed whether you call uniqueResult or list.
How to align linearlayout to vertical center?
Change orientation and gravity in
<LinearLayout
android:id="@+id/groupNumbers"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_weight="0.7"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
to
android:orientation="vertical"
android:layout_gravity="center_vertical"
You are adding orientation: horizontal, so the layout will contain all elements in single horizontal line. Which won't allow you to get the element in center.
Hope this helps.
Is putting a div inside an anchor ever correct?
You can't put <div>
inside <a>
- it's not valid (X)HTML.
Even though you style a span with display: block you still can't put block-level elements inside it: the (X)HTML still has to obey the (X)HTML DTD (whichever one you use), no matter how the CSS alters things.
The browser will probably display it as you want, but that doesn't make it right.
Vertical Alignment of text in a table cell
td.description {vertical-align: top;}
where description
is the class name of the td
with that text in it
_x000D_
_x000D_
td.description {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_
OR inline (yuk!)
_x000D_
_x000D_
<td style="vertical-align: top;">Description</td>
_x000D_
_x000D_
_x000D_
How can I replace newline or \r\n with <br/>?
nl2br()
as you have it should work fine:
$description = nl2br($description);
It's more likely that the unclosed '
on the first line of your example code is causing your issue. Remove the ' after $description...
...$description');
Maven: How to rename the war file for the project?
You need to configure the war plugin:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>bird.war</warName>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
More info here
Set line spacing
lineSpacing is used in React Native (or native mobile apps).
For web you can use letterSpacing
(or letter-spacing
)
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How do I deal with corrupted Git object files?
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
How to determine if OpenSSL and mod_ssl are installed on Apache2
Usually, when you compile your apache2 server (or install it by packages facility stuff), you can check any directive that're available to be used by tapping this command:
~# $(which httpd) -L | grep SSL # on RHEL/CentOS/Fedora
~# $(which apache2) -L | grep SSL # on Ubuntu/Debian
If you don't see any SSL* directive, it means that you don't have apache2 with mod_ssl compiled.
Hopes it helps ;)
IsNumeric function in c#
Is numeric can be achieved via many ways, but i use my way
public bool IsNumeric(string value)
{
bool isNumeric = true;
char[] digits = "0123456789".ToCharArray();
char[] letters = value.ToCharArray();
for (int k = 0; k < letters.Length; k++)
{
for (int i = 0; i < digits.Length; i++)
{
if (letters[k] != digits[i])
{
isNumeric = false;
break;
}
}
}
return isNumeric;
}
How do I create a user account for basic authentication?
Unfortunatelly, for IIS installed on Windows 7/8 machines, there is no option to create users only for IIS authentification.
For Windows Server there is that option where you can add users from IIS Manager UI. These users have roles only on IIS, but not for the rest of the system.
In this article it shows how you add users, but it is incorrect stating that is also appliable to standard OS, it only applies to server versions.
How can I get phone serial number (IMEI)
public String getIMEI(Context context){
TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
String imei = mngr.getDeviceId();
return imei;
}
How can I convert a std::string to int?
What about Boost.Lexical_cast?
Here is their example:
The following example treats command line arguments as a sequence of numeric data:
int main(int argc, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
...
}
Quick Sort Vs Merge Sort
Quicksort is in place. You need very little extra memory. Which is extremely important.
Good choice of median makes it even more efficient but even a bad choice of median quarantees Theta(nlogn).
asp:TextBox ReadOnly=true or Enabled=false?
If a control is disabled
it cannot be edited and its content is excluded when the form is submitted.
If a control is readonly
it cannot be edited, but its content (if any) is still included with the submission.
How can I know if a branch has been already merged into master?
Use git merge-base <commit> <commit>
.
This command finds best common ancestor(s) between two commits. And if the common ancestor is identical to the last commit of a "branch" ,then we can safely assume that that a "branch" has been already merged into the master.
Here are the steps
- Find last commit hash on master branch
- Find last commit hash on a "branch"
- Run command
git merge-base <commit-hash-step1> <commit-hash-step2>
.
- If output of step 3 is same as output of step 2, then a "branch" has been already merged into master.
More info on git merge-base https://git-scm.com/docs/git-merge-base.
Unable to allocate array with shape and data type
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
Is there a replacement for unistd.h for Windows (Visual C)?
I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h
header you are looking for.
The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.
How to make button fill table cell
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Android Recyclerview GridLayoutManager column spacing
This will work for RecyclerView
with header as well.
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
private int headerNum;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge, int headerNum) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
this.headerNum = headerNum;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view) - headerNum; // item position
if (position >= 0) {
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
} else {
outRect.left = 0;
outRect.right = 0;
outRect.top = 0;
outRect.bottom = 0;
}
}
}
}
How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?
The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:
perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt
Note that this sends the Unixified version of the file to stdout. If you want to replace the file with a Unixified version, add perl's -i
flag.
Get error message if ModelState.IsValid fails?
It is sample extension
public class GetModelErrors
{
//Usage return Json to View :
//return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
public class KeyMessages
{
public string Key { get; set; }
public string Message { get; set; }
}
private readonly ModelStateDictionary _entry;
public GetModelErrors(ModelStateDictionary entry)
{
_entry = entry;
}
public int Count()
{
return _entry.ErrorCount;
}
public string Exceptions(string sp = "\n")
{
return string.Join(sp, _entry.Values
.SelectMany(v => v.Errors)
.Select(e => e.Exception));
}
public string Messages(string sp = "\n")
{
string msg = string.Empty;
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
}
}
return msg;
}
public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
{
List<KeyMessages> list = new List<KeyMessages>();
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
list.Add(new KeyMessages
{
Key = item.Key,
Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
});
}
}
return list;
}
}
How to negate 'isblank' function
I suggest:
=not(isblank(A1))
which returns TRUE if A1 is populated and FALSE otherwise. Which compares with:
=isblank(A1)
which returns TRUE if A1 is empty and otherwise FALSE.
Mocking static methods with Mockito
Use PowerMockito on top of Mockito.
Example code:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {
@Test
public void shouldVerifyParameters() throws Exception {
//given
PowerMockito.mockStatic(DriverManager.class);
BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
//when
sut.execute(); // System Under Test (sut)
//then
PowerMockito.verifyStatic();
DriverManager.getConnection(...);
}
More information:
Importing packages in Java
Here is the right way to do imports in Java.
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes.
If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.
omp parallel vs. omp parallel for
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0
and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
Adding horizontal spacing between divs in Bootstrap 3
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
How to echo with different colors in the Windows command line
Setting color to the log statements in powershell is not a big deal friend.
you can use -ForegroundColor
parameter.
To write a confirmation message.
Write-Host "Process executed Successfully...." -ForegroundColor Magenta
To write an error message.
Write-Host "Sorry an unexpected error occurred.." -ForegroundColor Red
To write a progress message.
Write-Host "Working under pocess..." -ForegroundColor Green
Injection of autowired dependencies failed;
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
Trying to get property of non-object in
Your error
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
Your comment
@22 is <?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
Changing PowerShell's default output encoding to UTF-8
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
Optional reading: The cross-platform perspective: PowerShell Core:
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
- This works fine on PowerShell Core.
- It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
- This may not always be a problem, but definitely can be, such as when you try to read a file into a string in
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.
Inconsistent default encoding behavior in Windows PowerShell:
Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
Grant all on a specific schema in the db to a group role in PostgreSQL
My answer is similar to this one on ServerFault.com.
To Be Conservative
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
Access to the Schema
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
Existing Objects Versus Future
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
How to check the gradle version in Android Studio?
I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:
(left pane must be in project view, not android for this path)
app->gradle->wrapper->gradle-wrapper.properties
it has a line like this, indicating the gradle version:
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip
There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)
val() vs. text() for textarea
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
What's the difference between display:inline-flex and display:flex?
Open in Full page for better understanding
_x000D_
_x000D_
.item {_x000D_
width : 100px;_x000D_
height : 100px;_x000D_
margin: 20px;_x000D_
border: 1px solid blue;_x000D_
background-color: yellow;_x000D_
text-align: center;_x000D_
line-height: 99px;_x000D_
}_x000D_
_x000D_
.flex-con {_x000D_
flex-wrap: wrap;_x000D_
/* <A> */_x000D_
display: flex;_x000D_
/* 1. uncomment below 2 lines by commenting above 1 line */_x000D_
/* <B> */_x000D_
/* display: inline-flex; */_x000D_
_x000D_
}_x000D_
_x000D_
.label {_x000D_
padding-bottom: 20px;_x000D_
}_x000D_
.flex-inline-play {_x000D_
padding: 20px;_x000D_
border: 1px dashed green;_x000D_
/* <C> */_x000D_
width: 1000px;_x000D_
/* <D> */_x000D_
display: flex;_x000D_
}
_x000D_
<figure>_x000D_
<blockquote>_x000D_
<h1>Flex vs inline-flex</h1>_x000D_
<cite>This pen is understand difference between_x000D_
flex and inline-flex. Follow along to understand this basic property of css</cite>_x000D_
<ul>_x000D_
<li>Follow #1 in CSS:_x000D_
<ul>_x000D_
<li>Comment <code>display: flex</code></li>_x000D_
<li>Un-comment <code>display: inline-flex</code></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
Hope you would have understood till now. This is very similar to situation of `inline-block` vs `block`. Lets go beyond and understand usecase to apply learning. Now lets play with combinations of A, B, C & D by un-commenting only as instructed:_x000D_
<ul>_x000D_
<li>A with D -- does this do same job as <code>display: inline-flex</code>. Umm, you may be right, but not its doesnt do always, keep going !</li>_x000D_
<li>A with C</li>_x000D_
<li>A with C & D -- Something wrong ? Keep going !</li>_x000D_
<li>B with C</li>_x000D_
<li>B with C & D -- Still same ? Did you learn something ? inline-flex is useful if you have space to occupy in parent of 2 flexboxes <code>.flex-con</code>. That's the only usecase</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</blockquote>_x000D_
_x000D_
</figure>_x000D_
<br/>_x000D_
<div class="label">Playground:</div>_x000D_
<div class="flex-inline-play">_x000D_
<div class="flex-con">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
</div>_x000D_
<div class="flex-con">_x000D_
<div class="item">X</div>_x000D_
<div class="item">Y</div>_x000D_
<div class="item">Z</div>_x000D_
<div class="item">V</div>_x000D_
<div class="item">W</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
MongoDB vs Firebase
Firebase is designed for real-time updates. It easily integrates with angular. Both are NoSQL databases. MongoDB can also do this with Angular through Socket.io integration. Meteor.js also makes use of MongoDB with an open socket connection for real-time updates.
MongoDB can be run locally, or hosted on many different cloud based providers. Firebase, in my opinion is great for smaller apps, very quick to get up and running. MongoDB is ideal for more robust larger apps, real-time integration is possible but it takes a bit more work.