What is exactly the base pointer and stack pointer? To what do they point?
Long time since I've done Assembly programming, but this link might be useful...
The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.
The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.
Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.
Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.
Calling a function when ng-repeat has finished
If you need to call different functions for different ng-repeats on the same controller you can try something like this:
The directive:
var module = angular.module('testApp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit(attr.broadcasteventname ? attr.broadcasteventname : 'ngRepeatFinished');
});
}
}
}
});
In your controller, catch events with $on:
$scope.$on('ngRepeatBroadcast1', function(ngRepeatFinishedEvent) {
// Do something
});
$scope.$on('ngRepeatBroadcast2', function(ngRepeatFinishedEvent) {
// Do something
});
In your template with multiple ng-repeat
<div ng-repeat="item in collection1" on-finish-render broadcasteventname="ngRepeatBroadcast1">
<div>{{item.name}}}<div>
</div>
<div ng-repeat="item in collection2" on-finish-render broadcasteventname="ngRepeatBroadcast2">
<div>{{item.name}}}<div>
</div>
Throwing exceptions from constructors
It is OK to throw from your constructor, but you should make sure that
your object is constructed after main has started and before it
finishes:
class A
{
public:
A () {
throw int ();
}
};
A a; // Implementation defined behaviour if exception is thrown (15.3/13)
int main ()
{
try
{
// Exception for 'a' not caught here.
}
catch (int)
{
}
}
Get raw POST body in Python Flask regardless of Content-Type header
request.data
will be empty if request.headers["Content-Type"]
is recognized as form data, which will be parsed into request.form
. To get the raw data regardless of content type, use request.get_data()
.
request.data
calls request.get_data(parse_form_data=True)
, which results in the different behavior for form data.
AND/OR in Python?
if input == 'a':
for char in 'abc':
if char in some_list:
some_list.remove(char)
Arrays vs Vectors: Introductory Similarities and Differences
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size.
when using an array, you specify its size upon declaration:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
Use space as a delimiter with cut command
To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:
Two distinct mechanisms come into play here:
(a) whether cut
itself requires the delimiter (space, in this case) passed to the -d
option to be a separate argument or whether it's acceptable to append it directly to -d
.
(b) how the shell generally parses arguments before passing them to the command being invoked.
(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)
If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.
In other words: In this case, because -d
's option-argument is mandatory, you can choose whether to specify the delimiter as:
- (s) EITHER: a separate argument
- (d) OR: as a value directly attached to
-d
.
Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:
With approach (s), all of the following forms are EQUIVALENT:
-d ' '
-d " "
-d \<space> # <space> used to represent an actual space for technical reasons
With approach (d), all of the following forms are EQUIVALENT:
-d' '
-d" "
"-d "
'-d '
d\<space>
The equivalence is explained by the shell's string-literal processing:
All solutions above result in the exact same string (in each group) by the time cut
sees them:
(s): cut
sees -d
, as its own argument, followed by a separate argument that contains a space char - without quotes or \
prefix!.
(d): cut
sees -d
plus a space char - without quotes or \
prefix! - as part of the same argument.
The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:
- The shell allows literal to be specified as is through a mechanism called quoting, which can take several forms:
- single-quoted strings: the contents inside
'...'
is taken literally and forms a single argument
- double-quoted strings: the contents inside
"..."
also forms a single argument, but is subject to interpolation (expands variable references such as $var
, command substitutions ($(...)
or `...`
), or arithmetic expansions ($(( ... ))
).
\
-quoting of individual characters: a \
preceding a single character causes that character to be interpreted as a literal.
- Quoting is complemented by quote removal, which means that once the shell has parsed a command line, it removes the quote characters from the arguments (enclosing
'...'
or "..."
or \
instances) - thus, the command being invoked never sees the quote characters.
get number of columns of a particular row in given excel using Java
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot
Alternatively, consider using drawViewHierarchyInRect
:
Swift:
extension UIImage{
class func renderUIViewToImage(viewToBeRendered: UIView) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(viewToBeRendered.bounds.size, true, 0.0)
viewToBeRendered.drawViewHierarchyInRect(viewToBeRendered.bounds, afterScreenUpdates: true)
viewToBeRendered.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage
}
}
Objective-C:
- (UIImage *)snapshot:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Also see:
Reading Excel files from C#
you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manually).
then you could automate that from c#.
and once its in csv, the c# program can grok that.
(also, if someone asks you to program in excel, it's best to pretend you don't know how)
(edit: ah yes, rob and ryan are both right)
Executing Javascript from Python
One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.
PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.
pip install py-mini-racer
from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
return a+c+b;
}
""")
ctx.call("escramble_758")
And yes, you have to replace document.write
with return
as others suggested
C++ vector's insert & push_back difference
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
void operator could be used here.
Instead of:
React.useEffect(() => {
async function fetchData() {
}
fetchData();
}, []);
or
React.useEffect(() => {
(async function fetchData() {
})()
}, []);
you could write:
React.useEffect(() => {
void async function fetchData() {
}();
}, []);
It is a little bit cleaner and prettier.
Async effects could cause memory leaks so it is important to perform cleanup on component unmount. In case of fetch this could look like this:
function App() {
const [ data, setData ] = React.useState([]);
React.useEffect(() => {
const abortController = new AbortController();
void async function fetchData() {
try {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
const response = await fetch(url, { signal: abortController.signal });
setData(await response.json());
} catch (error) {
console.log('error', error);
}
}();
return () => {
abortController.abort(); // cancel pending fetch request on component unmount
};
}, []);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
HttpURLConnection timeout settings
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
How to set HTML Auto Indent format on Sublime Text 3?
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
Set cookies for cross origin requests
For express, upgrade your express library to 4.17.1
which is the latest stable version. Then;
In CorsOption: Set origin
to your localhost url or your frontend production url and credentials
to true
e.g
const corsOptions = {
origin: config.get("origin"),
credentials: true,
};
I set my origin dynamically using config npm module.
Then , in res.cookie:
For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly
to true
for http cookie to prevent XSS attack and other useful options depending on your use case.
For production environment, you need to set sameSite
to none
for cross-origin request and secure
to true
. Remember sameSite
works with express latest version only as at now and latest chrome version only set cookie over https
, thus the need for secure option.
Here is how I made mine dynamic
res
.cookie("access_token", token, {
httpOnly: true,
sameSite: app.get("env") === "development" ? true : "none",
secure: app.get("env") === "development" ? false : true,
})
Best Practice: Initialize JUnit class fields in setUp() or at declaration?
I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass
annotation (optimize later).
Example of optimization using the @BeforeClass
setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass
and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.
Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.
Trigger change() event when setting <select>'s value with val() function
The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?
As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.
If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)
Added this solution:
Another possible solution would be to create your own .val()
wrapper function and have it trigger a custom event after setting the value through .val()
, then when you use your .val() wrapper to set the value of a <select>
it will trigger your custom event which you can trap and handle.
Be sure to return this
, so it is chainable in jQuery fashion
send/post xml file using curl command line
You can using option --data with file.
Write xml content to a file named is soap_get.xml and using curl command to send request:
curl -X POST --header "Content-Type:text/xml;charset=UTF-8" --data @soap_get.xml your_url
Count number of rows by group using dplyr
There's a special function n()
in dplyr to count rows (potentially within groups):
library(dplyr)
mtcars %>%
group_by(cyl, gear) %>%
summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
But dplyr also offers a handy count
function which does exactly the same with less typing:
count(mtcars, cyl, gear) # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
# cyl gear n
# (dbl) (dbl) (int)
#1 4 3 1
#2 4 4 8
#3 4 5 2
#4 6 3 2
#5 6 4 4
#6 6 5 1
#7 8 3 12
#8 8 5 2
How to create a DataFrame from a text file in Spark
You can read a file to have an RDD and then assign schema to it. Two common ways to creating schema are either using a case class or a Schema object [my preferred one]. Follows the quick snippets of code that you may use.
Case Class approach
case class Test(id:String,name:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()
Schema Approach
import org.apache.spark.sql.types._
val schemaString = "id name"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)
val dfWithSchema = sparkSess.read.option("header","false").schema(schema).csv("file.txt")
dfWithSchema.show()
The second one is my preferred approach since case class has a limitation of max 22 fields and this will be a problem if your file has more than 22 fields!
How to lookup JNDI resources on WebLogic?
java
is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env
, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource");
if the resource reference name is jdbc/myDataSource
).
To avoid having to change your legacy code I think if you register the datasource with the name myDataSource
(remove the jdbc/
) you should be fine. Let me know if that works.
Http Basic Authentication in Java using HttpClient?
while using Header array
String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
new BasicHeader("Authorization", "Basic " +auth)
};
check if a key exists in a bucket in s3 using boto3
The easiest way I found (and probably the most efficient) is this:
import boto3
from botocore.errorfactory import ClientError
s3 = boto3.client('s3')
try:
s3.head_object(Bucket='bucket_name', Key='file_path')
except ClientError:
# Not found
pass
Why does cURL return error "(23) Failed writing body"?
If you are trying something similar like source <( curl -sS $url )
and getting the (23) Failed writing body
error, it is because sourcing a process substitution doesn't work in bash 3.2
(the default for macOS).
Instead, you can use this workaround.
source /dev/stdin <<<"$( curl -sS $url )"
How to make a flex item not fill the height of the flex container?
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
_x000D_
_x000D_
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
Spring Boot @Value Properties
I had the same problem like you. Here's my error code.
@Component
public class GetExprsAndEnvId {
@Value("hello")
private String Mysecret;
public GetExprsAndEnvId() {
System.out.println("construct");
}
public void print(){
System.out.println(this.Mysecret);
}
public String getMysecret() {
return Mysecret;
}
public void setMysecret(String mysecret) {
Mysecret = mysecret;
}
}
This is no problem like this, but
we need to use it like this:
@Autowired
private GetExprsAndEnvId getExprsAndEnvId;
not like this:
getExprsAndEnvId = new GetExprsAndEnvId();
Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.
CURL ERROR: Recv failure: Connection reset by peer - PHP Curl
This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.
If this server is on a secure network, please have a look at firewall rules of the server.
Thanks
Ganesh PNS
PostgreSQL DISTINCT ON with different ORDER BY
You can order by address_id in an subquery, then order by what you want in an outer query.
SELECT * FROM
(SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM "purchases"
WHERE "purchases"."product_id" = 1 ORDER BY address_id DESC )
ORDER BY purchased_at DESC
Running script upon login mac
tl;dr: use OSX's native process launcher and manager, launchd
.
To do so, make a launchctl
daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.
- Create a
.plist
file according to the instructions in the Apple Dev docs here or more detail below.
- Place in
~/Library/LaunchAgents
- Log in (or run manually via
launchctl load [filename.plist]
)
For more on launchd
, the wikipedia article is quite good and describes the system and its advantages over other older systems.
Here's the specific plist file to run a script at login.
Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.loginscript</string>
<key>ProgramArguments</key>
<array><string>/path/to/executable/script.sh</string></array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Replace the <string>
after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh
to ensure it is for all users).
Save as ~/Library/LaunchAgents/com.user.loginscript.plist
Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist
and log out/in to test (or to test directly, run launchctl start com.user.loginscript
)
Tail /var/log/system.log
for error messages.
The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons
) are run on boot.
If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.
"Parse Error : There is a problem parsing the package" while installing Android application
As a couple of the other answers have mentioned, there can be problems when installing from the SD card. In my case I was distributing my app via email attachment, and it usually worked fine. Just open the email and download the attachment (it apparently goes to the SD card) and click on it again and it gets installed.
But then one day it didn't work, and it turned out it was because I had the phone connected to my development PC via USB, and that placed the SD card in a different mode or something. So the solution was simply to disconnect the phone from the PC and then send the e-mail again and download the attachment again. Or else place the USB connection in "charging only" mode so the SD card is not "connected" to the PC.
pretty-print JSON using JavaScript
Couldn't find any solution that had good syntax highlighting for the console, so here's my 2p
Install & Add cli-highlight dependency
npm install cli-highlight --save
Define logjson globally
const highlight = require('cli-highlight').highlight
console.logjson = (obj) => console.log(
highlight( JSON.stringify(obj, null, 4),
{ language: 'json', ignoreIllegals: true } ));
Use
console.logjson({foo: "bar", someArray: ["string1", "string2"]});
how to make div click-able?
As you updated your question, here's an obtrustive example:
window.onload = function()
{
var div = document.getElementById("mydiv");
div.style.cursor = 'pointer';
div.onmouseover = function()
{
div.style.background = "#ff00ff";
};
}
Android Notification Sound
You have to use builder.setSound
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
}
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder.setSound(alarmSound);
manager.notify(1, builder.build());
What are the minimum margins most printers can handle?
As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.
Failed to resolve version for org.apache.maven.archetypes
The right way to solve my problem are as followed. Hope to be helpful to others.
the errors informations.
Could not resolve archetype org.apache.maven.archetypes:maven-archetype-webapp:1.0 from any of the configured repositories. Could not resolve artifact org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0 Failure to transfer org.apache.maven.archetypes:maven-archetype-webapp:pom:1.0
Delete the maven-archetype-webapp:1.0 in the directory ~/.m2/repository/org/Apache/maven/archetypes
Download the maven-archetype-webapp:1.0 and the maven-archetype-webapp-1.0.pom from
http://maven.ibiblio.org/maven2/org/apache/maven/archetypes/maven-archetype-webapp/1.0/
execute mvn install:install-file -DgroupId=org.apache.maven.archetypes -DartifactId=maven-archetype-quickstart -Dversion=1.1 -Dpackaging=jar -Dfile=???maven-archetype-webapp-1.0???.
try to establish a maven project of webapp to test whether the problem has solved.
Variably modified array at file scope
As it is already explained in other answers, const
in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum
as a real constant in C:
enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};
Get driving directions using Google Maps API v2
This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
Trigger a Travis-CI rebuild without pushing a commit?
I have found another way of forcing re-run CI builds and other triggers:
- Run
git commit --amend --no-edit
without any changes. This will recreate the last commit in the current branch.
git push --force-with-lease origin pr-branch
.
Set title background color
There is another way to change the background color, however it is a hack and might fail on future versions of Android if the View hierarchy of the Window and its title is changed. However, the code won't crash, just miss setting the wanted color, in such a case.
In your Activity, like onCreate, do:
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.rgb(0x88, 0x33, 0x33));
}
}
How to align form at the center of the page in html/css
I would just use table and not the form. Its done by using margin.
table {
margin: 0 auto;
}
also try using something like
table td {
padding-bottom: 5px;
}
instead of <br />
and also your input should end with />
e.g:
<input type="password" name="cpwd" />
Converting JavaScript object with numeric keys into array
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
FIDDLE
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
FIDDLE
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse
would be necessary as well.
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
What's the best practice for putting multiple projects in a git repository?
While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.
Solution 1
A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.
git checkout --orphan BRANCHNAME
This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.
Now for whatever reason, git needs a bit of cleanup after an orphan checkout.
rm .git/index
rm -r *
Make sure everything is committed before deleting
Once the orphan branch is clean, you can use it normally.
Solution 2
Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.
# repo 1
git push origin master:master-1
# repo 2
git push origin master:master-2
How can I generate a list or array of sequential integers in Java?
This is the shortest I could find.
List version
public List<Integer> makeSequence(int begin, int end)
{
List<Integer> ret = new ArrayList<Integer>(++end - begin);
for (; begin < end; )
ret.add(begin++);
return ret;
}
Array Version
public int[] makeSequence(int begin, int end)
{
if(end < begin)
return null;
int[] ret = new int[++end - begin];
for (int i=0; begin < end; )
ret[i++] = begin++;
return ret;
}
AngularJS ngClass conditional
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
How to return JSON with ASP.NET & jQuery
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
What version of MongoDB is installed on Ubuntu
When you entered in mongo shell using "mongo" command , that time only you will notice
MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2
also you can try command,in mongo shell ,
db.version()
What is href="#" and why is it used?
Putting the "#" symbol as the href for something means that it points not to a different URL, but rather to another id or name tag on the same page. For example:
<a href="#bottomOfPage">Click to go to the bottom of the page</a>
blah blah
blah blah
...
<a id="bottomOfPage"></a>
However, if there is no id or name then it goes "no where."
Here's another similar question asked HTML Anchors with 'name' or 'id'?
Regexp Java for password validation
Sample code block for strong password:
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?=\\S+$).{6,18}
- at least 6 digits
- up to 18 digits
- one number
- one lowercase
- one uppercase
- can contain all special characters
Go: panic: runtime error: invalid memory address or nil pointer dereference
Since I got here with my problem I will add this answer although it is not exactly relevant to the original question. When you are implementing an interface make sure you do not forget to add the type pointer on your member function declarations. Example:
type AnimalSounder interface {
MakeNoise()
}
type Dog struct {
Name string
mean bool
BarkStrength int
}
func (dog *Dog) MakeNoise() {
//implementation
}
I forgot the *(dog Dog) part, I do not recommend it. Then you get into ugly trouble when calling MakeNoice on an AnimalSounder interface variable of type Dog.
Skip certain tables with mysqldump
You can use the --ignore-table option. So you could do
mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql
There is no whitespace after -p
(this is not a typo).
To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.
If you want an alternative way to ignore multiple tables you can use a script like this:
#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
How to change icon on Google map marker
we can change the icon of markers, i did it on right click event.
Lets see if it works for you...
// Create a Marker
var marker = new google.maps.Marker({
position: location,
map: map,
title:'Sample Tool Tip'
});
// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
marker.setIcon('blank.png'); // set image path here...
});
ImportError: cannot import name
This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.
You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:
%reset
or menu->restart terminal
How to print all information from an HTTP request to the screen, in PHP
Putting together answers from Peter Bailey and Cmyker you get something like:
<?php
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$chunks = explode('_', $key);
$header = '';
for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
$header .= ucfirst(strtolower($chunks[$i])).'-';
}
$header .= ucfirst(strtolower($chunks[$i])).': '.$value;
echo $header."\n";
}
}
$body = file_get_contents('php://input');
if ($body != '') {
print("\n$body\n\n");
}
?>
which works with the php -S
built-in webserver, which is quite a handy feature of PHP.
Url decode UTF-8 in Python
You can achieve an expected result with requests
library as well:
import requests
url = "http://www.mywebsite.org/Data%20Set.zip"
print(f"Before: {url}")
print(f"After: {requests.utils.unquote(url)}")
Output:
$ python3 test_url_unquote.py
Before: http://www.mywebsite.org/Data%20Set.zip
After: http://www.mywebsite.org/Data Set.zip
Might be handy if you are already using requests
, without using another library for this job.
HTML tag inside JavaScript
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write
to display things on browser.
Also if your document.write
exceeds one line, make sure to put concatenation +
at the end of each line.
Example
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>
Regular Expression to reformat a US phone number in Javascript
You can use this functions to check valid phone numbers and normalize them:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
How do I use CSS with a ruby on rails application?
The original post might have been true back in 2009, but now it is actually incorrect now, and no linking is even required for the stylesheet as I see mentioned in some of the other responses. Rails will now do this for you by default.
- Place any new sheet .css (or other) in app/assets/stylesheets
- Test your server with rails-root/scripts/rails server and you'll see the link is added by rails itself.
You can test this with a path in your browser like testserverpath:3000/assets/filename_to_test.css?body=1
Where is array's length property defined?
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
field length
, which contains the number of components of the array. length
may be positive or zero.
The public
method clone
, which overrides the method of the same name in class Object
and throws no checked exceptions. The return type of the clone
method of an array type T[]
is T[]
.
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method of Object
that is not inherited is its clone
method.
Resources:
How to Get True Size of MySQL Database?
If you use phpMyAdmin, it can tell you this information.
Just go to "Databases" (menu on top) and click "Enable Statistics".
You will see something like this:
This will probably lose some accuracy as the sizes go up, but it should be accurate enough for your purposes.
Can a java file have more than one class?
A .java file is called a compilation unit.
Each compilation unit may contain any number of top-level classes and interfaces.
If there are no public top-level types then the compilation unit can be named anything.
//Multiple.java
//preceding package and import statements
class MyClass{...}
interface Service{...}
...
//No public classes or interfaces
...
There can be only one public class/interface in a compilation unit. The c.u. must be named exactly as this public top-level type.
//Test.java
//named exactly as the public class Test
public class Test{...}
//!public class Operations{...}
interface Selector{...}
...
//Other non-public classes/interfaces
Important points about the main method - part 1
Part 2
(Points regarding the number of classes and their access levels covered in part 2)
simulate background-size:cover on <video> or <img>
I just solved this and wanted to share. This works with Bootstrap 4. It works with img
but I didn't test it with video
. Here is the HAML and SCSS
HAML
.container
.detail-img.d-flex.align-items-center
%img{src: 'http://placehold.it/1000x700'}
SCSS
.detail-img { // simulate background: center/cover
max-height: 400px;
overflow: hidden;
img {
width: 100%;
}
}
_x000D_
_x000D_
/* simulate background: center/cover */_x000D_
.center-cover { _x000D_
max-height: 400px;_x000D_
overflow: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.center-cover img {_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="center-cover d-flex align-items-center">_x000D_
<img src="http://placehold.it/1000x700">_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
WPF - add static items to a combo box
Like this:
<ComboBox Text="MyCombo">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
Prevent Caching in ASP.NET MVC for specific actions using an attribute
For MVC6 (DNX), there is no System.Web.OutputCacheAttribute
Note: when you set NoStore
Duration parameter is not considered. It is possible to set an initial duration for first registration and override this with custom attributes.
But we have Microsoft.AspNet.Mvc.Filters.ResponseCacheFilter
public void ConfigureServices(IServiceCollection services)
...
services.AddMvc(config=>
{
config.Filters.Add(
new ResponseCacheFilter(
new CacheProfile() {
NoStore=true
}));
}
...
)
It is possible to override initial filter with a custom attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var filter=filterContext.Filters.Where(t => t.GetType() == typeof(ResponseCacheFilter)).FirstOrDefault();
if (filter != null)
{
ResponseCacheFilter f = (ResponseCacheFilter)filter;
f.NoStore = true;
//f.Duration = 0;
}
base.OnResultExecuting(filterContext);
}
}
Here is a use case
[NoCache]
[HttpGet]
public JsonResult Get()
{
return Json(new DateTime());
}
Java word count program
Not sure if there is a drawback, but this worked for me...
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
String trimmed = userInput.trim();
int count = 1;
for (int i = 0; i < trimmed.length(); i++) {
if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
count++;
}
}
Running command line silently with VbScript and getting output?
Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim filepath As String = path + "\" + "your.bat"
' Create the file if it does not exist.
If File.Exists(filepath) = False Then
File.Create(filepath)
Else
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(filepath)
If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Remove from Readonly the file.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer RO.", filepath)
Else
End If
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer Hidden.", filepath)
Else
End If
Dim sr As New StreamReader(filepath)
Dim input As String = sr.ReadToEnd()
sr.Close()
Dim output As String = "@echo off"
Dim output1 As String = vbNewLine + "your 1st cmd code"
Dim output2 As String = vbNewLine + "your 2nd cmd code "
Dim output3 As String = vbNewLine + "exit"
Dim sw As New StreamWriter(filepath)
sw.Write(output)
sw.Write(output1)
sw.Write(output2)
sw.Write(output3)
sw.Close()
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
Else
' Hide the file.
File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", filepath)
End If
Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
procInfo.WindowStyle = ProcessWindowStyle.Minimized
procInfo.WindowStyle = ProcessWindowStyle.Hidden
procInfo.CreateNoWindow = True
procInfo.FileName = path + "\" + "your.bat"
procInfo.Verb = "runas"
Process.Start(procInfo)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written
Using RegEX To Prefix And Append In Notepad++
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
Check if value exists in enum in TypeScript
For anyone who comes here looking to validate if a string is one of the values of an enum and type convert it, I wrote this function that returns the proper type and returns undefined
if the string is not in the enum.
function keepIfInEnum<T>(
value: string,
enumObject: { [key: string]: T }
) {
if (Object.values(enumObject).includes((value as unknown) as T)) {
return (value as unknown) as T;
} else {
return undefined;
}
}
As an example:
enum StringEnum {
value1 = 'FirstValue',
value2 = 'SecondValue',
}
keepIfInEnum<StringEnum>('FirstValue', StringEnum) // 'FirstValue'
keepIfInEnum<StringEnum>('OtherValue', StringEnum) // undefined
What REST PUT/POST/DELETE calls should return by a convention?
By the RFC7231 it does not matter and may be empty
How we implement json api standard based solution in the project:
post/put: outputs object attributes as in get (field filter/relations applies the same)
delete: data only contains null (for its a representation of missing object)
status for standard delete: 200
If (Array.Length == 0)
You can use .Length
== 0 if the length is empty and the array exists, but are you sure it's not null?
What is the function of the push / pop instructions used on registers in x86 assembly?
Pushing and popping registers are behind the scenes equivalent to this:
push reg <= same as => sub $8,%rsp # subtract 8 from rsp
mov reg,(%rsp) # store, using rsp as the address
pop reg <= same as=> mov (%rsp),reg # load, using rsp as the address
add $8,%rsp # add 8 to the rsp
Note this is x86-64 At&t syntax.
Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.
Check if a Class Object is subclass of another Class Object in Java
This is an improved version of @schuttek's answer. It is improved because it correctly return false for primitives (e.g. isSubclassOf(int.class, Object.class) => false) and also correctly handles interfaces (e.g. isSubclassOf(HashMap.class, Map.class) => true).
static public boolean isSubclassOf(final Class<?> clazz, final Class<?> possibleSuperClass)
{
if (clazz == null || possibleSuperClass == null)
{
return false;
}
else if (clazz.equals(possibleSuperClass))
{
return true;
}
else
{
final boolean isSubclass = isSubclassOf(clazz.getSuperclass(), possibleSuperClass);
if (!isSubclass && clazz.getInterfaces() != null)
{
for (final Class<?> inter : clazz.getInterfaces())
{
if (isSubclassOf(inter, possibleSuperClass))
{
return true;
}
}
}
return isSubclass;
}
}
Get battery level and state in Android
Other answers didn't mention how to access battery status (chraging or not).
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
How can I override the OnBeforeUnload dialog and replace it with my own?
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
Finding the mode of a list
#function to find mode
def mode(data):
modecnt=0
#for count of number appearing
for i in range(len(data)):
icount=data.count(data[i])
#for storing count of each number in list will be stored
if icount>modecnt:
#the loop activates if current count if greater than the previous count
mode=data[i]
#here the mode of number is stored
modecnt=icount
#count of the appearance of number is stored
return mode
print mode(data1)
How to check if text fields are empty on form submit using jQuery?
function isEmpty(val) {
if(val.length ==0 || val.length ==null){
return 'emptyForm';
}else{
return 'not emptyForm';
}
}
$(document).ready(function(){enter code here
$( "form" ).submit(function( event ) {
$('input').each(function(){
var getInputVal = $(this).val();
if(isEmpty(getInputVal) =='emptyForm'){
alert(isEmpty(getInputVal));
}else{
alert(isEmpty(getInputVal));
}
});
event.preventDefault();
});
});
In JavaScript can I make a "click" event fire programmatically for a file input element?
JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/
_x000D_
_x000D_
popFileSelector = function() {_x000D_
var el = document.getElementById("fileElem");_x000D_
if (el) {_x000D_
el.click(); _x000D_
}_x000D_
};_x000D_
_x000D_
window.popRightAway = function() {_x000D_
document.getElementById('log').innerHTML += 'I am right away!<br />';_x000D_
popFileSelector();_x000D_
};_x000D_
_x000D_
window.popWithDelay = function() {_x000D_
document.getElementById('log').innerHTML += 'I am gonna delay!<br />';_x000D_
window.setTimeout(function() {_x000D_
document.getElementById('log').innerHTML += 'I was delayed!<br />';_x000D_
popFileSelector();_x000D_
}, 1000);_x000D_
};
_x000D_
<body>_x000D_
<form>_x000D_
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />_x000D_
</form>_x000D_
<a onclick="popRightAway()" href="#">Pop Now</a>_x000D_
<br />_x000D_
<a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>_x000D_
<div id="log">Log: <br /></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_
How to draw an overlay on a SurfaceView used by Camera on Android?
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
- Put your
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axis
- Move your drawing logic
into a separate custom
View
class
- Add an instance of the custom View
class to the layout XML file as a
child of the
FrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
Remove part of a string
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
Create GUI using Eclipse (Java)
Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
C# event with custom arguments
EventHandler
receives EventArgs
as a parameter. To resolve your problem, you can build your own MyEventArgs
.
public enum MyEvents
{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEvents MyEvent { get; set; }
}
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents ev)
{
if (EventTriggered != null)
{
EventTriggered(null, new MyEventArgs { MyEvent = ev });
}
}
Lotus Notes email as an attachment to another email
The only way I know is this:
Reassure that preferences | Basic Notes Client configuration | Drag and drop saves as eml file is checked
1) Drag your email to e.g. your desktop or to an explorer instance (will be saved as an eml file).
2) Attach this file to your opened email by either selecting it with the paperclip menu item or drag 'n drop the file into the opened email.
How to hide a status bar in iOS?
-(void) viewWillAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How to check that an element is in a std::set?
You can also check whether an element is in set or not while inserting the element.
The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
For example: Suppose the set already has 20 as an element.
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator,bool> ret;
ret=myset.insert(20);
if(ret.second==false)
{
//do nothing
}
else
{
//do something
}
it=ret.first //points to element 20 already in set.
If the element is newly inserted than pair::first will point to the position of new element in set.
What does the ^ (XOR) operator do?
^
is the Python bitwise XOR operator. It is how you spell XOR
in python:
>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0
XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:
>>> 10 ^ 5
15
>>> 15 ^ 5
10
where 5
is the mask; (input XOR mask) XOR mask gives you the input again.
Play an audio file using jQuery when a button is clicked
Which approach?
You can play audio with <audio>
tag or <object>
or <embed>
.
Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play()
and pause it with .pause()
.
Things we used
We will use canplay
event to detect our file is ready to be played.
There is no .stop()
function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime
. We will use this line in our example audioElement.currentTime = 0;
. To achieve .stop()
function we first pause the file then reset its time.
We may want to know the length of the audio file and the current playing time. We already learnt .currentTime
above, to learn its length we use .duration
.
Example Guide
- When document is ready we created an audio element dynamically
- We set its source with the audio we want to play.
- We used 'ended' event to start file again.
When the currentTime is equal to its duration audio file will stop
playing. Whenever you use play()
, it will start from the beginning.
- We used
timeupdate
event to update current time whenever audio .currentTime
changes.
- We used
canplay
event to update information when file is ready to be played.
- We created buttons to play, pause, restart.
_x000D_
_x000D_
$(document).ready(function() {_x000D_
var audioElement = document.createElement('audio');_x000D_
audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
_x000D_
audioElement.addEventListener('ended', function() {_x000D_
this.play();_x000D_
}, false);_x000D_
_x000D_
audioElement.addEventListener("canplay",function(){_x000D_
$("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
$("#source").text("Source:" + audioElement.src);_x000D_
$("#status").text("Status: Ready to play").css("color","green");_x000D_
});_x000D_
_x000D_
audioElement.addEventListener("timeupdate",function(){_x000D_
$("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
});_x000D_
_x000D_
$('#play').click(function() {_x000D_
audioElement.play();_x000D_
$("#status").text("Status: Playing");_x000D_
});_x000D_
_x000D_
$('#pause').click(function() {_x000D_
audioElement.pause();_x000D_
$("#status").text("Status: Paused");_x000D_
});_x000D_
_x000D_
$('#restart').click(function() {_x000D_
audioElement.currentTime = 0;_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
<h2>Sound Information</h2>_x000D_
<div id="length">Duration:</div>_x000D_
<div id="source">Source:</div>_x000D_
<div id="status" style="color:red;">Status: Loading</div>_x000D_
<hr>_x000D_
<h2>Control Buttons</h2>_x000D_
<button id="play">Play</button>_x000D_
<button id="pause">Pause</button>_x000D_
<button id="restart">Restart</button>_x000D_
<hr>_x000D_
<h2>Playing Information</h2>_x000D_
<div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_
latex large division sign in a math formula
A possible soluttion that requires tweaking, but is very flexible is to use one of \big
, \Big
, \bigg
,\Bigg
in front of your division sign - these will make it progressively larger. For your formula, I think
$\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$
looks nicer than \middle\
which is automatically sized and IMHO is a bit too large.
VARCHAR to DECIMAL
You still haven't explained why you can't use a Float data type, so here is an example:
DECLARE @StringVal varchar(50)
SET @StringVal = '123456789.1234567'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
SET @StringVal = '1.12345678'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
SET @StringVal = '123456.1234'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
How to set a ripple effect on textview or imageview on Android?
<TextView
android:id="@+id/txt_banner"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_below="@+id/title"
android:background="@drawable/ripple_effect"
android:gravity="center|left"
android:paddingLeft="15dp"
android:text="@string/banner"
android:textSize="15sp" />
Add this into drawable
<?xml version="1.0" encoding="utf-8"?>
<!--this ripple animation only working for >= android version 21 -->
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/click_efect" />
ASP.NET MVC View Engine Comparison
My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.
To provide a simple sample:
@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>
And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.
As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.
Thanks
Nathj07
How to convert entire dataframe to numeric while preserving decimals?
Using dplyr
(a bit like sapply..)
df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))
which gives:
glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7
from your df1 which was:
glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7
Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in
MySQL socket is located, in general, in /tmp/mysql.sock
or /var/mysql/mysql.sock
, but probably PHP looks in the wrong place.
Check where is your socket with:
sudo /usr/libexec/locate.updatedb
When the updatedb is terminated:
locate mysql.sock
Then locate your php.ini:
php -i | grep php.ini
this will output something like:
Configuration File (php.ini) Path => /opt/local/etc/php54
Loaded Configuration File => /opt/local/etc/php54/php.ini
Edit your php.ini
sudo vim /opt/local/etc/php54/php.ini
Change the lines:
pdo_mysql.default_socket=/tmp/mysql.sock
mysql.default_socket=/tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock
where /tmp/mysql.sock is the path to your socket.
Save your modifications and exit ESC + SHIFT: x
Restart Apache
sudo apachectl stop
sudo apachectl start
How do you create a Distinct query in HQL
Here's a snippet of hql that we use. (Names have been changed to protect identities)
String queryString = "select distinct f from Foo f inner join foo.bars as b" +
" where f.creationDate >= ? and f.creationDate < ? and b.bar = ?";
return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});
finding first day of the month in python
First day of next month:
from datetime import datetime
class SomeClassName(models.Model):
if datetime.now().month == 12:
new_start_month = 1
else:
new_start_month = datetime.now().month + 1
Then we replace the month and the day
start_date = models.DateField(default=datetime.today().replace(month=new_start_month, day=1, hour=0, minute=0, second=0, microsecond=0))
Counting number of words in a file
The below code supports in Java 8
//Read file into String
String fileContent=new String(Files.readAlBytes(Paths.get("MyFile.txt")),StandardCharacters.UFT_8);
//Keeping these into list of strings by splitting with a delimiter
List<String> words = Arrays.asList(contents.split("\\PL+"));
int count=0;
for(String x: words){
if(x.length()>1) count++;
}
sop(x);
When should I use UNSIGNED and SIGNED INT in MySQL?
UNSIGNED
only stores positive numbers (or zero). On the other hand, signed can store negative numbers (i.e., may have a negative sign).
Here's a table of the ranges of values each INTEGER
type can store:
Source: http://dev.mysql.com/doc/refman/5.6/en/integer-types.html
UNSIGNED
ranges from 0
to n
, while signed ranges from about -n/2
to n/2
.
In this case, you have an AUTO_INCREMENT
ID column, so you would not have negatives. Thus, use UNSIGNED
. If you do not use UNSIGNED
for the AUTO_INCREMENT
column, your maximum possible value will be half as high (and the negative half of the value range would go unused).
htaccess redirect all pages to single page
This will direct everything from the old host to the root of the new host:
RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]
Child inside parent with min-height: 100% not inheriting height
For googlers:
This jquery-workaround makes #containment get a height automatically (by, height: auto), then gets the actual height assigned as a pixel value.
<script type="text/javascript">
<!--
$(function () {
// workaround for webkit-bug http://stackoverflow.com/a/8468131/348841
var rz = function () {
$('#containment')
.css('height', 'auto')
.css('height', $('#containment').height() + 'px');
};
$(window).resize(function () {
rz();
});
rz();
})
-->
</script>
How do I test if a variable is a number in Bash?
printf '%b' "-123\nABC" | tr '[:space:]' '_' | grep -q '^-\?[[:digit:]]\+$' && echo "Integer." || echo "NOT integer."
Remove the -\?
in grep matching pattern if you don't accept negative integer.
Chrome desktop notification example
I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.
Probably on Opera, IE and Edge as well but I haven't tested it yet.
Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.
Get it on Bower
$ bower install js-notify
This is how it works:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
You have to set the title but the json object as the second argument is optional.
How to delete the first row of a dataframe in R?
While I agree with the most voted answer, here is another way to keep all rows except the first:
dat <- tail(dat, -1)
This can also be accomplished using Hadley Wickham's dplyr
package.
dat <- dat %>% slice(-1)
Python dictionary get multiple values
No-one has mentioned the map
function, which allows a function to operate element-wise on a list:
mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']
values = list( map(mydictionary.get, keys) )
# values = ['bear', 'castle']
What Scala web-frameworks are available?
I have stumbled upon your question a few weeks back, but since then also learned about Circumflex. This is a nice, minimal framework that is therefore easy to learn, and it has pretty good documentation available as well.
Beside it's minimal-ness, it also claims to work well with other libraries and lets you use your own implementation of things when you need it.
Moment.js - How to convert date string into date?
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
Handling Enter Key in Vue.js
Event Modifiers
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call event.preventDefault()
or event.stopPropagation()
inside event handlers.
Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
_x000D_
_x000D_
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
validateEmailAddress: function(e) {_x000D_
if (e.keyCode === 13) {_x000D_
alert('Enter was pressed');_x000D_
} else if (e.keyCode === 50) {_x000D_
alert('@ was pressed');_x000D_
} _x000D_
this.log += e.key;_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
},_x000D_
noop () {_x000D_
// do nothing ?_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea> _x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_
What is the difference between an abstract function and a virtual function?
Virtual Method:
Abstract Method
Abstract means we MUST override it.
An abstract function has no implementation and must be in an abstract class.
It can only be declared. This forces the derived class to provide the implementation of it.
An abstract member is implicitly virtual. The abstract can be called as pure virtual in some of the languages.
public abstract class BaseClass
{
protected abstract void xAbstractMethod();
public virtual void xVirtualMethod()
{
var x = 3 + 4;
}
}
How do I count occurrence of duplicate items in array
I came here from google looking for a way to count the occurence of duplicate items in an array. Here is the way to do it simply:
$colors = array("red", "green", "blue", "red", "yellow", "blue");
$unique_colors = array_unique($colors);
// $unique colors : array("red", "green", "blue", "yellow")
$duplicates = count($colors) - count($unique_colors);
// $duplicates = 6 - 4 = 2
if( $duplicates == 0 ){
echo "There are no duplicates";
}
echo "No. of Duplicates are :" . $duplicates;
// Output: No. of Duplicates are: 2
How array_unique() works?
It elements all the duplicates.
ex:
Lets say we have an array as follows -
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");
When you do $cars = array_unique($cars);
cars will have only following elements.
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");
To read more: https://www.w3schools.com/php/func_array_unique.asp
Hope it is helpful to those who are coming here from google looking for a way to count duplicate values in array.
Converting Dictionary to List?
If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()
Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:
headers = ['Capital', 'Food', 'Year']
countries = [
['London', 'Fish & Chips', '2012'],
['Beijing', 'Noodles', '2008'],
]
for olympics in countries:
print zip(headers, olympics)
gives
[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]
Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.
How to use Chrome's network debugger with redirects
This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.
Current (= v32)
At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.
The little red dot on the left now has the purpose to switch network logging on and off completely.
Older versions
In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.
If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.
Setting TIME_WAIT TCP
TIME_WAIT might not be the culprit.
int listen(int sockfd, int backlog);
According to Unix Network Programming Volume1, backlog is defined to be the sum of completed connection queue and incomplete connection queue.
Let's say the backlog is 5. If you have 3 completed connections (ESTABLISHED state), and 2 incomplete connections (SYN_RCVD state), and there is another connect request with SYN. The TCP stack just ignores the SYN packet, knowing it'll be retransmitted some other time. This might be causing the degradation.
At least that's what I've been reading. ;)
How to find a value in an array of objects in JavaScript?
If you have an array such as
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
You can use the filter
method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations you can use a function expression:
people.filter(p => p.dinner == "sushi")
// => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!
SQL Update to the SUM of its joined values
This is a valid error. See this. Following (and others suggested below) are the ways to achieve this:-
UPDATE P
SET extrasPrice = t.TotalPrice
FROM BookingPitches AS P INNER JOIN
(
SELECT
PitchID,
SUM(Price) TotalPrice
FROM
BookingPitchExtras
GROUP BY PitchID
) t
ON t.PitchID = p.ID
Flutter: Setting the height of the AppBar
Cinn's answer is great, but there's one thing wrong with it.
The PreferredSize
widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.
The solution: Wrap the preferredSize
's child with a SafeArea
appBar: PreferredSize(
//Here is the preferred height.
preferredSize: Size.fromHeight(50.0),
child: SafeArea(
child: AppBar(
flexibleSpace: ...
),
),
),
If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar
will account for the status bar automatically.
Callback functions in C++
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
How to pass a type as a method parameter in Java
If you want to pass the type, than the equivalent in Java would be
java.lang.Class
If you want to use a weakly typed method, then you would simply use
java.lang.Object
and the corresponding operator
instanceof
e.g.
private void foo(Object o) {
if(o instanceof String) {
}
}//foo
However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.
The real question is what you actually want to achieve here, otherwise it is difficult to answer:
Or is there a better way?
Transfer data between iOS and Android via Bluetooth?
This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.
Some possible alternatives:
- Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
- Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
- Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
- Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)
Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.
Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.
How can I represent a range in Java?
You could create a class to represent this
public class Range
{
private int low;
private int high;
public Range(int low, int high){
this.low = low;
this.high = high;
}
public boolean contains(int number){
return (number >= low && number <= high);
}
}
Sample usage:
Range range = new Range(0, 2147483647);
if (range.contains(foo)) {
//do something
}
Convert a list to a dictionary in Python
b = dict(zip(a[::2], a[1::2]))
If a
is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()
and len()
, which would normally be a code smell.
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()
method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()
is already lazy in Python 3 so you don't need izip()
.
i = iter(a)
b = dict(zip(i, i))
If you want it on one line, you'll have to cheat and use a semicolon. ;-)
Git merge reports "Already up-to-date" though there is a difference
This happened to me because strangely GIT thought that the local branch was different from the remote branch.
This was visible in the branch graph: it displayed two different branches: remotes/origin/branch_name and branch_name.
The solution was simply to remove the local repo and re-clone it from remote. This way GIT would understand that remotes/origin/branch_name>and branch_name are indeed the same, and I could issue the git merge branch_name
.
rm <my_repo>
git clone <my_repo>
cd <my_repo>
git checkout <branch_name>
git pull
git checkout master
git merge <branch_name>
angular js unknown provider
My scenario may be a little obscure but it can cause the same error and someone may experience it, so:
When using the $controller service to instantiate a new controller (which was expecting '$scope' as it's first injected argument) I was passing the new controller's local scope into the $controller() function's second parameter. This lead to Angular trying to invoke a $scope service which doesn't exist (though, for a while, I actually thought that I'd some how deleted the '$scope' service from Angular's cache). The solution is to wrap the local scope in a locals object:
// Bad:
$controller('myController', newScope);
// Good:
$controller('myController, {$scope: newScope});
Programmatically navigate using react router V4
My answer is similar to Alex's. I'm not sure why React-Router made this so needlessly complicated. Why should I have to wrap my component with a HoC just to get access to what's essentially a global?
Anyway, if you take a look at how they implemented <BrowserRouter>
, it's just a tiny wrapper around history.
We can pull that history bit out so that we can import it from anywhere. The trick, however, is if you're doing server-side rendering and you try to import
the history module, it won't work because it uses browser-only APIs. But that's OK because we usually only redirect in response to a click or some other client-side event. Thus it's probably OK to fake it:
// history.js
if(__SERVER__) {
module.exports = {};
} else {
module.exports = require('history').createBrowserHistory();
}
With the help of webpack, we can define some vars so we know what environment we're in:
plugins: [
new DefinePlugin({
'__SERVER__': 'false',
'__BROWSER__': 'true', // you really only need one of these, but I like to have both
}),
And now you can
import history from './history';
From anywhere. It'll just return an empty module on the server.
If you don't want use these magic vars, you'll just have to require
in the global object where it's needed (inside your event handler). import
won't work because it only works at the top-level.
Installing PDO driver on MySQL Linux server
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
Fire event on enter key press for a textbox
ahaliav fox 's answer is correct, however there's a small coding problem.
Change
<%=Button1.UniqueId%>
to
<%=Button1.UniqueID%>
it is case sensitive. Control.UniqueID Property
Error 14 'System.Web.UI.WebControls.Button' does not contain a definition for 'UniqueId' and no extension method 'UniqueId' accepting a first argument of type 'System.Web.UI.WebControls.Button' could be found (are you missing a using directive or an assembly reference?)
N.b. I tried the TextChanged
event myself on AutoPostBack
before searching for the answer, and although it is almost right it doesn't give the desired result I wanted nor for the question asked. It fires on losing focus on the Textbox
and not when pressing the return key.
A KeyValuePair in Java
You can create your custom KeyValuePair class easily
public class Key<K, V>{
K key;
V value;
public Key() {
}
public Key(K key, V value) {
this.key = key;
this.value = value;
}
public void setValue(V value) {
this.value = value;
}
public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}
public K getKey() {
return key;
}
}
Very Long If Statement in Python
Here is the example directly from PEP 8 on limiting line length:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
Unnamed/anonymous namespaces vs. static functions
I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.
For example, in my XmlUtil.cpp file, I define a namespace XmlUtil_I { ... }
for all of my module variables and functions. That way I can apply the XmlUtil_I::
qualification in the debugger to access the variables. In this case, the _I
distinguishes it from a public namespace such as XmlUtil
that I may want to use elsewhere.
I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.
After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName
I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.
The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url
property, instead it want´s to have spring.datasource.jdbc-url
(lapkritinis also pointed that out).
So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url
to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:
You should at least specify the URL by setting the
spring.datasource.url property. Otherwise, Spring Boot tries to
auto-configure an embedded database.
You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc
as a dependency to your pom.xml:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
And then configure Spring Boot to use it accordingly inside application.properties:
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)
What is the proper way to test if a parameter is empty in a batch file?
From IF /?:
If Command Extensions are enabled IF
changes as follows:
IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command
......
The DEFINED conditional works just
like EXISTS except it takes an
environment variable name and returns
true if the environment variable is
defined.
How do I use tools:overrideLibrary in a build.gradle file?
<manifest xmlns:tools="http://schemas.android.com/tools" ... >
<uses-sdk tools:overrideLibrary="nl.innovalor.ocr, nl.innovalor.corelib" />
I was facing the issue of conflict between different min sdk versions.
So this solution worked for me.
android.widget.Switch - on/off event listener?
The layout for Switch widget is something like this.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:gravity="right"
android:text="All"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20dp"
android:id="@+id/list_toggle" />
</LinearLayout>
In the Activity class, you can code by two ways. Depends on the use you can code.
First Way
public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(this);
}
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
Second way
public class ActivityClass extends Activity {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
}
}
How do you perform address validation?
There are a number of good answers in here but most of them make the assumption that the user wants an "API" solution where they must write code to connect to a 3rd-party service and/or screen scrape the USPS. This is all well and good, but should be factored into the business requirements and costs associated with the implementation and then weighed against the desired benefits.
Depending upon the business requirements and the way that the data is received into the system, a real-time address processing solution may be the best bet. If a real-time solution is required, you will want to consider the license agreement and technical limitations of the Google Maps/Bing/Yahoo APIs. They typically limit the number of calls you can make each day. The USPS web tools API is the same in additional they restrict how/why you can use their system and how you are allowed to use the data thereafter.
At the same time, there are a handful of great service providers that can easily process a static list of addresses. Essentially, you give the service provider a CSV file or Excel file, they clean it up and get it back to you. It's a one-time deal with no long-term commitment or obligation—usually.
Full disclosure: I'm the founder of SmartyStreets. We do address verification for addresses within the United States. We are easily able to CASS certify a list and we also offer a address verification web service API. We have no hidden fees, contracts, or anything. You use our service until you no longer need it and you can walk away. (Unlike cell phone companies that require a contract.)
Installing Numpy on 64bit Windows 7 with Python 2.7.3
It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included "Python Environment" Window. "Overview" is selected within the window as default. You can select "Pip" there.
Then you can install numpy without additional work by entering numpy into the seach window. The coresponding "install numpy" instruction is already suggested.
Nevertheless I had 2 easy to solve Problems in the beginning:
- "error: Unable to find vcvarsall.bat": This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
- Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.
Finally the installation was done. It took some time (5 minutes), so don't cancel the process to early.
What are "res" and "req" parameters in Express functions?
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggered
request.method
, which will be "GET"
in this case, hence the app.get()
call.
- An array of HTTP headers in
request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
- An array of query string parameters if there were any, in
request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).
To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
How to get input text length and validate user in javascript
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
Are there pointers in php?
That syntax is a way of accessing a class member. PHP does not have pointers, but it does have references.
The syntax that you're quoting is basically the same as accessing a member from a pointer to a class in C++ (whereas dot notation is used when it isn't a pointer.)