Prevent text selection after double click
Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me.
Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":
$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});
HTH !
What is the --save option for npm install?
Update as of npm 5:
As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.
Original answer:
It won't do anything if you don't have a package.json
file. Start by running npm init
to create one. Then calls to npm install --save
or npm install --save-dev
or npm install --save-optional
will update the package.json
to list your dependencies.
How do I select elements of an array given condition?
Actually I would do it this way:
L1 is the index list of elements satisfying condition 1;(maybe you can use somelist.index(condition1)
or np.where(condition1)
to get L1.)
Similarly, you get L2, a list of elements satisfying condition 2;
Then you find intersection using intersect(L1,L2)
.
You can also find intersection of multiple lists if you get multiple conditions to satisfy.
Then you can apply index in any other array, for example, x.
Visual Studio Code Search and Replace with Regular Expressions
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
start/play embedded (iframe) youtube-video on click of an image
To start video
var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);
To stop video
var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);
You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters
works for both vimeo and youtube on FF & Chrome
AttributeError: 'module' object has no attribute 'model'
I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.
Difference between Width:100% and width:100vw?
You can solve this issue be adding max-width
:
#element {
width: 100vw;
height: 100vw;
max-width: 100%;
}
When you using CSS to make the wrapper full width using the code width: 100vw;
then you will notice a horizontal scroll in the page, and that happened because the padding
and margin
of html
and body
tags added to the wrapper size, so the solution is to add max-width: 100%
Cast object to interface in TypeScript
Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:
export function forceCast<T>(input: any): T {
// ... do runtime checks here
// @ts-ignore <-- forces TS compiler to compile this as-is
return input;
}
Then you can use it to force cast objects to a certain type:
import { forceCast } from './forceCast';
const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);
Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts
interface files into JSON schemas and using ajv
to validate in runtime.
Is Safari on iOS 6 caching $.ajax results?
I was able to fix my problem by using a combination of $.ajaxSetup and appending a timestamp to the url of my post (not to the post parameters/body). This based on the recommendations of previous answers
$(document).ready(function(){
$.ajaxSetup({ type:'POST', headers: {"cache-control","no-cache"}});
$('#myForm').submit(function() {
var data = $('#myForm').serialize();
var now = new Date();
var n = now.getTime();
$.ajax({
type: 'POST',
url: 'myendpoint.cfc?method=login&time='+n,
data: data,
success: function(results){
if(results.success) {
window.location = 'app.cfm';
} else {
console.log(results);
alert('login failed');
}
}
});
});
});
Adding JPanel to JFrame
Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);
Are you sure of this? test
is NOT a component!
To do what you're trying to do you should let Test2
extend JPanel
!
Converting a sentence string to a string array of words in Java
String.split() will do most of what you want. You may then need to loop over the words to pull out any punctuation.
For example:
String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
// You may want to check for a non-word character before blindly
// performing a replacement
// It may also be necessary to adjust the character class
words[i] = words[i].replaceAll("[^\\w]", "");
}
Should I return EXIT_SUCCESS or 0 from main()?
Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.
How to split a data frame?
The answer you want depends very much on how and why you want to break up the data frame.
For example, if you want to leave out some variables, you can create new data frames from specific columns of the database. The subscripts in brackets after the data frame refer to row and column numbers. Check out Spoetry for a complete description.
newdf <- mydf[,1:3]
Or, you can choose specific rows.
newdf <- mydf[1:3,]
And these subscripts can also be logical tests, such as choosing rows that contain a particular value, or factors with a desired value.
What do you want to do with the chunks left over? Do you need to perform the same operation on each chunk of the database? Then you'll want to ensure that the subsets of the data frame end up in a convenient object, such as a list, that will help you perform the same command on each chunk of the data frame.
Redis strings vs Redis hashes to represent JSON: efficiency?
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Overall Summary
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
"cannot resolve symbol R" in Android Studio
Simply defining an app namespace in your xml file can cause this. This was a completely innocuous line that only selected out one symbol (out of many) to make unresolved. Simply removing the entire line, greyed in the pic below, enabled my code to reference to unresolved symbol. Even when I added the line back it decided to build without problem. Go figure.
How do I run a Python program in the Command Prompt in Windows 7?
So after 30 min of R&D i realized that after setup the PATH at environment variable
i.e.
" C:\Python/27; "
just restart
now open cmd :
C:> cd Python27
C:\ Python27> python.exe
USE python.exe with extension
alternative option is :
if the software is installed properly directly run Python program, your command line screen will automatically appear without cmd.
Thanks.
When to use "ON UPDATE CASCADE"
A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE
can be useful. Take a look at this example (PostgreSQL):
CREATE TABLE club
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE band
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE concert
(
key SERIAL PRIMARY KEY,
club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
concert_date DATE
);
In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE
was the key to solve the problem.
Will iOS launch my app into the background if it was force-quit by the user?
You can change your target's launch settings in "Manage Scheme" to Wait for <app>.app to be launched manually
, which allows you debug by setting a breakpoint in application: didReceiveRemoteNotification: fetchCompletionHandler:
and sending the push notification to trigger the background launch.
I'm not sure it'll solve the issue, but it may assist you with debugging for now.
How to see my Eclipse version?
Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below
Calling the base constructor in C#
class Exception
{
public Exception(string message)
{
[...]
}
}
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
: base(message)
{
[...]
}
}
jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027
see http://www.utf8-chartable.de/ for all of them
edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.
Make Vim show ALL white spaces as a character
To highlight spaces, just search for it:
/<space>
Notes:
<space> means just type the space character.
Enable highlighting of search results with :set hlsearch
To highlight spaces & tabs:
/[<space><tab>]
A quick way to remove the highlights is to search for anything else:
/asdf
(just type any short list of random characters)
C++11 reverse range-based for-loop
Actually, in C++14 it can be done with a very few lines of code.
This is a very similar in idea to @Paul's solution. Due to things missing from C++11, that solution is a bit unnecessarily bloated (plus defining in std smells). Thanks to C++14 we can make it a lot more readable.
The key observation is that range-based for-loops work by relying on begin()
and end()
in order to acquire the range's iterators. Thanks to ADL, one doesn't even need to define their custom begin()
and end()
in the std:: namespace.
Here is a very simple-sample solution:
// -------------------------------------------------------------------
// --- Reversed iterable
template <typename T>
struct reversion_wrapper { T& iterable; };
template <typename T>
auto begin (reversion_wrapper<T> w) { return std::rbegin(w.iterable); }
template <typename T>
auto end (reversion_wrapper<T> w) { return std::rend(w.iterable); }
template <typename T>
reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; }
This works like a charm, for instance:
template <typename T>
void print_iterable (std::ostream& out, const T& iterable)
{
for (auto&& element: iterable)
out << element << ',';
out << '\n';
}
int main (int, char**)
{
using namespace std;
// on prvalues
print_iterable(cout, reverse(initializer_list<int> { 1, 2, 3, 4, }));
// on const lvalue references
const list<int> ints_list { 1, 2, 3, 4, };
for (auto&& el: reverse(ints_list))
cout << el << ',';
cout << '\n';
// on mutable lvalue references
vector<int> ints_vec { 0, 0, 0, 0, };
size_t i = 0;
for (int& el: reverse(ints_vec))
el += i++;
print_iterable(cout, ints_vec);
print_iterable(cout, reverse(ints_vec));
return 0;
}
prints as expected
4,3,2,1,
4,3,2,1,
3,2,1,0,
0,1,2,3,
NOTE std::rbegin()
, std::rend()
, and std::make_reverse_iterator()
are not yet implemented in GCC-4.9. I write these examples according to the standard, but they would not compile in stable g++. Nevertheless, adding temporary stubs for these three functions is very easy. Here is a sample implementation, definitely not complete but works well enough for most cases:
// --------------------------------------------------
template <typename I>
reverse_iterator<I> make_reverse_iterator (I i)
{
return std::reverse_iterator<I> { i };
}
// --------------------------------------------------
template <typename T>
auto rbegin (T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
// const container variants
template <typename T>
auto rbegin (const T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (const T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
Using Jquery Datatable with AngularJs
Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.
Another good option is ng-grid http://angular-ui.github.io/ng-grid/.
And there's a beta version (http://ui-grid.info/) available already with some improvements:
- Native AngularJS implementation, no jQuery
- Performs well with large data sets; even 10,000+ rows
- Plugin architecture allows you to use only the features you need
UPDATE:
It seems UI GRID is not beta anymore.
With the 3.0 release, the repository has been renamed from "ng-grid"
to "ui-grid".
Windows-1252 to UTF-8 encoding
If you are sure your files are either UTF-8 or Windows 1252 (or Latin1), you can take advantage of the fact that recode will exit with an error if you try to convert an invalid file.
While utf8 is valid Win-1252, the reverse is not true: win-1252 is NOT valid UTF-8. So:
recode utf8..utf16 <unknown.txt >/dev/null || recode cp1252..utf8 <unknown.txt >utf8-2.txt
Will spit out errors for all cp1252 files, and then proceed to convert them to UTF8.
I would wrap this into a cleaner bash script, keeping a backup of every converted file.
Before doing the charset conversion, you may wish to first ensure you have consistent line-endings in all files. Otherwise, recode will complain because of that, and may convert files which were already UTF8, but just had the wrong line-endings.
How to use cURL in Java?
The Runtime object allows you to execute external command line applications from Java and would therefore allow you to use cURL however as the other answers indicate there is probably a better way to do what you are trying to do. If all you want to do is download a file the URL object will work great.
Simultaneously merge multiple data.frames in a list
When you have a list of dfs, and a column contains the "ID", but in some lists, some IDs are missing, then you may use this version of Reduce / Merge in order to join multiple Dfs of missing Row Ids or labels:
Reduce(function(x, y) merge(x=x, y=y, by="V1", all.x=T, all.y=T), list_of_dfs)
How to calculate moving average without keeping the count and data-total?
The answer of Flip is computationally more consistent than the Muis one.
Using double number format, you could see the roundoff problem in the Muis approach:
When you divide and subtract, a roundoff appears in the previous stored value, changing it.
However, the Flip approach preserves the stored value and reduces the number of divisions, hence, reducing the roundoff, and minimizing the error propagated to the stored value. Adding only will bring up roundoffs if there is something to add (when N is big, there is nothing to add)
Those changes are remarkable when you make a mean of big values tend their mean to zero.
I show you the results using a spreadsheet program:
Firstly, the results obtained:
The A and B columns are the n and X_n values, respectively.
The C column is the Flip approach, and the D one is the Muis approach, the result stored in the mean. The E column corresponds with the medium value used in the computation.
A graph showing the mean of even values is the next one:
As you can see, there is big differences between both approachs.
Adding a color background and border radius to a Layout
You don't need the separate fill item. In fact, it's invalid. You just have to add a solid
block to the shape
. The subsequent stroke
draws on top of the solid
:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="1dip"
android:color="@color/bggrey" />
</shape>
You also don't need the layer-list
if you only have one shape
.
Find the most popular element in int[] array
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
How to set Java environment path in Ubuntu
if you have intalled only openJDK, the you should update your links, because you can have some OpenJDK intallation.
sudo update-alternatives --config java
after this
$gedit ~/.bashrc
add the following line in the file
JAVA_HOME=/usr/lib/jvm/YOUR_JAVA_VERSION
export PATH=$PATH:$JAVA_HOME/bin
export JAVA_HOME
you can get you java version with
java -version
Variables within app.config/web.config
A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your app.config
/ web.config
file, you can have this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section must be the first section within the <configuration> node -->
<configSections>
<section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
</configSections>
<DirectoryInfo>
<Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
</DirectoryInfo>
</configuration>
Then, in your .NET code (I'll use C# in my example), you can create two classes like this:
using System;
using System.Configuration;
namespace MyProjectNamespace {
public class DirectoryInfoConfigSection : ConfigurationSection {
[ConfigurationProperty("Directory")]
public DirectoryConfigElement Directory {
get {
return (DirectoryConfigElement)base["Directory"];
}
}
public class DirectoryConfigElement : ConfigurationElement {
[ConfigurationProperty("MyBaseDir")]
public String BaseDirectory {
get {
return (String)base["MyBaseDir"];
}
}
[ConfigurationProperty("Dir1")]
public String Directory1 {
get {
return (String)base["Dir1"];
}
}
[ConfigurationProperty("Dir2")]
public String Directory2 {
get {
return (String)base["Dir2"];
}
}
// You can make custom properties to combine your directory names.
public String Directory1Resolved {
get {
return System.IO.Path.Combine(BaseDirectory, Directory1);
}
}
}
}
Finally, in your program code, you can access your app.config
variables, using your new classes, in this manner:
DirectoryInfoConfigSection config =
(DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved; // This value will equal "C:\MyBase\Dir1"
Convert pyQt UI to python
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
Setting Android Theme background color
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
Split Spark Dataframe string column into multiple columns
Here's another approach, in case you want split a string with a delimiter.
import pyspark.sql.functions as f
df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
| value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+
df_split = df.select(f.split(df.value,":")).rdd.flatMap(
lambda x: x).toDF(schema=["col1","col2","col3"])
df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
| 1| a|2001|
| 2| b|2002|
| 3| c|2003|
+----+----+----+
I don't think this transition back and forth to RDDs is going to slow you down...
Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.
Assigning strings to arrays of characters
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject
, and AssignObject
. When the compiler sees thing = value
, it looks at the context and calls one InitializeObject
if you're making a new thing
. If you're not, it instead calls AssignObject
.
Normally this is fine as InitializeObject
and AssignObject
usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
List<object>.RemoveAll - How to create an appropriate Predicate
A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.
{
List<Vehicle> vehicles;
// Using a lambda
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
// Using an equivalent anonymous method
vehicles.RemoveAll(delegate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
});
// Using an equivalent actual method
vehicles.RemoveAll(VehiclePredicate);
}
private static bool VehiclePredicate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
}
Deprecated meaning?
The simplest answer to the meaning of deprecated
when used to describe software APIs is:
- Stop using APIs marked as deprecated!
- They will go away in a future release!!
- Start using the new versions ASAP!!!
How to Delete node_modules - Deep Nested Folder in Windows
I've simply done that by using Winrar, this may seem a strange solution but working very well.
- right click on
node_modules
folder
- select
Add to archive ...
from the menu.
- Winrar dialog opens
- just check the option
delete files after archiving
- Don't forget to delete the node_modules.rar after finished.
[UPDATE]
This also works with 7Zip
pandas how to check dtype for all columns in a dataframe?
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
How to find largest objects in a SQL Server database?
You may also use the following code:
USE AdventureWork
GO
CREATE TABLE #GetLargest
(
table_name sysname ,
row_count INT,
reserved_size VARCHAR(50),
data_size VARCHAR(50),
index_size VARCHAR(50),
unused_size VARCHAR(50)
)
SET NOCOUNT ON
INSERT #GetLargest
EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT
a.table_name,
a.row_count,
COUNT(*) AS col_count,
a.data_size
FROM #GetLargest a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC
DROP TABLE #GetLargest
Does reading an entire file leave the file handle open?
Instead of retrieving the file content as a single string,
it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover,
this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Can I store images in MySQL
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
Ex:
CREATE TABLE 'test'.'pic' (
'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'caption' VARCHAR(45) NOT NULL,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('idpic')
)
As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.
How to insert DECIMAL into MySQL database
MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.
The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.
Thus, (4,2)
can be anything from -99.99
to 99.99
.
As for why you're getting 99.99
instead of the desired 3.80
, the value you're inserting must be interpreted as larger than 99.99
, so the max value is used. Maybe you could post the code that you are using to insert or update the table.
Edit
Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.
Use of document.getElementById in JavaScript
Consider
var x = document.getElementById("age");
Here x
is the element with id="age"
.
Now look at the following line
var age = document.getElementById("age").value;
this means you are getting the value of the element which has id="age"
What is the => assignment in C# in a property signature
For the following statement shared by Alex Booker in their answer
When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:
Please see the following screenshot, it shows how this statement (using SharpLab link)
public string APIBasePath => Configuration.ToolsAPIBasePath;
converts to
public string APIBasePath
{
get
{
return Configuration.ToolsAPIBasePath;
}
}
Screenshot:
SQL split values to multiple rows
The original question was for MySQL and SQL in general. The example below is for the new versions of MySQL. Unfortunately, a generic query that would work on any SQL server is not possible. Some servers do no support CTE, others do not have substring_index, yet others have built-in functions for splitting a string into multiple rows.
--- the answer follows ---
Recursive queries are convenient when the server does not provide built-in functionality. They can also be the bottleneck.
The following query was written and tested on MySQL version 8.0.16. It will not work on version 5.7-. The old versions do not support Common Table Expression (CTE) and thus recursive queries.
with recursive
input as (
select 1 as id, 'a,b,c' as names
union
select 2, 'b'
),
recurs as (
select id, 1 as pos, names as remain, substring_index( names, ',', 1 ) as name
from input
union all
select id, pos + 1, substring( remain, char_length( name ) + 2 ),
substring_index( substring( remain, char_length( name ) + 2 ), ',', 1 )
from recurs
where char_length( remain ) > char_length( name )
)
select id, name
from recurs
order by id, pos;
Max parallel http connections in a browser?
Max Number of default simultaneous persistent connections per server/proxy:
Firefox 2: 2
Firefox 3+: 6
Opera 9.26: 4
Opera 12: 6
Safari 3: 4
Safari 5: 6
IE 7: 2
IE 8: 6
IE 10: 8
Edge: 6
Chrome: 6
The limit is per-server/proxy, so your wildcard scheme will work.
FYI: this is specifically related to HTTP 1.1; other protocols have separate concerns and limitations (i.e., SPDY, TLS, HTTP 2).
error: Your local changes to the following files would be overwritten by checkout
Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).
Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not push
ed); or - use stash:
git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop
git stash save
will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop
will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.
Uncaught ReferenceError: React is not defined
If you are using Babel and React 17, you might need to add "runtime2: "automatic" to config.
{
"presets": ["@babel/preset-env", ["@babel/preset-react", {
"runtime": "automatic"
}]]
}
iPad WebApp Full Screen in Safari
First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.
After locating the webpage, tap on the arrow icon at the top of your screen.
In the drop-down menu, tap on the Add to Home Screen option.
The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.
A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.
Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars.
This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:
<meta name="apple-mobile-web-app-capable" content="yes">
You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.
Java : Accessing a class within a package, which is the better way?
No, it doesn't save you memory.
Also note that you don't have to import Math
at all. Everything in java.lang
is imported automatically.
A better example would be something like an ArrayList
import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();
Note I'm importing the ArrayList
specifically. I could have done
import java.util.*;
But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.
WebView link click open default browser
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(https://whatoplay.com/);
You don't have to include this code.
// webview.setWebViewClient(new WebViewClient());
Instead use below code.
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
String url2="https://whatoplay.com/";
// all links with in ur site will be open inside the webview
//links that start ur domain example(http://www.example.com/)
if (url != null && url.startsWith(url2)){
return false;
}
// all links that points outside the site will be open in a normal android browser
else
{
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
}
});
How does numpy.newaxis work and when to use it?
newaxis
object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.
It is not just conversion of row matrix to column matrix.
Consider the example below:
In [1]:x1 = np.arange(1,10).reshape(3,3)
print(x1)
Out[1]: array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Now lets add new dimension to our data,
In [2]:x1_new = x1[:,np.newaxis]
print(x1_new)
Out[2]:array([[[1, 2, 3]],
[[4, 5, 6]],
[[7, 8, 9]]])
You can see that newaxis
added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).
How our new dimension enables us to different operations:
In [3]:x2 = np.arange(11,20).reshape(3,3)
print(x2)
Out[3]:array([[11, 12, 13],
[14, 15, 16],
[17, 18, 19]])
Adding x1_new and x2, we get:
In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
[15, 17, 19],
[18, 20, 22]],
[[15, 17, 19],
[18, 20, 22],
[21, 23, 25]],
[[18, 20, 22],
[21, 23, 25],
[24, 26, 28]]])
Thus, newaxis
is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.
Is Python strongly typed?
A Python variable stores an untyped reference to the target object that represent the value.
Any assignment operation means assigning the untyped reference to the assigned object -- i.e. the object is shared via the original and the new (counted) references.
The value type is bound to the target object, not to the reference value. The (strong) type checking is done when an operation with the value is performed (run time).
In other words, variables (technically) have no type -- it does not make sense to think in terms of a variable type if one wants to be exact. But references are automatically dereferenced and we actually think in terms of the type of the target object.
Concept of void pointer in C programming
void pointer is a generic pointer.. Address of any datatype of any variable can be assigned to a void pointer.
int a = 10;
float b = 3.14;
void *ptr;
ptr = &a;
printf( "data is %d " , *((int *)ptr));
//(int *)ptr used for typecasting dereferencing as int
ptr = &b;
printf( "data is %f " , *((float *)ptr));
//(float *)ptr used for typecasting dereferencing as float
How to configure logging to syslog in Python?
Here's the yaml dictConfig way recommended for 3.2 & later.
In log cfg.yml
:
version: 1
disable_existing_loggers: true
formatters:
default:
format: "[%(process)d] %(name)s(%(funcName)s:%(lineno)s) - %(levelname)s: %(message)s"
handlers:
syslog:
class: logging.handlers.SysLogHandler
level: DEBUG
formatter: default
address: /dev/log
facility: local0
rotating_file:
class: logging.handlers.RotatingFileHandler
level: DEBUG
formatter: default
filename: rotating.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
root:
level: DEBUG
handlers: [syslog, rotating_file]
propogate: yes
loggers:
main:
level: DEBUG
handlers: [syslog, rotating_file]
propogate: yes
Load the config using:
log_config = yaml.safe_load(open('cfg.yml'))
logging.config.dictConfig(log_config)
Configured both syslog & a direct file. Note that the /dev/log
is OS specific.
How do I get elapsed time in milliseconds in Ruby?
As stated already, you can operate on Time
objects as if they were numeric (or floating point) values. These operations result in second resolution which can easily be converted.
For example:
def time_diff_milli(start, finish)
(finish - start) * 1000.0
end
t1 = Time.now
# arbitrary elapsed time
t2 = Time.now
msecs = time_diff_milli t1, t2
You will need to decide whether to truncate that or not.
How to parse my json string in C#(4.0)using Newtonsoft.Json package?
This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
WebClient client = new WebClient();
string jsonstring;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
Response.Write(dynObj.results[0].address_components[1].long_name);
}
}
}
Copying data from one SQLite database to another
You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
Or, if the columns are not matched up in order:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
How to create an Excel File with Nodejs?
Or - build on @Jamaica Geek's answer, using Express - to avoid saving and reading a file:
res.attachment('file.xls');
var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = [0,21,'BOB'].join('\t')
var row2 = [0,22,'bob'].join('\t');
var c = header + row1 + row2;
return res.send(c);
Running Java Program from Command Line Linux
Guys let's understand the syntax of it.
If class file is present in the Current Dir.
java -cp . fileName
If class file is present within the Dir. Go to the Parent Dir and enter below cmd.
java -cp . dir1.dir2.dir3.fileName
If there is a dependency on external jars then,
java -cp .:./jarName1:./jarName2 fileName
Hope this helps.
How to exit from Python without traceback?
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main
routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
What is an HttpHandler in ASP.NET
In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler
interface.
ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
ASP.NET offers a few default HTTP handlers:
- Page Handler (.aspx): handles Web pages
- User Control Handler (.ascx): handles Web user control pages
- Web Service Handler (.asmx): handles Web service pages
- Trace Handler (trace.axd): handles trace functionality
You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example
- delivery of dynamically created images (charts for example) or resized pictures.
- RSS feeds which emit RSS-formated XML
You implement the IHttpHandler
interface to create a synchronous handler and the IHttpAsyncHandler
interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest
method and the IsReusable
property.
The ProcessRequest
method handles the actual processing for requests made, while the Boolean IsReusable
property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
MySQL & Java - Get id of the last inserted value (JDBC)
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.
Compare two date formats in javascript/jquery
try with new Date(obj).getTime()
if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
alert(fit_end_time + " is greater."); // your code
}
else
{
alert("both are same!"); // your code
}
jQuery - find table row containing table cell containing specific text
I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.
$("tr:contains(needle)");
//where needle is the text you are searching for.
For example, if you are searching for the text 'box', that would be:
$("tr:contains('box')");
This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements
How to apply slide animation between two activities in Android?
Here is a Slide Animation for you.
Let's say you have two activities.
- MovieDetailActivity
- AllCastActivity
And on click of a Button, this happens.
You can achieve this in 3 simple steps
1) Enable Content Transition
Go to your style.xml
and add this line to enable the content transition.
<item name="android:windowContentTransitions">true</item>
2) Write Default Enter and Exit Transition for your AllCastActivity
public void setAnimation()
{
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
slide.setDuration(400);
slide.setInterpolator(new AccelerateDecelerateInterpolator());
getWindow().setExitTransition(slide);
getWindow().setEnterTransition(slide);
}
}
3) Start Activity with Intent
Write this method in Your MovieDetailActivity
to start AllCastActivity
public void startActivity(){
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());
if(Build.VERSION.SDK_INT>20)
{
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
startActivity(i,options.toBundle());
}
else {
startActivity(i);
}
}
Most important!
put your setAnimation()
method before setContentView()
method otherwise the animation will not work.
So your AllCastActivity.java
should look like this
class AllCastActivity extends AppcompatActivity {
@Override
protected void onCreate(Bundle savedInstaceState)
{
super.onCreate(savedInstaceState);
setAnimation();
setContentView(R.layout.all_cast_activity);
.......
}
private void setAnimation(){
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
..........
}
}
ERROR: Cannot open source file " "
You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h
resides, the other issue could be that GameEngine.h
is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA
and ProjectB
, if you are including GameEngine.h
in some source/header file in ProjectA
then to include it properly, assuming that ProjectB
is in the same parent folder do this:
include "../ProjectB/GameEngine.h"
This is if you have a structure like this:
Root\ProjectA
Root\ProjectB <- GameEngine.h actually lives here
Hide password with "•••••••" in a textField
You can achieve this directly in Xcode:
The very last checkbox, make sure secure
is checked .
Or you can do it using code:
Identifies whether the text object should hide the text being entered.
Declaration
optional var secureTextEntry: Bool { get set }
Discussion
This property is set to false
by default. Setting this property to true
creates a password-style text object, which hides the text being entered.
example:
texfield.secureTextEntry = true
Adding two numbers concatenates them instead of calculating the sum
You are missing the type conversion during the addition step...
var x = y + z;
should be var x = parseInt(y) + parseInt(z);
<!DOCTYPE html>
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction()
{
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseInt(y) + parseInt(z);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Accessing Session Using ASP.NET Web API
Going back to basics why not keep it simple and store the Session value in a hidden html value to pass to your API?
Controller
public ActionResult Index()
{
Session["Blah"] = 609;
YourObject yourObject = new YourObject();
yourObject.SessionValue = int.Parse(Session["Blah"].ToString());
return View(yourObject);
}
cshtml
@model YourObject
@{
var sessionValue = Model.SessionValue;
}
<input type="hidden" value="@sessionValue" id="hBlah" />
Javascript
$(document).ready(function () {
var sessionValue = $('#hBlah').val();
alert(sessionValue);
/* Now call your API with the session variable */}
}
Replacing NULL and empty string within Select statement
For an example data in your table such as combinations of
''
, null
and as well as actual value
than if you want to only actual value
and replace to ''
and null
value by #
symbol than execute this query
SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull
function but here only i am mentioning IIF
function
SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name
SELECT IIF(Column_Name = '', '#', Column_Name) FROM Table_Name
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
Convert MFC CString to integer
you can also use good old sscanf.
CString s;
int i;
int j = _stscanf(s, _T("%d"), &i);
if (j != 1)
{
// tranfer didn't work
}
Debugging PHP Mail() and/or PHPMailer
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Access Database opens as read only
Another thing to watch for is when someone has access to READ the fileshare, but cannot WRITE to the directory. It's OK to make the database read-only for someone, but if they ever read it (including using an ODBC connection), it seems like they need to have WRITE permissions for the directory so they can create the lock file.
I've run into situations where the database gets locked read-only on the fileshare because the user who accessed it couldn't write to the directory. The only way to fix that quickly has been a call to the storage team, who can see who has the file and kick them off.
Check if input is number or letter javascript
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
MongoDB: update every document on one field
You can use updateMany()
methods of mongodb to update multiple document
Simple query is like this
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
As per your requirement the update code will be like this:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set
Is there a better jQuery solution to this.form.submit();?
Your question in somewhat confusing in that that you don't explain what you mean by "current element".
If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.
But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.
Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:
<form action="...">
<input type="hidden" name="rowId" value="...">
<button type="submit" name="myaction" value="edit">Edit</button>
<button type="submit" name="myaction" value="delete">Delete</button>
</form>
When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).
Then on the server you just read the value of the variable "myaction" and decide what to do.
JQuery confirm dialog
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
Export/import jobs in Jenkins
Importing Jobs Manually: Alternate way
Upload the Jobs on to Git (Version Control)
Basically upload config.xml of the Job.
If Linux Servers:
cd /var/lib/jenkins/jobs/<Job name>
Download the config.xml from Git
Restart the Jenkins
how to make window.open pop up Modal?
I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.
In parent window use:
<head>
<style>
.disableWin{
pointer-events: none;
}
</style>
<script type="text/javascript">
function openPopUp(url) {
disableParentWin();
var win = window.open(url);
win.focus();
checkPopUpClosed(win);
}
/*Function to detect pop up is closed and take action to enable parent window*/
function checkPopUpClosed(win) {
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
enableParentWin();
}
}, 1000);
}
/*Function to enable parent window*/
function enableParentWin() {
window.document.getElementById('mainDiv').class="";
}
/*Function to enable parent window*/
function disableParentWin() {
window.document.getElementById('mainDiv').class="disableWin";
}
</script>
</head>
<body>
<div id="mainDiv class="">
</div>
</body>
How to convert a JSON string to a dictionary?
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization
and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
How can I count the numbers of rows that a MySQL query returned?
Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.
However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).
Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.
How do I loop through a date range?
Iterate every 15 minutes
DateTime startDate = DateTime.Parse("2018-06-24 06:00");
DateTime endDate = DateTime.Parse("2018-06-24 11:45");
while (startDate.AddMinutes(15) <= endDate)
{
Console.WriteLine(startDate.ToString("yyyy-MM-dd HH:mm"));
startDate = startDate.AddMinutes(15);
}
jquery mobile background image
I think your answer will be background-size:cover
.
.ui-page
{
background: #000;
background-image:url(image.gif);
background-size:cover;
}
increment date by one month
strtotime( "+1 month", strtotime( $time ) );
this returns a timestamp that can be used with the date function
How to auto-scroll to end of div when data is added?
If you don't know when data will be added to #data
, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
How to properly use the "choices" field option in Django
I would suggest to use django-model-utils instead of Django built-in solution.
The main advantage of this solution is the lack of string declaration duplication. All choice items are declared exactly once. Also this is the easiest way for declaring choices using 3 values and storing database value different than usage in source code.
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
class MyModel(models.Model):
MONTH = Choices(
('JAN', _('January')),
('FEB', _('February')),
('MAR', _('March')),
)
# [..]
month = models.CharField(
max_length=3,
choices=MONTH,
default=MONTH.JAN,
)
And with usage IntegerField instead:
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
class MyModel(models.Model):
MONTH = Choices(
(1, 'JAN', _('January')),
(2, 'FEB', _('February')),
(3, 'MAR', _('March')),
)
# [..]
month = models.PositiveSmallIntegerField(
choices=MONTH,
default=MONTH.JAN,
)
- This method has one small disadvantage: in any IDE (eg. PyCharm) there will be no code completion for available choices (it’s because those values aren’t standard members of Choices class).
Scala Doubles, and Precision
A bit strange but nice. I use String and not BigDecimal
def round(x: Double)(p: Int): Double = {
var A = x.toString().split('.')
(A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}
'NoneType' object is not subscriptable?
The print()
function returns None
. You are trying to index None. You can not, because 'NoneType' object is not subscriptable
.
Put the [0]
inside the brackets. Now you're printing everything, and not just the first term.
Identifying Exception Type in a handler Catch Block
Alternative Solution
Instead halting a debug session to add some throw-away statements to then recompile and restart, why not just use the debugger to answer that question immediately when a breakpoint is hit?
That can be done by opening up the Immediate Window
of the debugger and typing a GetType
off of the exception and hitting Enter. The immediate window also allows one to interrogate variables as needed.
See VS Docs: Immediate Window
For example I needed to know what the exception was and just extracted the Name
property of GetType
as such without having to recompile:
How to compile and run C files from within Notepad++ using NppExec plugin?
For perl,
To run perl script use this procedure
Requirement: You need to setup classpath variable.
Go to plugins->NppExec->Execute
In command section, type this
cmd /c cd "$(CURRENT_DIRECTORY)"&&"$(FULL_CURRENT_PATH)"
Save it and give name to it.(I give Perl).
Press OK. If editor wants to restart, do it first.
Now press F6 and you will find your Perl script output on below side.
Note: Not required seperate config for seperate files.
For java,
Requirement: You need to setup JAVA_HOME
and classpath
variable.
Go to plugins->NppExec->Execute
In command section, type this
cmd /c cd "$(CURRENT_DIRECTORY)"&&"%JAVA_HOME%\bin\javac""$(FULL_CURRENT_PATH)"
your *.class
will generate on location of current folder; despite of programming error.
For Python,
Use this Plugin Python Plugin
Go to plugins->NppExec-> Run file in Python intercative
By using this you can run scripts within Notepad++.
For PHP,
No need for different configuration just download this plugin.
PHP Plugin
and done.
For C language,
Requirement: You need to setup classpath variable.
I am using MinGW compiler.
Go to plugins->NppExec->Execute
paste this into there
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)"
a
(Remember to give above four lines separate lines.)
Now, give name, save and ok.
Restart Npp.
Go to plugins->NppExec->Advanced options.
Menu Item->Item Name (I have C compiler)
Associated Script-> from combo box select the above name of script.
Click on Add/modify and Ok.
Now assign shortcut key as given in first answer.
Press F6 and select script or just press shortcut(I assigned Ctrl+2).
For C++,
Only change g++ instead of gcc
and *.cpp
instead on *.c
That's it!!
Setting unique Constraint with fluent API?
@coni2k 's answer is correct however you must add [StringLength]
attribute for it to work otherwise you will get an invalid key exception (Example bellow).
[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }
[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }
How to change the font on the TextView?
When your font is stored inside res/asset/fonts/Helvetica.ttf
use the following:
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf");
txt.setTypeface(tf);
Or, if your font file is stores inside res/font/helvetica.ttf
use the following:
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
Push local Git repo to new remote including all branches and tags
Below command will push all the branches(including the ones which you have never checked-out but present in your git repo, you can see them by git branch -a
)
git push origin '*:*'
NOTE: This command comes handy when you are migrating version control
service(i.e migrating from Gitlab to GitHub)
How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?
I think this answers the question best, it actually changes the alpha value of something that has been drawn already. Maybe this wasn't part of the api when this question was asked.
Given 2d context c
.
function reduceAlpha(x, y, w, h, dA) {
let screenData = c.getImageData(x, y, w, h);
for(let i = 3; i < screenData.data.length; i+=4){
screenData.data[i] -= dA; //delta-Alpha
}
c.putImageData(screenData, x, y );
}
Active Menu Highlight CSS
Add a class to the body of each page:
<body class="home">
Or if you're on the contact page:
<body class="contact">
Then take this into consideration when you're creating your styles:
#sub-header ul li:hover,
body.home li.home,
body.contact li.contact { background-color: #000;}
#sub-header ul li:hover a,
body.home li.home a,
body.contact li.contact a { color: #fff; }
Lastly, apply class names to your list items:
<ul>
<li class="home"><a href="index.php">Home</a></li>
<li class="contact"><a href="contact.php">Contact Us</a></li>
<li class="about"><a href="about.php">About Us</a></li>
</ul>
This point, whenever you're on the body.home
page, your li.home a
link will have default styling indicating it is the current page.
CMake does not find Visual C++ compiler
Checking CMakeErrors.log in CMakeFiles returned:
C:\Program Files
(x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140_xp\Toolset.targets(36,5): warning MSB8003: Could not find WindowsSdkDir_71A variable from the
registry. TargetFrameworkVersion or PlatformToolset may be set to an
invalid version number.
The error means that the build tools for XP (v140_xp) are not installed. To fix it I installed the proper feature in Visual Studio 2019 installer under Individual Components tab:
Passing argument to alias in bash
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
What does a bitwise shift (left or right) do and what is it used for?
Left Shift
x = x * 2^value
(normal operation)
x << value
(bit-wise operation)
x = x * 16
(which is the same as 2^4
)
The left shift equivalent would be x = x << 4
Right Shift
x = x / 2^value
(normal arithmetic operation)
x >> value
(bit-wise operation)
x = x / 8
(which is the same as 2^3
)
The right shift equivalent would be x = x >> 3
What does -> mean in Python function definitions?
def f(x) -> 123:
return x
My summary:
Simply ->
is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107
This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.
You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.
You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.
Send email using the GMail SMTP server from a PHP page
SwiftMailer can send E-Mail using external servers.
here is an example that shows how to use a Gmail server:
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
"smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
MySQL SELECT WHERE datetime matches day (and not necessarily time)
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
- it will calculate
DATE()
for all rows, including those, that don't match
- it will make it impossible to use an index for the query
It is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
Equivalent of String.format in jQuery
I have a plunker that adds it to the string prototype:
string.format
It is not just as short as some of the other examples, but a lot more flexible.
Usage is similar to c# version:
var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy");
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array
Also, added support for using names & object properties
var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"});
//result: Meet you on Thursday, ask for Frank
Kill detached screen session
To kill all detached screen sessions, include this function in your .bash_profile:
killd () {
for session in $(screen -ls | grep -o '[0-9]\{5\}')
do
screen -S "${session}" -X quit;
done
}
to run it, call killd
Why use prefixes on member variables in C++ classes
I use m_ for member variables just to take advantage of Intellisense and related IDE-functionality. When I'm coding the implementation of a class I can type m_ and see the combobox with all m_ members grouped together.
But I could live without m_ 's without problem, of course. It's just my style of work.
What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Bluetooth pairing without user confirmation
If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.
I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.
How to execute UNION without sorting? (SQL)
Try this:
SELECT DISTINCT * FROM (
SELECT column1, column2 FROM Table1
UNION ALL
SELECT column1, column2 FROM Table2
UNION ALL
SELECT column1, column2 FROM Table3
) X ORDER BY Column1
How to embed images in html email
Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.
define("EMAIL_DOMAIN", "yourdomain.com");
public function send_email_html($to, $from, $subject, $html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$uniqid = md5(uniqid(time()));
$boundary = "--==_mimepart_".$uniqid;
$headers = "From: ".$from."\n".
'Reply-to: '.$from."\n".
'Return-Path: '.$from."\n".
'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
'Mime-Version: 1.0'."\n".
'Content-Type: multipart/related;'."\n".
' boundary='.$boundary.";\n".
' charset=UTF-8'."\n".
'X-Mailer: PHP/' . phpversion();
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'UTF-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if (file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
mail($to, $subject, $multipart, $headers);
}
Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]
That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.
My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.
- Switches - (very unlikely but sometimes they get in a sick state)
- Routers - more likely than switches, but not much
- Firewall - More likely than routers. Things to look for here are resource exhaustion (license, cpu, etc)
- Client side filtering software - antivirus, malware detection etc.
How to Set user name and Password of phpmyadmin
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there..
Hope this Helps.
How much should a function trust another function
My 2 cents.
This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.
On the other hand if its some client I don't control then it is a good idea to do thorough error checking.
Establish a VPN connection in cmd
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
How to force R to use a specified factor level as reference in a regression?
See the relevel()
function. Here is an example:
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
head(DF)
str(DF)
m1 <- lm(y ~ x + b, data = DF)
summary(m1)
Now alter the factor b
in DF
by use of the relevel()
function:
DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
The models have estimated different reference levels.
> coef(m1)
(Intercept) x b2 b3 b4 b5
3.2903239 1.4358520 0.6296896 0.3698343 1.0357633 0.4666219
> coef(m2)
(Intercept) x b1 b2 b4 b5
3.66015826 1.43585196 -0.36983433 0.25985529 0.66592898 0.09678759
Android Starting Service at Boot Time , How to restart service class after device Reboot?
Your receiver:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, YourService.class);
context.startService(myIntent);
}
}
Your AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcast.receiver.example"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
<activity android:name=".BR_Example"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
<!-- Adding the permission -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Renaming column names of a DataFrame in Spark Scala
Sometime we have the column name is below format in SQLServer or MySQL table
Ex : Account Number,customer number
But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.
Solution:
val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)
CSS Disabled scrolling
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
Android Saving created bitmap to directory on sd card
Hi You can write data to bytes and then create a file in sdcard folder with whatever name and extension you want and then write the bytes to that file.
This will save bitmap to sdcard.
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
Assuming you will get the date string in a proper format, I have a solution.
function parseDateTime(dt) {
var date = false;
if (dt) {
var c_date = new Date(dt);
var hrs = c_date.getHours();
var min = c_date.getMinutes();
if (isNaN(hrs) || isNaN(min) || c_date === "Invalid Date") {
return null;
}
var type = (hrs <= 12) ? " AM" : " PM";
date = ((+hrs % 12) || hrs) + ":" + min + type;
}
return date;
}
parseDateTime("2016-11-21 12:39:08");//"12:39 AM"
parseDateTime("2017-11-21 23:39:08");//"11:39 PM"
How can I capture the right-click event in JavaScript?
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
var.replace is not a function
I fixed the problem.... sorry I should have put the code on how I was calling it too.... realized I accidentally was passing the object of the form field itself rather than it's value.
Thanks for your responses anyway. :)
How to set auto increment primary key in PostgreSQL?
Auto incrementing primary key in postgresql:
Step 1, create your table:
CREATE TABLE epictable
(
mytable_key serial primary key,
moobars VARCHAR(40) not null,
foobars DATE
);
Step 2, insert values into your table like this, notice that mytable_key is not specified in the first parameter list, this causes the default sequence to autoincrement.
insert into epictable(moobars,foobars) values('delicious moobars','2012-05-01')
insert into epictable(moobars,foobars) values('worldwide interblag','2012-05-02')
Step 3, select * from your table:
el@voyager$ psql -U pgadmin -d kurz_prod -c "select * from epictable"
Step 4, interpret the output:
mytable_key | moobars | foobars
-------------+-----------------------+------------
1 | delicious moobars | 2012-05-01
2 | world wide interblags | 2012-05-02
(2 rows)
Observe that mytable_key column has been auto incremented.
ProTip:
You should always be using a primary key on your table because postgresql internally uses hash table structures to increase the speed of inserts, deletes, updates and selects. If a primary key column (which is forced unique and non-null) is available, it can be depended on to provide a unique seed for the hash function. If no primary key column is available, the hash function becomes inefficient as it selects some other set of columns as a key.
Proper use of the IDisposable interface
I won't repeat the usual stuff about Using or freeing un-managed resources, that has all been covered. But I would like to point out what seems a common misconception.
Given the following code
Public Class LargeStuff
Implements IDisposable
Private _Large as string()
'Some strange code that means _Large now contains several million long strings.
Public Sub Dispose() Implements IDisposable.Dispose
_Large=Nothing
End Sub
I realise that the Disposable implementation does not follow current guidelines, but hopefully you all get the idea.
Now, when Dispose is called, how much memory gets freed?
Answer: None.
Calling Dispose can release unmanaged resources, it CANNOT reclaim managed memory, only the GC can do that. Thats not to say that the above isn't a good idea, following the above pattern is still a good idea in fact. Once Dispose has been run, there is nothing stopping the GC re-claiming the memory that was being used by _Large, even though the instance of LargeStuff may still be in scope. The strings in _Large may also be in gen 0 but the instance of LargeStuff might be gen 2, so again, memory would be re-claimed sooner.
There is no point in adding a finaliser to call the Dispose method shown above though. That will just DELAY the re-claiming of memory to allow the finaliser to run.
Jquery button click() function is not working
You need to use a delegated event handler, as the #add
elements dynamically appended won't have the click event bound to them. Try this:
$("#buildyourform").on('click', "#add", function() {
// your code...
});
Also, you can make your HTML strings easier to read by mixing line quotes:
var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');
Or even supplying the attributes as an object:
var fieldWrapper = $('<div></div>', {
'class': 'fieldwrapper',
'name': 'field' + intId,
'id': 'field' + intId
});
What exactly does Double mean in java?
In a comment on @paxdiablo's answer, you asked:
"So basically, is it better to use Double than Float?"
That is a complicated question. I will deal with it in two parts
Deciding between double
versus float
On the one hand, a double
occupies 8 bytes versus 4 bytes for a float
. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double
values is typically slower than with float
values ... though once again this is hardware dependent.
On the other hand, a double
can represent larger (and smaller) numbers than a float
and can represent them with more than twice the precision. For the details, refer to Wikipedia.
The tricky question is knowing whether you actually need the extra range and precision of a double
. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double
is going to give you enough precision. (And beware of the trap of expecting float
and double
to give you an exact representation. They won't and they can't!)
There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.
Deciding between Double
versus Float
For the Double
versus Float
case, the issues of precision and range are the same as for double
versus float
, but the relative performance measures will be slightly different.
A Double
(on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float
. Compare this to 8 bytes versus 4 bytes for the double
versus float
case. So the ratio is 5 to 4 versus 2 to 1.
Arithmetic involving Double
and Float
typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double
case.
Correctness
Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double
in preference to float
, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float
will make a difference with respect to that requirement.
Using headers with the Python requests library's get method
Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).
requests.get(url, params=None, headers=None, cookies=None, auth=None,
timeout=None)
Sends a GET request.
Returns Response
object.
Parameters:
- url – URL for the new
Request
object.
- params – (optional)
Dictionary of GET Parameters to send
with the
Request
.
- headers – (optional)
Dictionary of HTTP Headers to send
with the
Request
.
- cookies – (optional)
CookieJar object to send with the
Request
.
- auth – (optional) AuthObject
to enable Basic HTTP Auth.
- timeout –
(optional) Float describing the
timeout of the request.
REST API Best practice: How to accept list of parameter values as input
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
The project was not built since its build path is incomplete
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
- Right-click on the project, Build Path and go to Configure Build Path
- Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
- Close the dialog.
To add it:
Right-click on the project, Maven → Disable Maven Nature
Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
How do I uninstall nodejs installed from pkg (Mac OS X)?
Use npm to uninstall. Just running sudo npm uninstall npm -g
removes all the files.
To get rid of the extraneous stuff like bash pathnames run this (from nicerobot's answer):
sudo rm -rf /usr/local/lib/node \
/usr/local/lib/node_modules \
/var/db/receipts/org.nodejs.*
Passing a varchar full of comma delimited values to a SQL Server IN function
If you use SQL Server 2008 or higher, use table valued parameters; for example:
CREATE PROCEDURE [dbo].[GetAccounts](@accountIds nvarchar)
AS
BEGIN
SELECT *
FROM accountsTable
WHERE accountId IN (select * from @accountIds)
END
CREATE TYPE intListTableType AS TABLE (n int NOT NULL)
DECLARE @tvp intListTableType
-- inserts each id to one row in the tvp table
INSERT @tvp(n) VALUES (16509),(16685),(46173),(42925),(46167),(5511)
EXEC GetAccounts @tvp
Read .doc file with python
You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images.
You can install it by running: pip install docx2txt
.
Let's download and read the first Microsoft document on here:
import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)
Here is a screenshot of the Terminal output the above code:
EDIT:
This does NOT work for .doc files. The only reason I am keep this answer is that it seems there are people who find it useful for .docx files.
C char array initialization
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct
or union
.
Example program:
#include <stdio.h>
struct ccont
{
char array[32];
};
struct icont
{
int array[32];
};
int main()
{
int cnt;
char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '\0', '\0', ...
int iarray[32] = { 67, 42, 25 };
struct ccont cc = { 0 };
struct icont ic = { 0 };
/* these don't work
carray = { [0]=1 }; // expected expression before '{' token
carray = { [0 ... 31]=1 }; // (likewise)
carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g)
*/
// but these perfectly work...
cc = (struct ccont){ .array='a' }; // 'a', '\0', '\0', '\0', ...
// the following is a gcc extension,
cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '\0', '\0', ...
ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ...
// index ranges can overlap, the latter override the former
// (no compiler warning with -Wall -Wextra)
ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...
for (cnt=0; cnt<5; cnt++)
printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);
return 0;
}
How to turn off the Eclipse code formatter for certain sections of Java code?
Eclipse 3.6 allows you to turn off formatting by placing a special comment, like
// @formatter:off
...
// @formatter:on
The on/off features have to be turned "on" in Eclipse preferences: Java > Code Style > Formatter. Click on Edit, Off/On Tags, enable Enable Off/On tags.
It's also possible to change the magic strings in the preferences — check out the Eclipse 3.6 docs here.
More Information
Java
>
Code Style
>
Formatter
>
Edit
>
Off/On Tags
This preference allows you to define one tag to disable and one tag to enable the formatter (see the Off/On Tags tab in your formatter profile):
You also need to enable the flags from Java Formatting
What is the difference between a symbolic link and a hard link?
Hard links are useful when the original file is getting moved around. For example, moving a file from /bin to /usr/bin or to /usr/local/bin. Any symlink to the file in /bin would be broken by this, but a hardlink, being a link directly to the inode for the file, wouldn't care.
Hard links may take less disk space as they only take up a directory entry, whereas a symlink needs its own inode to store the name it points to.
Hard links also take less time to resolve - symlinks can point to other symlinks that are in symlinked directories. And some of these could be on NFS or other high-latency file systems, and so could result in network traffic to resolve. Hard links, being always on the same file system, are always resolved in a single look-up, and never involve network latency (if it's a hardlink on an NFS filesystem, the NFS server would do the resolution, and it would be invisible to the client system). Sometimes this is important. Not for me, but I can imagine high-performance systems where this might be important.
I also think things like mmap(2) and even open(2) use the same functionality as hardlinks to keep a file's inode active so that even if the file gets unlink(2)ed, the inode remains to allow the process continued access, and only once the process closes it does the file really go away. This allows for much safer temporary files (if you can get the open and unlink to happen atomically, which there may be a POSIX API for that I'm not remembering, then you really have a safe temporary file) where you can read/write your data without anyone being able to access it. Well, that was true before /proc gave everyone the ability to look at your file descriptors, but that's another story.
Speaking of which, recovering a file that is open in process A, but unlinked on the file system revolves around using hardlinks to recreate the inode links so the file doesn't go away when the process which has it open closes it or goes away.
Get drop down value
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
Why is processing a sorted array faster than processing an unsorted array?
The assumption by other answers that one needs to sort the data is not correct.
The following code does not sort the entire array, but only 200-element segments of it, and thereby runs the fastest.
Sorting only k-element sections completes the pre-processing in linear time, O(n)
, rather than the O(n.log(n))
time needed to sort the entire array.
#include <algorithm>
#include <ctime>
#include <iostream>
int main() {
int data[32768]; const int l = sizeof data / sizeof data[0];
for (unsigned c = 0; c < l; ++c)
data[c] = std::rand() % 256;
// sort 200-element segments, not the whole array
for (unsigned c = 0; c + 200 <= l; c += 200)
std::sort(&data[c], &data[c + 200]);
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i) {
for (unsigned c = 0; c < sizeof data / sizeof(int); ++c) {
if (data[c] >= 128)
sum += data[c];
}
}
std::cout << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << std::endl;
std::cout << "sum = " << sum << std::endl;
}
This also "proves" that it has nothing to do with any algorithmic issue such as sort order, and it is indeed branch prediction.
How to hash some string with sha256 in Java?
I traced the Apache code through DigestUtils
and sha256
seems to default back to java.security.MessageDigest
for calculation. Apache does not implement an independent sha256
solution. I was looking for an independent implementation to compare against the java.security
library. FYI only.
Access nested dictionary items via a list of keys?
Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.
The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:
def keysInDict(dataDict, parent=[]):
if not isinstance(dataDict, dict):
return [tuple(parent)]
else:
return reduce(list.__add__,
[keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])
One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).
def dict_to_df(dataDict):
ret = []
for k in keysInDict(dataDict):
v = np.array( getFromDict(dataDict, k), )
v = pd.DataFrame(v)
v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
ret.append(v)
return reduce(pd.DataFrame.join, ret)