How to add Python to Windows registry
You can find the Python executable with this command:
C:\> where python.exe
It should return something like:
C:\Users\<user>\AppData\Local\enthought\Canopy32\User\python.exe
Open regedit, navigate to HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\<version>\PythonPath
and add or edit the default key with this the value found in the first command.
Logout, login and python should be found. SciKit can now be installed.
See Additional “application paths” in https://docs.python.org/2/using/windows.html#finding-modules for more details.
Check if a property exists in a class
If you are binding like I was:
<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2") %>
Restore DB — Error RESTORE HEADERONLY is terminating abnormally.
Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'
The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\
is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?
BACKUP DATABASE go4sharepoint_1384_8481
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT
Note there is no space between '
and C:
What is a Sticky Broadcast?
If an Activity calls onPause
with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume
.
Update 6/23/2020
Sticky broadcasts are deprecated.
See sendStickyBroadcast
documentation.
This method was deprecated in API level 21.
Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
Implement
Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);
Resources
C# Iterating through an enum? (Indexing a System.Array)
How about a dictionary list?
Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}
and of course you can change the dictionary value type to whatever your enum values are.
Twitter bootstrap collapse: change display of toggle button
Here's another CSS only solution that works with any HTML layout.
It works with any element you need to switch. Whatever your toggle layout is you just put it inside a couple of elements with the if-collapsed
and if-not-collapsed
classes inside the toggle element.
The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed
class on the toggle.
It also requires the :not
selector, so it doesn't work on IE8.
HTML example:
<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
<!--You can put any valid html inside these!-->
<span class="if-collapsed">Open</span>
<span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
Less version:
[data-toggle="collapse"] {
&.collapsed .if-not-collapsed {
display: none;
}
&:not(.collapsed) .if-collapsed {
display: none;
}
}
CSS version:
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
JS Fiddle
Allowed memory size of 536870912 bytes exhausted in Laravel
You can try editing /etc/php5/fpm/php.ini:
; Old Limit
; memory_limit = 512M
; New Limit
memory_limit = 2048M
You may need to restart nginx
:
sudo systemctl restart nginx
You may also have an infinite loop somewhere. Can you post the code you're calling?
Difference between RUN and CMD in a Dockerfile
RUN Command:
RUN command will basically, execute the default command, when we are building the image. It also will commit the image changes for next step.
There can be more than 1 RUN command, to aid in process of building a new image.
CMD Command:
CMD commands will just set the default command for the new container. This will not be executed at build time.
If a docker file has more than 1 CMD commands then all of them are ignored except the last one. As this command will not execute anything but just set the default command.
SQL Server Insert Example
To insert a single row of data:
INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');
To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');
To insert multiple rows of data in SQL Server 2008 or later:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'
Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.
Link to a section of a webpage
Hashtags at the end of the URL bring a visitor to the element with the ID: e.g.
http://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage#answers
Would bring you to where the DIV with the ID 'answers' begins. Also, you can use the name attribute in anchor tags, to create the same effect.
Resource
What's the best way to add a drop shadow to my UIView
Wasabii's answer in Swift 2.3:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.CGPath
And in Swift 3/4/5:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.cgPath
Put this code in layoutSubviews() if you're using AutoLayout.
In SwiftUI, this is all much easier:
Color.yellow // or whatever your view
.shadow(radius: 3)
.frame(width: 200, height: 100)
How to find if element with specific id exists or not
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
Move the most recent commit(s) to a new branch with Git
Most previous answers are dangerously wrong!
Do NOT do this:
git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch
As the next time you run git rebase
(or git pull --rebase
) those 3 commits would be silently discarded from newbranch
! (see explanation below)
Instead do this:
git reset --keep HEAD~3
git checkout -t -b newbranch
git cherry-pick ..HEAD@{2}
- First it discards the 3 most recent commits (
--keep
is like --hard
, but safer, as fails rather than throw away uncommitted changes).
- Then it forks off
newbranch
.
- Then it cherry-picks those 3 commits back onto
newbranch
. Since they're no longer referenced by a branch, it does that by using git's reflog: HEAD@{2}
is the commit that HEAD
used to refer to 2 operations ago, i.e. before we 1. checked out newbranch
and 2. used git reset
to discard the 3 commits.
Warning: the reflog is enabled by default, but if you've manually disabled it (e.g. by using a "bare" git repository), you won't be able to get the 3 commits back after running git reset --keep HEAD~3
.
An alternative that doesn't rely on the reflog is:
# newbranch will omit the 3 most recent commits.
git checkout -b newbranch HEAD~3
git branch --set-upstream-to=oldbranch
# Cherry-picks the extra commits from oldbranch.
git cherry-pick ..oldbranch
# Discards the 3 most recent commits from oldbranch.
git branch --force oldbranch oldbranch~3
(if you prefer you can write @{-1}
- the previously checked out branch - instead of oldbranch
).
Technical explanation
Why would git rebase
discard the 3 commits after the first example? It's because git rebase
with no arguments enables the --fork-point
option by default, which uses the local reflog to try to be robust against the upstream branch being force-pushed.
Suppose you branched off origin/master when it contained commits M1, M2, M3, then made three commits yourself:
M1--M2--M3 <-- origin/master
\
T1--T2--T3 <-- topic
but then someone rewrites history by force-pushing origin/master to remove M2:
M1--M3' <-- origin/master
\
M2--M3--T1--T2--T3 <-- topic
Using your local reflog, git rebase
can see that you forked from an earlier incarnation of the origin/master branch, and hence that the M2 and M3 commits are not really part of your topic branch. Hence it reasonably assumes that since M2 was removed from the upstream branch, you no longer want it in your topic branch either once the topic branch is rebased:
M1--M3' <-- origin/master
\
T1'--T2'--T3' <-- topic (rebased)
This behavior makes sense, and is generally the right thing to do when rebasing.
So the reason that the following commands fail:
git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch
is because they leave the reflog in the wrong state. Git sees newbranch
as having forked off the upstream branch at a revision that includes the 3 commits, then the reset --hard
rewrites the upstream's history to remove the commits, and so next time you run git rebase
it discards them like any other commit that has been removed from the upstream.
But in this particular case we want those 3 commits to be considered as part of the topic branch. To achieve that, we need to fork off the upstream at the earlier revision that doesn't include the 3 commits. That's what my suggested solutions do, hence they both leave the reflog in the correct state.
For more details, see the definition of --fork-point
in the git rebase and git merge-base docs.
How to use an output parameter in Java?
Thank you. I use passing in an object as a parameter. My Android code is below
String oPerson= null;
if (CheckAddress("5556", oPerson))
{
Toast.makeText(this,
"It's Match! " + oPerson,
Toast.LENGTH_LONG).show();
}
private boolean CheckAddress(String iAddress, String oPerson)
{
Cursor cAddress = mDbHelper.getAllContacts();
String address = "";
if (cAddress.getCount() > 0) {
cAddress.moveToFirst();
while (cAddress.isAfterLast() == false) {
address = cAddress.getString(2).toString();
oPerson = cAddress.getString(1).toString();
if(iAddress.indexOf(address) != -1)
{
Toast.makeText(this,
"Person : " + oPerson,
Toast.LENGTH_LONG).show();
System.out.println(oPerson);
cAddress.close();
return true;
}
else cAddress.moveToNext();
}
}
cAddress.close();
return false;
}
The result is
Person : John
It's Match! null
Actually, "It's Match! John"
Please check my mistake.
How to return a table from a Stored Procedure?
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
Setting Oracle 11g Session Timeout
I came to this question looking for a way to enable oracle session pool expiration based on total session lifetime instead of idle time.
Another goal is to avoid force closes unexpected to application.
It seems it's possible by setting pool validation query to
select 1 from V$SESSION
where AUDSID = userenv('SESSIONID') and sysdate-LOGON_TIME < 30/24/60
This would close sessions aging over 30 minutes in predictable manner that doesn't affect application.
How can I count text lines inside an DOM element? Can I?
I found a way to calc the line number when I develop a html editor.
The primary method is that:
In IE you can call getBoundingClientRects, it returns each line as a
rectangle
In webkit or new standard html engine, it returns each element or
node's client rectangles, in this case you can compare each
rectangles, I mean each there must be a rectangle is the largest, so
you can ignore those rectangles that height is smaller(if there is a
rectangle's top smaller than it and bottom larger than it, the
condition is true.)
so let's see the test result:
The green rectangle is the largest rectangle in each row
The red rectangle is the selection boundary
The blue rectangle is the boundary from start to selection after expanding, we see it may larger than red rectangle, so we have to check each rectangle's bottom to limit it must smaller than red rectangle's bottom.
var lineCount = "?";
var rects;
if (window.getSelection) {
//Get all client rectangles from body start to selection, count those rectangles that has the max bottom and min top
var bounding = {};
var range = window.getSelection().getRangeAt(0);//As this is the demo code, I dont check the range count
bounding = range.getBoundingClientRect();//!!!GET BOUNDING BEFORE SET START!!!
//Get bounding and fix it , when the cursor is in the last character of lineCount, it may expand to the next lineCount.
var boundingTop = bounding.top;
var boundingBottom = bounding.bottom;
var node = range.startContainer;
if (node.nodeType !== 1) {
node = node.parentNode;
}
var style = window.getComputedStyle(node);
var lineHeight = parseInt(style.lineHeight);
if (!isNaN(lineHeight)) {
boundingBottom = boundingTop + lineHeight;
}
else {
var fontSize = parseInt(style.fontSize);
if (!isNaN(fontSize)) {
boundingBottom = boundingTop + fontSize;
}
}
range = range.cloneRange();
//Now we have enougn datas to compare
range.setStart(body, 0);
rects = range.getClientRects();
lineCount = 0;
var flags = {};//Mark a flags to avoid of check some repeat lines again
for (var i = 0; i < rects.length; i++) {
var rect = rects[i];
if (rect.width === 0 && rect.height === 0) {//Ignore zero rectangles
continue;
}
if (rect.bottom > boundingBottom) {//Check if current rectangle out of the real bounding of selection
break;
}
var top = rect.top;
var bottom = rect.bottom;
if (flags[top]) {
continue;
}
flags[top] = 1;
//Check if there is no rectangle contains this rectangle in vertical direction.
var succ = true;
for (var j = 0; j < rects.length; j++) {
var rect2 = rects[j];
if (j !== i && rect2.top < top && rect2.bottom > bottom) {
succ = false;
break;
}
}
//If succ, add lineCount 1
if (succ) {
lineCount++;
}
}
}
else if (editor.document.selection) {//IN IE8 getClientRects returns each single lineCount as a rectangle
var range = body.createTextRange();
range.setEndPoint("EndToEnd", range);
rects = range.getClientRects();
lineCount = rects.length;
}
//Now we get lineCount here
Navigation bar show/hide
If you want to detect the status of navigation bar wether it is
hidden/shown. You can simply use following code to detect -
if self.navigationController?.isNavigationBarHidden{
print("Show navigation bar")
} else {
print("hide navigation bar")
}
How to upload, display and save images using node.js and express
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
How to add custom validation to an AngularJS form?
Angular-UI's project includes a ui-validate directive, which will probably help you with this. It let's you specify a function to call to do the validation.
Have a look at the demo page: http://angular-ui.github.com/, search down to the Validate heading.
From the demo page:
<input ng-model="email" ui-validate='{blacklist : notBlackListed}'>
<span ng-show='form.email.$error.blacklist'>This e-mail is black-listed!</span>
then in your controller:
function ValidateCtrl($scope) {
$scope.blackList = ['[email protected]','[email protected]'];
$scope.notBlackListed = function(value) {
return $scope.blackList.indexOf(value) === -1;
};
}
Get all child elements
Yes, you can achieve it by find_elements_by_css_selector("*")
or find_elements_by_xpath(".//*")
.
However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")
header = driver.find_element_by_id("header")
# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")
print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))
Set Focus After Last Character in Text Box
This works fine for me . [Ref: the very nice plug in by Gavin G]
(function($){
$.fn.focusTextToEnd = function(){
this.focus();
var $thisVal = this.val();
this.val('').val($thisVal);
return this;
}
}(jQuery));
$('#mytext').focusTextToEnd();
Check if event exists on element
This work for me it is showing the objects and type of event which has occurred.
var foo = $._data( $('body').get(0), 'events' );
$.each( foo, function(i,o) {
console.log(i); // guide of the event
console.log(o); // the function definition of the event handler
});
How to copy multiple files in one layer using a Dockerfile?
It might be worth mentioning that you can also create a .dockerignore
file, to exclude the files that you don't want to copy:
https://docs.docker.com/engine/reference/builder/#dockerignore-file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.
What’s the best way to get an HTTP response code from a URL?
Update using the wonderful requests library. Note we are using the HEAD request, which should happen more quickly then a full GET or POST request.
import requests
try:
r = requests.head("https://stackoverflow.com")
print(r.status_code)
# prints the int of the status code. Find more at httpstatusrappers.com :)
except requests.ConnectionError:
print("failed to connect")
How to delete an instantiated object Python?
What do you mean by delete
? In Python, removing a reference (or a name) can be done with the del
keyword, but if there are other names to the same object that object will not be deleted.
--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
compared to:
--> test = 5
--> other is test # check that both name refer to the exact same object
True
--> del test # gets rid of test, but the object is still referenced by other
--> print(other)
5
Doing a join across two databases with different collations on SQL Server and getting an error
A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.
It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)
select
sone_field collate DATABASE_DEFAULT
from
table_1
inner join
table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever
How do you properly use namespaces in C++?
Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:
#include "lib/module1.h"
#include "lib/module2.h"
lib::class1 *v = new lib::class1();
I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.
using wildcards in LDAP search filters/queries
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
trying to align html button at the center of the my page
Here's your solution: JsFiddle
Basically, place your button into a div with centred text:
<div class="wrapper">
<button class="button">Button</button>
</div>
With the following styles:
.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 50%;
}
There are many ways to skin a cat, and this is just one.
Tomcat 8 Maven Plugin for Java 8
groupId and Mojo name change
Since version 2.0-beta-1 tomcat mojos has been renamed to tomcat6 and tomcat7 with the same goals.
You must configure your pom to use this new groupId:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
</plugins>
</pluginManagement>
Or add the groupId in your settings.xml
....
org.apache.tomcat.maven
....
How to disable a input in angular2
What you are looking for is disabled="true". Here is an example:
<textarea class="customPayload" disabled="true" *ngIf="!showSpinner"></textarea>
How to detect Esc Key Press in React and how to handle it
React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:
handleOnKeyDown = (e) => {
if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
// select item
e.preventDefault();
} else if (e.key === 'ArrowUp') {
// go to top item
e.preventDefault();
} else if (e.key === 'ArrowDown') {
// go to bottom item
e.preventDefault();
} else if (e.key === 'Escape') {
// escape
e.preventDefault();
}
};
How can I mock an ES6 module import using Jest?
I solved this another way. Let's say you have your dependency.js
export const myFunction = () => { }
I create a depdency.mock.js file besides it with the following content:
export const mockFunction = jest.fn();
jest.mock('dependency.js', () => ({ myFunction: mockFunction }));
And in the test, before I import the file that has the dependency, I use:
import { mockFunction } from 'dependency.mock'
import functionThatCallsDep from './tested-code'
it('my test', () => {
mockFunction.returnValue(false);
functionThatCallsDep();
expect(mockFunction).toHaveBeenCalled();
})
Rails raw SQL example
You can also mix raw SQL with ActiveRecord conditions, for example if you want to call a function in a condition:
my_instances = MyModel.where.not(attribute_a: nil) \
.where('crc32(attribute_b) = ?', slot) \
.select(:id)
JavaScript function in href vs. onclick
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.
Default keystore file does not exist?
For Mac/Linux debug keystore, the Android docs have:
keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore
But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return
in terminal after the backslash so that the second that starts with -alias
is on a new line. Simply pasting as-is will not work.
Your terminal (if successful) will look something like this:
$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password:
The default debug password is: android
Side note: In Android Studio you can manage signing in:
File > Project Structure > Modules - (Your App) > Signing
Set specific precision of a BigDecimal
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
Reduce git repository size
In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.
What did the trick was:
bfg -b 100M # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Then, you need to push force on your branch:
git push origin <your_branch_name> --force
Note: bfg is a tool that can be installed on Linux and macOS using brew:
brew install bfg
Targeting .NET Framework 4.5 via Visual Studio 2010
There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).
Backup your project file!!!
Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.
Open your project in VS2010.
Create a text file in your project named Compile_4_5_CSharp.targets
with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):
<Project DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
<PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
<DefineConstants Condition="'$(DefineConstants)'==''">
TARGETTING_FX_4_5
</DefineConstants>
<DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
$(DefineConstants);TARGETTING_FX_4_5
</DefineConstants>
<PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<!-- Import the standard C# targets -->
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- Add .NET 4.5 as an available platform -->
<PropertyGroup>
<AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
</PropertyGroup>
</Project>
Unload your project (right click -> unload).
Edit the project file (right click -> Edit *.csproj).
Make the following changes in the project file:
a. Replace the default Microsoft.CSharp.targets
with the target file created in step 4
<!-- Old Import Entry -->
<!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
<!-- New Import Entry -->
<Import Project="Compile_4_5_CSharp.targets" />
b. Change the default platform to .NET 4.5
<!-- Old default platform entry -->
<!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
<!-- New default platform entry -->
<Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
c. Add AnyCPU
platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup>
tag in the file
<PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
.
.
.
<ItemGroup>
.
.
.
Save your changes and close the *.csproj
file.
Reload your project (right click -> Reload Project).
In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.
Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.
Build your project and check for errors.
Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:
using System;
using System.Text;
namespace testing
{
using net45check = System.Reflection.ReflectionContext;
}
When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:
Error 6: The type or namespace name 'ReflectionContext' does not exist in
the namespace 'System.Reflection' (are you missing an assembly reference?)
Having a UITextField in a UITableViewCell
I ran into the same problem. It seems that setting the cell.textlabel.text
property brings the UILabel to the front of the contentView of the cell.
Add the textView after setting textLabel.text
, or (if that's not possible) call this:
[cell.contentView bringSubviewToFront:textField]
sending email via php mail function goes to spam
The problem is simple that the PHP-Mail function is not using a well configured SMTP Server.
Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.
Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are gone.
https://github.com/PHPMailer/PHPMailer
How do you clear a stringstream variable?
You can clear the error state and empty the stringstream all in one line
std::stringstream().swap(m); // swap m with a default constructed stringstream
This effectively resets m to a default constructed state
cURL equivalent in Node.js?
I ended up using the grunt-shell library.
Here is my source gist for my fully implemented Grunt task for anyone else thinking about working with the EdgeCast API. You'll find in my example that I use a grunt-shell to execute the curl command which purges the CDN.
This was that I ended up with after spending hours trying to get an HTTP request to work within Node. I was able to get one working in Ruby and Python, but did not meet the requirements of this project.
Check if a value is an object in JavaScript
Oh My God! I think this could be more shorter than ever, let see this:
Short and Final code
_x000D_
_x000D_
function isObject(obj)_x000D_
{_x000D_
return obj != null && obj.constructor.name === "Object"_x000D_
}_x000D_
_x000D_
console.log(isObject({})) // returns true_x000D_
console.log(isObject([])) // returns false_x000D_
console.log(isObject(null)) // returns false
_x000D_
_x000D_
_x000D_
Explained
Return Types
typeof JavaScript objects (including null
) returns "object"
_x000D_
_x000D_
console.log(typeof null, typeof [], typeof {})
_x000D_
_x000D_
_x000D_
Checking on Their constructors
Checking on their constructor
property returns function with their names.
_x000D_
_x000D_
console.log(({}).constructor) // returns a function with name "Object"_x000D_
console.log(([]).constructor) // returns a function with name "Array"_x000D_
console.log((null).constructor) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_
Introducing Function.name
Function.name
returns a readonly name of a function or "anonymous"
for closures.
_x000D_
_x000D_
console.log(({}).constructor.name) // returns "Object"_x000D_
console.log(([]).constructor.name) // returns "Array"_x000D_
console.log((null).constructor.name) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_
Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility
How to get the parent dir location
os.path.dirname(os.path.abspath(__file__))
Should give you the path to a
.
But if b.py
is the file that is currently executed, then you can achieve the same by just doing
os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
If statement with String comparison fails
If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals()
or equalsIgnoreCase()
for that.
How to detect IE11?
Use !(window.ActiveXObject) && "ActiveXObject" in window
to detect IE11 explicitly.
To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window
instead.
How do I install the OpenSSL libraries on Ubuntu?
As a general rule, when on Debian or Ubuntu and you're missing a development file (or any other file for that matter), use apt-file
to figure out which package provides that file:
~ apt-file search openssl/bio.h
android-libboringssl-dev: /usr/include/android/openssl/bio.h
libssl-dev: /usr/include/openssl/bio.h
libwolfssl-dev: /usr/include/cyassl/openssl/bio.h
libwolfssl-dev: /usr/include/wolfssl/openssl/bio.h
A quick glance at each of the packages that are returned by the command, using apt show
will tell you which among the packages is the one you're looking for:
~ apt show libssl-dev
Package: libssl-dev
Version: 1.1.1d-2
Priority: optional
Section: libdevel
Source: openssl
Maintainer: Debian OpenSSL Team <[email protected]>
Installed-Size: 8,095 kB
Depends: libssl1.1 (= 1.1.1d-2)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Homepage: https://www.openssl.org/
Tag: devel::lang:c, devel::library, implemented-in::TODO, implemented-in::c,
protocol::ssl, role::devel-lib, security::cryptography
Download-Size: 1,797 kB
APT-Sources: http://ftp.fr.debian.org/debian unstable/main amd64 Packages
Description: Secure Sockets Layer toolkit - development files
This package is part of the OpenSSL project's implementation of the SSL
and TLS cryptographic protocols for secure communication over the
Internet.
.
It contains development libraries, header files, and manpages for libssl
and libcrypto.
N: There is 1 additional record. Please use the '-a' switch to see it
How to Export Private / Secret ASC Key to Decrypt GPG Files
You can export the private key with the command-line tool from GPG. It works on the Windows-shell. Use the following command:
gpg --export-secret-keys
A normal export with --export
will not include any private keys, therefore you have to use --export-secret-keys
.
Edit:
To sum up the information given in my comments, this is the command that allows you to export a specific key with the ID 1234ABCD to the file secret.asc:
gpg --export-secret-keys --armor 1234ABCD > secret.asc
You can find the ID that you need using the following command. The ID is the second part of the second column:
gpg --list-keys
To Export just 1 specific secret key instead of all of them:
gpg --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
Communication between tabs or windows
Checkout AcrossTabs - Easy communication between cross-origin browser tabs. It uses a combination of postMessage and sessionStorage API to make communication much easier and reliable.
There are different approaches and each one has its own advantages and disadvantages. Lets discuss each:
LocalStorage
Pros:
- Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
- The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
- The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
- It works on same-origin policy. So, data stored will only be able available on the same origin.
Cookies
Pros:
- Compared to others, there's nothing AFAIK.
Cons:
- The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
Typically, the following are allowed:
- 300 cookies in total
- 4096 bytes per cookie
- 20 cookies per domain
- 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
sessionStorage
Pros:
- It is similar to
localStorage
.
- Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted
Cons:
- The data is available only inside the window/tab in which it was set.
- The data is not persistent i.e. it will be lost once the window/tab is closed.
- Like
localStorage
, tt works on same-origin policy. So, data stored will only be able available on the same origin.
PostMessage
Pros:
- Safely enables cross-origin communication.
- As a data point, the WebKit implementation (used by Safari and Chrome) doesn't currently enforce any limits (other than those imposed by running out of memory).
Cons:
- Need to open a window from the current window and then can communicate only as long as you keep the windows open.
- Security concerns - Sending strings via postMessage is that you will pick up other postMessage events published by other JavaScript plugins, so be sure to implement a
targetOrigin
and a sanity check for the data being passed on to the messages listener.
A combination of PostMessage + SessionStorage
Using postMessage to communicate between multiple tabs and at the same time using sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain opened. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.
I have written a JavaScript library for this, named AcrossTabs which uses postMessage API to communicate between cross-origin tabs/windows and sessionStorage to persist the opened tabs/windows identity as long as they live.
PHP remove commas from numeric strings
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Create a dropdown component
I would say that it depends on what you want to do.
If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.
Here is a sample:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Input()
value: string[];
@Output()
valueChange: EventEmitter;
constructor(private elementRef:ElementRef) {
this.valueChange = new EventEmitter();
}
select(value) {
this.valueChange.emit(value);
}
}
This allows you to use it this way:
<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>
You can build your dropdown within the component, apply styles and manage selections internally.
Edit
You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Output()
select: EventEmitter;
constructor() {
this.select = new EventEmitter();
}
selectItem(value) {
this.select.emit(value);
}
}
Then you can use the component like this:
<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>
Notice that the action
method is the one of the parent component (not the dropdown one).
Mapping many-to-many association table with extra column(s)
As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship.
You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded
I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.
I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.
iterating through json object javascript
An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:
var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
jDepthLvl++;
if (isIterable(object)) {
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
} else
console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
forEachIn(object, function (accessor, child) {
visit(child, accessor);
});
} else {
var value = object;
console.log("%c"
+ spacesDepth(jDepthLvl)
+ objectAccessor + "[%c" + value + "%c] "
,"color:blue","color:red","color:blue");
}
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
}
jDepthLvl--;
}
function spacesDepth(jDepthLvl) {
let jSpc="";
for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
jSpc+="\u0020\u0020"
}
return jSpc;
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
visit($OBJECT_OR_ARRAY$);
UIGestureRecognizer on UIImageView
For Blocks lover you can use ALActionBlocks to add action of gestures in block
__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];
How can I use external JARs in an Android project?
If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):
- Select the Project view in the Project sideview (instead of Packages or Android)
- Create a folder called libs in your project's root folder
- Copy your JAR files to the libs folder
- The sideview will be updated and the JAR files will show up in your project
- Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
- After that, all you need to do is reference the new classes in your code, eg.
import javax.mail.*
Load CSV file with Spark
This is in PYSPARK
path="Your file path with file name"
df=spark.read.format("csv").option("header","true").option("inferSchema","true").load(path)
Then you can check
df.show(5)
df.count()
Create controller for partial view in ASP.NET MVC
You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async
@await Html.PartialAsync("_LoginPartial")
or
@{await Html.RenderPartialAsync("PartialName");}
or if you are using .net core 2.1 > you can just use:
<partial name="Shared/_ProductPartial.cshtml"
for="Product" />
How to convert integer to char in C?
A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
c = i +'0';
The '0' is a character in the ASCll table.
Delete from two tables in one query
You should either create a FOREIGN KEY
with ON DELETE CASCADE
:
ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE
, or do it using two queries in a transaction:
START TRANSACTION;;
DELETE
FROM usermessages
WHERE messageid = 1
DELETE
FROM messages
WHERE messageid = 1;
COMMIT;
Transaction affects only InnoDB
tables, though.
What is <scope> under <dependency> in pom.xml for?
Six Dependency scopes:
- compile: default scope, classpath is available for both
src/main
and src/test
- test: classpath is available for
src/test
- provided: like complie but provided by JDK or a container at runtime
- runtime: not required for compilation only require at runtime
- system: provided locally provide classpath
- import: can only import other POMs into the
<dependencyManagement/>
, only available in Maven 2.0.9 or later (like java import
)
How to create a custom navigation drawer in android
Android Navigation Drawer using Activity
I just followed the example :http://antonioleiva.com/navigation-view/
You just need few Customization:
public class MainActivity extends AppCompatActivity {
public static final String AVATAR_URL = "http://lorempixel.com/200/200/people/1/";
private DrawerLayout drawerLayout;
private View content;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
initToolbar();
setupDrawerLayout();
content = findViewById(R.id.content);
drawerToggle = setupDrawerToggle();
final ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.avatar);
Picasso.with(this).load(AVATAR_URL).transform(new CircleTransform()).into(avatar);
}
private void initToolbar() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.drawer_home:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
break;
case R.id.drawer_favorite:
Intent j = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(j);
finish();
break;
}
return true;
}
});
}
Here is the xml Layout
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer"/>
Add drawer.xml in menu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="@+id/drawer_home"
android:checked="true"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/home"/>
<item
android:id="@+id/drawer_favourite"
android:icon="@drawable/ic_favorite_black_24dp"
android:title="@string/favourite"/>
...
<item
android:id="@+id/drawer_settings"
android:icon="@drawable/ic_settings_black_24dp"
android:title="@string/settings"/>
</group>
To open and close drawer add this values in string.xml
<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>
drawer.xml
enter code here
<ImageView
android:id="@+id/avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_margin="@dimen/spacing_large"
android:elevation="4dp"
tools:src="@drawable/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/email"
android:layout_marginLeft="@dimen/spacing_large"
android:layout_marginStart="@dimen/spacing_large"
android:text="Username"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="@dimen/spacing_large"
android:layout_marginStart="@dimen/spacing_large"
android:layout_marginBottom="@dimen/spacing_large"
android:text="[email protected]"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>
How to post a file from a form with Axios
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Placing an image to the top right corner - CSS
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download
I used all above changes but still I was getting same issue on my web application.
Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.
They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.
Hope this answer will help someone.This is what worked for me
How to create composite primary key in SQL Server 2008
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
Materialize CSS - Select Doesn't Seem to Render
@littleguy23 That is correct, but you don't want to do it to multi select. So just a small change to the code:
$(document).ready(function() {
// Select - Single
$('select:not([multiple])').material_select();
});
iterating over each character of a String in ruby 1.8.6 (each_char)
I have the same problem. I usually resort to String#split
:
"ABCDEFG".split("").each do |i|
puts i
end
I guess you could also implement it yourself like this:
class String
def each_char
self.split("").each { |i| yield i }
end
end
Edit: yet another alternative is String#each_byte
, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:
"ABCDEFG".each_byte do |i|
puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end
Understanding ASP.NET Eval() and Bind()
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
- IntelliSense can find the correct property of the object your're working with
- If property is renamed/deleted, you will get an error before page is viewed in browser
- External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object
Source: from this excellent book
Formatting DataBinder.Eval data
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
Compute elapsed time
Hope this will help:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>
Built in Python hash() function
This is the hash function that Google uses in production for python 2.5:
def c_mul(a, b):
return eval(hex((long(a) * b) & (2**64 - 1))[:-1])
def py25hash(self):
if not self:
return 0 # empty
value = ord(self[0]) << 7
for char in self:
value = c_mul(1000003, value) ^ ord(char)
value = value ^ len(self)
if value == -1:
value = -2
if value >= 2**63:
value -= 2**64
return value
Ruby on Rails form_for select field with class
This work for me
<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>
How to handle the modal closing event in Twitter Bootstrap?
There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden".
As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:
$( '#modal' )
.on('hide', function() {
console.log('hide');
})
.on('hidden', function(){
console.log('hidden');
})
.on('show', function() {
console.log('show');
})
.on('shown', function(){
console.log('shown' )
});
And, as for your question, I think you should listen to the 'hide' event of your modal.
How to add column to numpy array
I think that your problem is that you are expecting np.append
to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, `out` is a flattened array.
so you need to save the output all_data = np.append(...)
:
my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)
Alternative ways:
all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)
I believe that the only difference between these three functions (as well as np.vstack
) are their default behaviors for when axis
is unspecified:
concatenate
assumes axis = 0
hstack
assumes axis = 1
unless inputs are 1d, then axis = 0
vstack
assumes axis = 0
after adding an axis if inputs are 1d
append
flattens array
Based on your comment, and looking more closely at your example code, I now believe that what you are probably looking to do is add a field to a record array. You imported both genfromtxt
which returns a structured array and recfromcsv
which returns the subtly different record array (recarray
). You used the recfromcsv
so right now my_data
is actually a recarray
, which means that most likely my_data.shape = (210,)
since recarrays are 1d arrays of records, where each record is a tuple with the given dtype.
So you could try this:
import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
# (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
# (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588 , 2.121903762680979 ),
# (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
# (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675 , 1.4957409515009568),
# (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308 , 2.4853911958174133),
# (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103 , 1.275756904913104 ),
# (0.684075052174589 , 0.6654774682866273 , 0.5246593820025259 , 1.8742119024637423),
# (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
# (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)],
# dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')
How to use Javascript to read local text file and read line by line?
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
How do I show a console output/window in a forms application?
Why not just leave it as a Window Forms app, and create a simple form to mimic the Console. The form can be made to look just like the black-screened Console, and have it respond directly to key press.
Then, in the program.cs file, you decide whether you need to Run the main form or the ConsoleForm. For example, I use this approach to capture the command line arguments in the program.cs file. I create the ConsoleForm, initially hide it, then pass the command line strings to an AddCommand function in it, which displays the allowed commands. Finally, if the user gave the -h or -? command, I call the .Show on the ConsoleForm and when the user hits any key on it, I shut down the program. If the user doesn't give the -? command, I close the hidden ConsoleForm and Run the main form.
How do I set the selected item in a drop down box
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
Get all column names of a DataTable into string array using (LINQ/Predicate)
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
What are the new features in C++17?
Language features:
Templates and Generic Code
Lambda
Attributes
Syntax cleanup
Cleaner multi-return and flow control
Misc
Hexadecimal float point literals
Dynamic memory allocation for over-aligned data
Guaranteed copy elision
- Finally!
- Not in all cases, but distinguishes syntax where you are "just creating something" that was called elision, from "genuine elision".
Fixed order-of-evaluation for (some) expressions with some modifications
- Not including function arguments, but function argument evaluation interleaving now banned
- Makes a bunch of broken code work mostly, and makes
.then
on future work.
Direct list-initialization of enums
Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
- I think this is saying "the implementation may not stall threads forever"?
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
"noexcept" in the type system
__has_include
- Test if a header file include would be an error
- makes migrating from experimental to std almost seamless
Arrays of pointer conversion fixes
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
aggregate initialization with inheritance.
std::launder
, type punning, etc
Library additions:
Data types
Invoke stuff
std::invoke
- Call any callable (function pointer, function, member pointer) with one syntax. From the standard INVOKE concept.
std::apply
- Takes a function-like and a tuple, and unpacks the tuple into the call.
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
Threading
Container Improvements
Smart pointer changes
Other std
datatype improvements:
Misc
C++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
destroy(_at|_n)
, uninitialized_move(_n)
, uninitialized_value_construct(_n)
, uninitialized_default_construct(_n)
- utility code already in most
std
implementations exposed
- Special math functions
std::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughly
gcd
and lcm
std::uncaught_exceptions
- Required if you want to only throw if safe from destructors
std::as_const
std::bool_constant
- A whole bunch of
_v
template variables
std::void_t<T>
- Surprisingly useful when writing templates
std::owner_less<void>
- like
std::less<void>
, but for smart pointers to sort based on contents
std::chrono
polish
std::conjunction
, std::disjunction
, std::negation
exposed
std::not_fn
- Rules for noexcept within
std
- std::is_contiguous_layout, useful for efficient hashing
- std::to_chars/std::from_chars, high performance, locale agnostic number conversion; finally a way to serialize/deserialize to human readable formats (JSON & co)
std::default_order, indirection over std::less
. (breaks ABI of some compilers due to name mangling, removed.)
Traits
Deprecated
Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
Removed:
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
Papers not yet integrated into above:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
Spec changes:
Further reference:
Get list from pandas dataframe column or row?
Assuming the name of the dataframe after reading the excel sheet is df
, take an empty list (e.g. dataList
), iterate through the dataframe row by row and append to your empty list like-
dataList = [] #empty list
for index, row in df.iterrows():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
Or,
dataList = [] #empty list
for row in df.itertuples():
mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
dataList.append(mylist)
No, if you print the dataList
, you will get each rows as a list in the dataList
.
How to declare a global variable in JavaScript
The best way is to use closures
, because the window
object gets very, very cluttered with properties.
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // Private
return {
init : function(Args) {
_args = Args;
// Some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
Why is there still a row limit in Microsoft Excel?
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
- Open workbooks: Limited by available memory and system resources
- Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
- Column width: 255 characters (8 bits)
- Row height: 409 points
- Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
- Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
- Characters in a header or footer: 255 (8 bits)
- Sheets in a workbook: Limited by available memory (default is 1 sheet)
- Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
- Named views in a workbook: Limited by available memory
- Unique cell formats/cell styles: 64,000 (16 bits = 65536)
- Fill styles: 256 (8 bits)
- Line weight and styles: 256 (8 bits)
- Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
- Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
- Names in a workbook: Limited by available memory
- Windows in a workbook: Limited by available memory
- Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
- Panes in a window: 4
- Linked sheets: Limited by available memory
- Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
- Changing cells in a scenario: 32
- Adjustable cells in Solver: 200
- Custom functions: Limited by available memory
- Zoom range: 10 percent to 400 percent
- Reports: Limited by available memory
- Sort references: 64 in a single sort; unlimited when using sequential sorts
- Undo levels: 100
- Fields in a data form: 32
- Workbook parameters: 255 parameters per workbook
- Items displayed in filter drop-down lists: 10,000
In PHP, how can I add an object element to an array?
Do you really need an object? What about:
$myArray[] = array("name" => "my name");
Just use a two-dimensional array.
Output (var_dump):
array(1) {
[0]=>
array(1) {
["name"]=>
string(7) "my name"
}
}
You could access your last entry like this:
echo $myArray[count($myArray) - 1]["name"];
how to convert string to numerical values in mongodb
Three things need to care for:
- parseInt() will store double data type in mongodb. Please use new NumberInt(string).
- in Mongo shell command for bulk usage, yield won't work. Please DO NOT add 'yield'.
- If you already change string to double by parseInt(). It looks like you have no way to change the type to int directly. The solution is a little bit wired: change double to string first and then change back to int by new NumberInt().
How can I get the source directory of a Bash script from within the script itself?
The following will return the current directory of the script
- works if it's sourced, or not sourced
- works if run in the current directory, or some other directory.
- works if relative directories are used.
- works with bash, not sure of other shells.
/tmp/a/b/c $ . ./test.sh
/tmp/a/b/c
/tmp/a/b/c $ . /tmp/a/b/c/test.sh
/tmp/a/b/c
/tmp/a/b/c $ ./test.sh
/tmp/a/b/c
/tmp/a/b/c $ /tmp/a/b/c/test.sh
/tmp/a/b/c
/tmp/a/b/c $ cd
~ $ . /tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ . ../../tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ /tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ ../../tmp/a/b/c/test.sh
/tmp/a/b/c
test.sh
#!/usr/bin/env bash
# snagged from: https://stackoverflow.com/a/51264222/26510
function toAbsPath {
local target
target="$1"
if [ "$target" == "." ]; then
echo "$(pwd)"
elif [ "$target" == ".." ]; then
echo "$(dirname "$(pwd)")"
else
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
fi
}
function getScriptDir(){
local SOURCED
local RESULT
(return 0 2>/dev/null) && SOURCED=1 || SOURCED=0
if [ "$SOURCED" == "1" ]
then
RESULT=$(dirname "$1")
else
RESULT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
fi
toAbsPath "$RESULT"
}
SCRIPT_DIR=$(getScriptDir "$0")
echo "$SCRIPT_DIR"
Implement division with bit-wise operator
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
Error: JavaFX runtime components are missing, and are required to run this application with JDK 11
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.)
You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Cloning a private Github repo
Cloning Private Repository using HTTPS in Year 2020
If maintainer of repository has given Developer access to you on his private library ,you need to first login to https://gitlab.com/users/sign_in with user for which you have received invitation,you will be prompted to change your password,once you change your password then you can successfully clone repository ,pull and push changes to it.
Python: Making a beep noise
Linux.
$ apt-get install beep
$ python
>>> os.system("beep -f 555 -l 460")
OR
$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460
jQuery - add additional parameters on submit (NOT ajax)
You could write a jQuery function which allowed you to add hidden fields to a form:
// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
return this.each(function () {
var input = $("<input>").attr("type", "hidden").attr("name", name).val(value);
$(this).append($(input));
});
};
And then add the hidden field before you submit:
var frm = $("#form").addHidden('SaveAndReturn', 'Save and Return')
.submit();
How do I calculate r-squared using Python and Numpy?
From scipy.stats.linregress source. They use the average sum of squares method.
import numpy as np
x = np.array(x)
y = np.array(y)
# average sum of squares:
ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat
r_num = ssxym
r_den = np.sqrt(ssxm * ssym)
r = r_num / r_den
if r_den == 0.0:
r = 0.0
else:
r = r_num / r_den
if r > 1.0:
r = 1.0
elif r < -1.0:
r = -1.0
Merging dataframes on index with pandas
You can do this with merge
:
df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)
The keyword argument how='outer'
keeps all indices from both frames, filling in missing indices with NaN
. The left_index
and right_index
keyword arguments have the merge be done on the indices. If you get all NaN
in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes
.
The merge
code above produces the following output for me:
V1 V2
A 2012-01-01 12.0 15.0
2012-02-01 14.0 NaN
2012-03-01 NaN 21.0
B 2012-01-01 15.0 24.0
2012-02-01 8.0 9.0
C 2012-01-01 17.0 NaN
2012-02-01 9.0 NaN
D 2012-01-01 NaN 7.0
2012-02-01 NaN 16.0
Where's javax.servlet?
The normal procedure with Eclipse and Java EE webapplications is to install a servlet container (Tomcat, Jetty, etc) or application server (Glassfish (which is bundled in the "Sun Java EE" download), JBoss AS, WebSphere, Weblogic, etc) and integrate it in Eclipse using a (builtin) plugin in the Servers view.
During the creation wizard of a new Dynamic Web Project, you can then pick the integrated server from the list. If you happen to have an existing Dynamic Web Project without a server or want to change the associated one, then you need to modify it in the Targeted Rutimes section of the project's properties.
Either way, Eclipse will automatically place the necessary server-specific libraries in the project's classpath (buildpath).
You should absolutely in no way extract and copy server-specific libraries into /WEB-INF/lib
or even worse the JRE/lib
yourself, to "fix" the compilation errors in Eclipse. It would make your webapplication tied to a specific server and thus completely unportable.
How to find the lowest common ancestor of two nodes in any binary tree?
If someone interested in pseudo code(for university home works) here is one.
GETLCA(BINARYTREE BT, NODE A, NODE B)
IF Root==NIL
return NIL
ENDIF
IF Root==A OR root==B
return Root
ENDIF
Left = GETLCA (Root.Left, A, B)
Right = GETLCA (Root.Right, A, B)
IF Left! = NIL AND Right! = NIL
return root
ELSEIF Left! = NIL
Return Left
ELSE
Return Right
ENDIF
How to 'insert if not exists' in MySQL?
Update or insert without known primary key
If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ...
or REPLACE INTO ...
should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).
But if you have the values for some_column_id
and some_type
, the combination of which are known to be unique. And you want to update some_value
if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:
INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
SELECT id, some_column_id, some_type, some_value
FROM my_table
WHERE some_column_id = ? AND some_type = ?
UNION ALL
SELECT s.id, s.some_column_id, s.some_type, s.some_value
FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?
Basically, the query executes this way (less complicated than it may look):
- Select an existing row via the
WHERE
clause match.
- Union that result with a potential new row (table
s
), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
- If an existing row is found, then the potential new row from table
s
is discarded (due to LIMIT 1 on table t
), and it will always trigger an ON DUPLICATE KEY
which will UPDATE
the some_value
column.
- If an existing row is not found, then the potential new row is inserted (as given by table
s
).
Note: Every table in a relational database should have at least a primary auto-increment id
column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".
MySQL WHERE: how to write "!=" or "not equals"?
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
Counting lines, words, and characters within a text file using Python
Try this:
fname = "feed.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
Back to your code:
fname = "feed.txt"
fname = open('feed.txt', 'r')
what's the point of this? fname
is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.
for line in feed:
lines = line.split('\n')
line
is one line from the file. It does not make sense to split('\n')
it.
HTML Script tag: type or language (or omit both)?
The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.
The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.
Which version of C# am I using
Thanks to @fortesl and this answer
I'm using VS 2019 and it doesn't easily tell you the C# version you are using. I'm working with .Net Core 3.0, and VS 2019 using C# 8 in that environment. But "csc -langversion:?" makes this clear:
D:\>csc -langversion:?
Supported language versions:
default
1
2
3
4
5
6
7.0
7.1
7.2
7.3
8.0 (default)
latestmajor
preview
latest
Not sure what csc -version is identifying:
D:\>csc --version
Microsoft (R) Visual C# Compiler version 3.4.0-beta1-19462-14 (2f21c63b)
Copyright (C) Microsoft Corporation. All rights reserved.
ImportError: No module named - Python
For the Python module import to work, you must have "src" in your path, not "gen_py/lib".
When processing an import like import gen_py.lib
, it looks for a module gen_py
, then looks for a submodule lib
.
As the module gen_py
won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.
Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..')
. You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py
Find the most frequent number in a NumPy array
Here is a general solution that may be applied along an axis, regardless of values, using purely numpy. I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.
import numpy
def mode(ndarray, axis=0):
# Check inputs
ndarray = numpy.asarray(ndarray)
ndim = ndarray.ndim
if ndarray.size == 1:
return (ndarray[0], 1)
elif ndarray.size == 0:
raise Exception('Cannot compute mode on empty array')
try:
axis = range(ndarray.ndim)[axis]
except:
raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))
# If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
if all([ndim == 1,
int(numpy.__version__.split('.')[0]) >= 1,
int(numpy.__version__.split('.')[1]) >= 9]):
modals, counts = numpy.unique(ndarray, return_counts=True)
index = numpy.argmax(counts)
return modals[index], counts[index]
# Sort array
sort = numpy.sort(ndarray, axis=axis)
# Create array to transpose along the axis and get padding shape
transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
shape = list(sort.shape)
shape[axis] = 1
# Create a boolean array along strides of unique values
strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
numpy.diff(sort, axis=axis) == 0,
numpy.zeros(shape=shape, dtype='bool')],
axis=axis).transpose(transpose).ravel()
# Count the stride lengths
counts = numpy.cumsum(strides)
counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
counts[strides] = 0
# Get shape of padded counts and slice to return to the original shape
shape = numpy.array(sort.shape)
shape[axis] += 1
shape = shape[transpose]
slices = [slice(None)] * ndim
slices[axis] = slice(1, None)
# Reshape and compute final counts
counts = counts.reshape(shape).transpose(transpose)[slices] + 1
# Find maximum counts and return modals/counts
slices = [slice(None, i) for i in sort.shape]
del slices[axis]
index = numpy.ogrid[slices]
index.insert(axis, numpy.argmax(counts, axis=axis))
return sort[index], counts[index]
Best way to store password in database
The best security practice is not to store the password at all (not even encrypted), but to store the salted hash (with a unique salt per password) of the encrypted password.
That way it is (practically) impossible to retrieve a plaintext password.
java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config
The error is telling you it cannot find the class because it is not available in your application.
If you are using Maven, make sure you have the dependency for jstl
artifact:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
If you are not using it, just make sure you include the JAR in your classpath. See this answer for download links.
What is the difference between synchronous and asynchronous programming (in node.js)
The function makes the second one asynchronous.
The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.
Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).
What is the difference between git pull and git fetch + git rebase?
TLDR:
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
In reply to your first statement,
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for git fetch
followed by
git merge
FETCH_HEAD" More precisely, git pull
runs git fetch
with the
given parameters and then calls git merge
to merge the retrieved branch
heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
For your second statement/question:
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
Now, if you wanted to ask
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
Save file to specific folder with curl command
For powershell in Windows, you can add relative path + filename to --output
flag:
curl -L http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip
here build_firefox is relative folder.
C#: How do you edit items and subitems in a listview?
Click the items in the list view.
Add a button that will edit the selected items.
Add the code
try
{
LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}
What exactly is nullptr?
Why nullptr in C++11? What is it? Why is NULL not sufficient?
C++ expert Alex Allain says it perfectly here (my emphasis added in bold):
...imagine you have the following two function declarations:
void func(int n);
void func(char *s);
func( NULL ); // guess which function gets called?
Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead. This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. A language feature that looks like a compiler bug is, well, not something you want.
Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers; in other words, wherever you were writing NULL before, you should use nullptr instead. It's no more clear to you, the programmer, (everyone knows what NULL means), but it's more explicit to the compiler, which will no longer see 0s everywhere being used to have special meaning when used as a pointer.
Allain ends his article with:
Regardless of all this--the rule of thumb for C++11 is simply to start using nullptr
whenever you would have otherwise used NULL
in the past.
(My words):
Lastly, don't forget that nullptr
is an object--a class. It can be used anywhere NULL
was used before, but if you need its type for some reason, it's type can be extracted with decltype(nullptr)
, or directly described as std::nullptr_t
, which is simply a typedef
of decltype(nullptr)
.
References:
- Cprogramming.com: Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint
- https://en.cppreference.com/w/cpp/language/decltype
- https://en.cppreference.com/w/cpp/types/nullptr_t
Converting URL to String and back again
Swift 3 (forget about NSURL).
let fileName = "20-01-2017 22:47"
let folderString = "file:///var/mobile/someLongPath"
To make a URL out of a string:
let folder: URL? = Foundation.URL(string: folderString)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath
If we want to add the filename. Note, that appendingPathComponent() adds the percent encoding automatically:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath/20-01-2017%2022:47
When we want to have String but without the root part (pay attention that percent encoding is removed automatically):
let folderWithFilename: String? = folderWithFilename.path
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017 22:47"
If we want to keep the root part we do this (but mind the percent encoding - it is not removed):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
To manually add the percent encoding for a string:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017%2022:47"
To remove the percent encoding:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
The percent-encoding is important because URLs for network requests need them, while URLs to file system won't always work - it depends on the actual method that uses them. The caveat here is that they may be removed or added automatically, so better debug these conversions carefully.
Preferred method to store PHP arrays (json_encode vs serialize)
I know this is late but the answers are pretty old, I thought my benchmarks might help as I have just tested in PHP 7.4
Serialize/Unserialize is much faster than JSON, takes less memory and space, and wins outright in PHP 7.4 but I am not sure my test is the most efficient or the best,
I have basically created a PHP file which returns an array which I encoded, serialised, then decoded and unserialised.
$array = include __DIR__.'/../tests/data/dao/testfiles/testArray.php';
//JSON ENCODE
$json_encode_memory_start = memory_get_usage();
$json_encode_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$encoded = json_encode($array);
}
$json_encode_time_end = microtime(true);
$json_encode_memory_end = memory_get_usage();
$json_encode_time = $json_encode_time_end - $json_encode_time_start;
$json_encode_memory =
$json_encode_memory_end - $json_encode_memory_start;
//SERIALIZE
$serialize_memory_start = memory_get_usage();
$serialize_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$serialized = serialize($array);
}
$serialize_time_end = microtime(true);
$serialize_memory_end = memory_get_usage();
$serialize_time = $serialize_time_end - $serialize_time_start;
$serialize_memory = $serialize_memory_end - $serialize_memory_start;
//Write to file time:
$fpc_memory_start = memory_get_usage();
$fpc_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$fpc_bytes =
file_put_contents(
__DIR__.'/../tests/data/dao/testOneBigFile',
'<?php return '.var_export($array,true).' ?>;'
);
}
$fpc_time_end = microtime(true);
$fpc_memory_end = memory_get_usage();
$fpc_time = $fpc_time_end - $fpc_time_start;
$fpc_memory = $fpc_memory_end - $fpc_memory_start;
//JSON DECODE
$json_decode_memory_start = memory_get_usage();
$json_decode_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$decoded = json_encode($encoded);
}
$json_decode_time_end = microtime(true);
$json_decode_memory_end = memory_get_usage();
$json_decode_time = $json_decode_time_end - $json_decode_time_start;
$json_decode_memory =
$json_decode_memory_end - $json_decode_memory_start;
//UNSERIALIZE
$unserialize_memory_start = memory_get_usage();
$unserialize_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$unserialized = unserialize($serialized);
}
$unserialize_time_end = microtime(true);
$unserialize_memory_end = memory_get_usage();
$unserialize_time = $unserialize_time_end - $unserialize_time_start;
$unserialize_memory =
$unserialize_memory_end - $unserialize_memory_start;
//GET FROM VAR EXPORT:
$var_export_memory_start = memory_get_usage();
$var_export_time_start = microtime(true);
for ($i=0; $i < 20000; $i++) {
$array = include __DIR__.'/../tests/data/dao/testOneBigFile';
}
$var_export_time_end = microtime(true);
$var_export_memory_end = memory_get_usage();
$var_export_time = $var_export_time_end - $var_export_time_start;
$var_export_memory = $var_export_memory_end - $var_export_memory_start;
Results:
Var Export length: 11447
Serialized length: 11541
Json encoded length: 11895
file put contents Bytes: 11464
Json Encode Time: 1.9197590351105
Serialize Time: 0.160325050354
FPC Time: 6.2793469429016
Json Encode Memory: 12288
Serialize Memory: 12288
FPC Memory: 0
JSON Decoded time: 1.7493588924408
UnSerialize Time: 0.19309520721436
Var Export and Include: 3.1974139213562
JSON Decoded memory: 16384
UnSerialize Memory: 14360
Var Export and Include: 192
Relative path to absolute path in C#?
Have you tried Server.MapPath
method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
Reading a text file in MATLAB line by line
You could actually use xlsread
to accomplish this. After first placing your sample data above in a file 'input_file.csv'
, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from xlsread
:
>> [numData,textData,rawData] = xlsread('input_file.csv')
numData = % An array of the numeric values from the file
51.9358 4.1833
51.9354 4.1841
51.9352 4.1846
51.9343 4.1864
51.9343 4.1864
51.9341 4.1869
textData = % A cell array of strings for the text values from the file
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
rawData = % All the data from the file (numeric and text) in a cell array
'ABC' [51.9358] [4.1833]
'ABC' [51.9354] [4.1841]
'ABC' [51.9352] [4.1846]
'ABC' [51.9343] [4.1864]
'ABC' [51.9343] [4.1864]
'ABC' [51.9341] [4.1869]
You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using xlswrite
. Here's an example:
index = sqrt(sum(numData.^2,2)) >= 50; % Find the rows where the point is
% at a distance of 50 or greater
% from the origin
xlswrite('output_file.csv',rawData(index,:)); % Write those rows to a new file
Set textarea width to 100% in bootstrap modal
The provided solutions do resolve the issue. However, they also impact all other textarea
elements with the same styling. I had to solve this and just created a more specific selector. Here is what I came up with to prevent invasive changes.
.modal-content textarea.form-control {
max-width: 100%;
}
While this selector may seem aggressive. It helps restrain the textarea
into the content area of the modal itself.
Additionally, the min-width
solution presented, above, works with basic bootstrap modals, though I had issues when using it with angular-ui-bootstrap modals.
Loading scripts after page load?
For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.
For example:
loadScript("js/myscript.js").then(function(){
// Do whatever you want to do after script load
});
or when used in an async function:
await loadScript("js/myscript.js");
// Do whatever you want to do after script load
In your case you may execute this after document ready:
$(document).ready(async function() {
await loadScript("js/myscript.js");
// Do whatever you want to do after script is ready
});
Function for loadScript:
function loadScript(src) {
return new Promise(function (resolve, reject) {
if ($("script[src='" + src + "']").length === 0) {
var script = document.createElement('script');
script.onload = function () {
resolve();
};
script.onerror = function () {
reject();
};
script.src = src;
document.body.appendChild(script);
} else {
resolve();
}
});
}
Benefit of this way:
- It uses browser cache
- You can load the script file when a user performs an action which needs the script instead loading it always.
How to build query string with Javascript
2k20 update: use Josh's solution with URLSearchParams.toString().
Old answer:
Without jQuery
var params = {
parameter1: 'value_1',
parameter2: 'value 2',
parameter3: 'value&3'
};
var esc = encodeURIComponent;
var query = Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
For browsers that don't support arrow function syntax which requires ES5, change the .map...
line to
.map(function(k) {return esc(k) + '=' + esc(params[k]);})
Add new column in Pandas DataFrame Python
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
how to get GET and POST variables with JQuery?
Just for the record, I wanted to know the answer to this question, so I used a PHP method:
<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
foreach($_GET as $key => $val)
echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>
That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.
Is there a better way to iterate over two lists, getting one element from each list for each iteration?
Another way to do this would be to by using map
.
>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
One difference in using map compared to zip is, with zip the length of new list is
same as the length of shortest list.
For example:
>>> a
[1, 2, 3, 9]
>>> b
[4, 5, 6]
>>> for i,j in zip(a,b):
... print i,j
...
1 4
2 5
3 6
Using map on same data:
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
9 None
How to start an application without waiting in a batch file?
I'm making a guess here, but your start
invocation probably looks like this:
start "\Foo\Bar\Path with spaces in it\program.exe"
This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.
If you use start
with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:
start "" "\Foo\Bar\Path with spaces in it\program.exe"
This is because start
interprets the first quoted argument it finds as the window title for a new console window.
Make a URL-encoded POST request using `http.NewRequest(...)`
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
Wait until page is loaded with Selenium WebDriver for Python
Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.
import time
from selenium import webdriver
def page_has_loaded(driver, sleep_time = 2):
'''
Waits for page to completely load by comparing current page hash values.
'''
def get_page_hash(driver):
'''
Returns html dom hash
'''
# can find element by either 'html' tag or by the html 'root' id
dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
# dom = driver.find_element_by_id('root').get_attribute('innerHTML')
dom_hash = hash(dom.encode('utf-8'))
return dom_hash
page_hash = 'empty'
page_hash_new = ''
# comparing old and new page DOM hash together to verify the page is fully loaded
while page_hash != page_hash_new:
page_hash = get_page_hash(driver)
time.sleep(sleep_time)
page_hash_new = get_page_hash(driver)
print('<page_has_loaded> - page not loaded')
print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))
What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?
For iPhone cocoa-touch projects:
I had this problem and thanks to Eric Farraro's comment, I was able to get it resolved. I was importing a class WSHelper.h in many of my other classes. But I also was importing some of those same classes in my WSHelper.h (circular like Eric said). So, to fix this I moved the imports from my WSHelper.h file to my WSHelper.m file as they weren't really needed in the .h file anyway.
Use of 'const' for function parameters
There's really no reason to make a value-parameter "const" as the function can only modify a copy of the variable anyway.
The reason to use "const" is if you're passing something bigger (e.g. a struct with lots of members) by reference, in which case it ensures that the function can't modify it; or rather, the compiler will complain if you try to modify it in the conventional way. It prevents it from being accidentally modified.
Eclipse: Error ".. overlaps the location of another project.." when trying to create new project
Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!
So you have two solutions:
Move the folder counter_src
somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src
.
Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\
as your root directory. If Eclipse sees a project, you will be able to import it.
convert xml to java object using jaxb (unmarshal)
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified
If you are connecting from Windows machine A to Windows machine B (server with SQL Server installed), and are getting this error, you need to do the following:
On machine B:
1.) turn on the Windows service called "SQL Server Browser" and start the service
2.) in the Windows firewall, enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)
3.) in the Windows firewall, enable incoming port TCP 1433 (in case there is a telnet connection)
4.) in SQL Server Configuration Manager, enable TCP/IP protocol for port 1433
What are passive event listeners?
Passive event listeners are an emerging web standard, new feature
shipped in Chrome 51 that provide a major potential boost to scroll
performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
DOM Spec , Demo Video , Explainer Doc
How can I enable CORS on Django REST Framework
For Django versions > 1.10, according to the documentation, a custom MIDDLEWARE can be written as a function, let's say in the file: yourproject/middleware.py
(as a sibling of settings.py
):
def open_access_middleware(get_response):
def middleware(request):
response = get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
return response
return middleware
and finally, add the python path of this function (w.r.t. the root of your project) to the MIDDLEWARE list in your project's settings.py
:
MIDDLEWARE = [
.
.
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'yourproject.middleware.open_access_middleware'
]
Easy peasy!
Not Equal to This OR That in Lua
Your problem stems from a misunderstanding of the or
operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1
, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1)
or x ~= 0 or 1
it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or
has a lower precedence than ~=
, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1)
, the interpreter will first compute 0 or 1
(because of the parentheses) and then x ~=
the result of the first computation, and in the second example, it will compute x ~= 0
and then apply the result of that computation to or 1
.
The logical operator or
"returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~=
is the inverse of the equality operator ==
; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1)
will decompose to x ~= 0
(after applying the or
operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1
will first evaluate x ~= 0
(which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1
or true or 1
. In the first case, the statement will return 1
, and in the second case, the statement will return true
. Because control structures in Lua only consider nil
and false
to be false, and anything else to be true, this will always enter the if
statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1
. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1
, and what this erroneous expression would return!
Android Gradle Could not reserve enough space for object heap
Faced this issue on Android studio 4.1, windows 10.
The solution that worked for me:
1 - Go to gradle.properties file which is in the root directory of the project.
2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio
decide on the best compatible option.
3 - Now close any open project from File -> close project.
4 - On the Welcome window, Go to Configure > Settings.
5 - Go to Build, Execution, Deployment > Compiler
6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.
Now close the android studio and restart it. The issue will be gone.
Color text in discord
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Option #1 (Markdown code-blocks)
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Option #2 (Embeds)
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
(Embed Cheat-sheet)
Can clearInterval() be called inside setInterval()?
Yes you can. You can even test it:
_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
console.log(++i);_x000D_
if (i === 5) clearInterval(timer);_x000D_
console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_
In this example, this timer clears when i
reaches 5.
What good are SQL Server schemas?
At an ORACLE shop I worked at for many years, schemas were used to encapsulate procedures (and packages) that applied to different front-end applications. A different 'API' schema for each application often made sense as the use cases, users, and system requirements were quite different. For example, one 'API' schema was for a development/configuration application only to be used by developers. Another 'API' schema was for accessing the client data via views and procedures (searches). Another 'API' schema encapsulated code that was used for synchronizing development/configuration and client data with an application that had it's own database. Some of these 'API' schemas, under the covers, would still share common procedures and functions with eachother (via other 'COMMON' schemas) where it made sense.
I will say that not having a schema is probably not the end of the world, though it can be very helpful. Really, it is the lack of packages in SQL Server that really creates problems in my mind... but that is a different topic.
How to get attribute of element from Selenium?
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
Hide text using css
This worked for me with span (knockout validation).
<span class="validationMessage">This field is required.</span>
.validationMessage {
background-image: url('images/exclamation.png');
background-repeat: no-repeat;
margin-left: 5px;
width: 16px;
height: 16px;
vertical-align: top;
/* Hide the text. */
display: inline-block;
overflow: hidden;
font-size: 0px;
}
Get last 5 characters in a string
in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)
Dim str as String = "Hello World"
Msgbox(Microsoft.VisualBasic.Right(str,5))
'World"
Same goes for Left() too.
Passing Arrays to Function in C++
firstarray
and secondarray
are converted to a pointer to int, when passed to printarray()
.
printarray(int arg[], ...)
is equivalent to printarray(int *arg, ...)
However, this is not specific to C++. C has the same rules for passing array names to a function.
Difference between const reference and normal parameter
The first method passes n
by value, i.e. a copy of n
is sent to the function. The second one passes n
by reference which basically means that a pointer to the n
with which the function is called is sent to the function.
For integral types like int
it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.
Regex that accepts only numbers (0-9) and NO characters
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
Change CSS properties on click
In your code you aren't using jquery, so, if you want to use it, yo need something like...
$('#foo').css({'background-color' : 'red', 'color' : 'white', 'font-size' : '44px'});
http://api.jquery.com/css/
Other way, if you are not using jquery, you need to do ...
document.getElementById('foo').style = 'background-color: red; color: white; font-size: 44px';
What's the difference between Invoke() and BeginInvoke()
Just to give a short, working example to see an effect of their difference
new Thread(foo).Start();
private void foo()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
myTextBox.Text = "bing";
Thread.Sleep(TimeSpan.FromSeconds(3));
});
MessageBox.Show("done");
}
If use BeginInvoke, MessageBox pops simultaneous to the text update. If use Invoke, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (BeginInvoke) and a synchronous (Invoke) call.
What is the meaning of "operator bool() const"
Member functions of the form
operator TypeName()
are conversion operators. They allow objects of the class type to be used as if they were of type TypeName
and when they are, they are converted to TypeName
using the conversion function.
In this particular case, operator bool()
allows an object of the class type to be used as if it were a bool
. For example, if you have an object of the class type named obj
, you can use it as
if (obj)
This will call the operator bool()
, return the result, and use the result as the condition of the if
.
It should be noted that operator bool()
is A Very Bad Idea and you should really never use it. For a detailed explanation as to why it is bad and for the solution to the problem, see "The Safe Bool Idiom."
(C++0x, the forthcoming revision of the C++ Standard, adds support for explicit conversion operators. These will allow you to write a safe explicit operator bool()
that works correctly without having to jump through the hoops of implementing the Safe Bool Idiom.)