XAMPP MySQL password setting (Can not enter in PHPMYADMIN)
1.open your xampp dir ( c:/xampp )
2.to phpMyadmin dir [C:\xampp\phpMyAdmin]
3.open [ config.inc.php ] file with any text editor
$cfg['Servers'][$i]['auth_type'] = 'config'; //replace 'config' to ‘cookie’
$cfg['Servers'][$i]['AllowNoPassword'] = true; //change ‘true’ to ‘false’.
last : save the file .
here is a video link in case you want to see it in Action [ click Here ]
Remove ':hover' CSS behavior from element
Use the :not
pseudo-class to exclude the classes you don't want the hover to apply to:
FIDDLE
<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test nohover"> blah </div>
.test:not(.nohover):hover {
border: 1px solid red;
}
This does what you want in one css rule!
Which .NET Dependency Injection frameworks are worth looking into?
edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc:
- Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight
- Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection
- Autofac - An addictive .NET IoC container
- DryIoc - Simple, fast all fully featured IoC container.
- Ninject - The ninja of .NET dependency injectors
- StructureMap - The original IoC/DI Container for .Net
- Spring.Net - Spring.NET is an open source application framework that makes building enterprise .NET applications easier
- LightInject - A ultra lightweight IoC container
- Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.
- Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications.
- Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.
- VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio.
- TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.
Original answer follows.
I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.
That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.
Update
I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.
Other IoC screencasts can also be found here on Dimecasts.
How to fix "could not find a base address that matches schema http"... in WCF
I had to do two things to the IIS configuration of the site/application. My issue had to do with getting net.tcp working in an IIS Web Site App:
First:
- Right click on the IIS App name.
- Manage Web Site
- Advanced Settings
- Set Enabled protocols to be "http,net.tcp"
Second:
- Under the Actions menu on the right side of the Manager, click Bindings...
- Click Add
- Change type to "net.tcp"
- Set binding information to {open port number}:*
- OK
Python debugging tips
Logging
Python already has an excellent built-in logging module. You may want to use the logging template here.
The logging module lets you specify a level of importance; during debugging you can log everything, while during normal operation you might only log critical things. You can switch things off and on.
Most people just use basic print statements to debug, and then remove the print statements. It's better to leave them in, but disable them; then, when you have another bug, you can just re-enable everything and look your logs over.
This can be the best possible way to debug programs that need to do things quickly, such as networking programs that need to respond before the other end of the network connection times out and goes away. You might not have much time to single-step a debugger; but you can just let your code run, and log everything, then pore over the logs and figure out what's really happening.
EDIT: The original URL for the templates was: http://aymanh.com/python-debugging-techniques
This page is missing so I replaced it with a reference to the snapshot saved at archive.org: http://web.archive.org/web/20120819135307/http://aymanh.com/python-debugging-techniques
In case it disappears again, here are the templates I mentioned. This is code taken from the blog; I didn't write it.
import logging
import optparse
LOGGING_LEVELS = {'critical': logging.CRITICAL,
'error': logging.ERROR,
'warning': logging.WARNING,
'info': logging.INFO,
'debug': logging.DEBUG}
def main():
parser = optparse.OptionParser()
parser.add_option('-l', '--logging-level', help='Logging level')
parser.add_option('-f', '--logging-file', help='Logging file name')
(options, args) = parser.parse_args()
logging_level = LOGGING_LEVELS.get(options.logging_level, logging.NOTSET)
logging.basicConfig(level=logging_level, filename=options.logging_file,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# Your program goes here.
# You can access command-line arguments using the args variable.
if __name__ == '__main__':
main()
And here is his explanation of how to use the above. Again, I don't get the credit for this:
By default, the logging module prints critical, error and warning messages. To change this so that all levels are printed, use:
$ ./your-program.py --logging=debug
To send log messages to a file called debug.log, use:
$ ./your-program.py --logging-level=debug --logging-file=debug.log
jQuery or JavaScript auto click
First i tried with this sample code:
$(document).ready(function(){
$('#upload-file').click();
});
It didn't work for me. Then after, tried with this
$(document).ready(function(){
$('#upload-file')[0].click();
});
No change. At last, tried with this
$(document).ready(function(){
$('#upload-file')[0].click(function(){
});
});
Solved my problem. Helpful for anyone.
Reset CSS display property to default value
If you have access to JavaScript, you can create an element and read its computed style.
function defaultValueOfCssPropertyForElement(cssPropertyName, elementTagName, opt_pseudoElement) {
var pseudoElement = opt_pseudoElement || null;
var element = document.createElement(elementTagName);
document.body.appendChild(element);
var computedStyle = getComputedStyle(element, pseudoElement)[cssPropertyName];
element.remove();
return computedStyle;
}
// Usage:
defaultValueOfCssPropertyForElement('display', 'div'); // Output: 'block'
defaultValueOfCssPropertyForElement('content', 'div', ':after'); // Output: 'none'
What is bootstrapping?
As a humble beginner in the world of programming, and flicking through all the answers here after seeing this word used a lot in apparently slightly different ways in different places, I found reading the Wikipedia page on Bootstrapping (duh! I didn't think of it either at first) is very informative to understand differences in use of this word. Could it be......on extremely rare occasions......Wikipedia might even have better explanations of certain terms than....(redacted)? Will they bring in rep points on Wikipedia though?
To me, it seems all the meanings something to do with: start with something as simple as possible Thing1, make something slightly more complex with that Thing2, and now you can use Thing2 to do some kind of tasks more efficiently and quickly than you could originally with Thing1. Then repeat from Thing2 to Thing 3 ad infinitum...
I see it as closely connected to both biological evolution and 'Layers of Abstraction' (newbies like me see, ahem, Wikipedia, cough) - the evolution from 1940's computers with switches, machine code, Assembly, C, Python, AIs you can give all kinds of complex instructions to like "make the %4^% dinner to my default &^$% requirements and clean the floor you %$£"@:~" in drunken slang English or Amazon tribal dialect without them 'raising an exception' (for newbies again...you guessed it) - missed out lot of links there due to simple ignorance.
Then in certain specific software meanings:
Meaning1: Thing1 is used to load latest version of Thing2 (because of course Thing2 will be bigger than Thing1, just as Thing3 will be be bigger than Thing2).
Meaning2: Thing1 is a lower level language (closer to 1001011100....011001 than print("Hello, ", user.name)) used to write a little bit of the higher language of Thing2, then this little bit of Thing2 is used to expand Thing2 itself from baby vocabulary level towards adult vocabulary level (Thing2 starts to be processed, or to use correct technical term 'compiled', by the baby version of itself (it's a clever baby!), whereas the baby version of Thing2 itself could of course only be compiled by Thing1, cause it can't exist before it exists, right duh!), then child version of Thing2 compiles Surly Teenager version of Thing2, at which point programming community decides whether Surly Teenager's 'issues' (software term and metaphor term!) are worth spending enough time resolving to be accepted long term, or to abandon them to (not sure where to take the analogy here).
If yes, then Thing2 has 'Bootstrapped' itself (possibly a few times) from babyhood to adulthood: "the child is the father of the man" (Wordsworth, suggest don't try looking up the quote or the author on Stack Overflow).
Adding 30 minutes to time formatted as H:i in PHP
Your current solution does not work because $time
is a string - it needs to be a Unix timestamp. You can do this instead:
$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );
Show all current locks from get_lock
I found following way which can be used if you KNOW name of lock
select IS_USED_LOCK('lockname');
however i not found any info about how to list all names.
How to run a function when the page is loaded?
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
I'd recommend this if you use native Javascript.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
How to prevent buttons from submitting forms
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Error: "an object reference is required for the non-static field, method or property..."
The error message means that you need to invoke volteado
and siprimo
on an instance of the Program
class. E.g.:
...
Program p = new Program();
long av = p.volteado(a); // av is "a" but swapped
if (p.siprimo(a) == false && p.siprimo(av) == false)
...
They cannot be invoked directly from the Main
method because Main
is static while volteado
and siprimo
are not.
The easiest way to fix this is to make the volteado
and siprimo
methods static:
private static bool siprimo(long a)
{
...
}
private static bool volteado(long a)
{
...
}
Sort Go map values by keys
In reply to James Craig Burley's answer. In order to make a clean and re-usable design, one might choose for a more object oriented approach. This way methods can be safely bound to the types of the specified map. To me this approach feels cleaner and organized.
Example:
package main
import (
"fmt"
"sort"
)
type myIntMap map[int]string
func (m myIntMap) sort() (index []int) {
for k, _ := range m {
index = append(index, k)
}
sort.Ints(index)
return
}
func main() {
m := myIntMap{
1: "one",
11: "eleven",
3: "three",
}
for _, k := range m.sort() {
fmt.Println(m[k])
}
}
Extended playground example with multiple map types.
Important note
In all cases, the map and the sorted slice are decoupled from the moment the for
loop over the map range
is finished. Meaning that, if the map gets modified after the sorting logic, but before you use it, you can get into trouble. (Not thread / Go routine safe). If there is a change of parallel Map write access, you'll need to use a mutex around the writes and the sorted for
loop.
mutex.Lock()
for _, k := range m.sort() {
fmt.Println(m[k])
}
mutex.Unlock()
How to set an environment variable from a Gradle build?
In my project I have Gradle task for integration test in sub-module:
task intTest(type: Test) {
...
system.properties System.properties
...
this is the main point to inject all your system params into test environment.
So, now you can run gradle like this to pass param with ABC value and use its value by ${param} in your code
gradle :some-service:intTest -Dparam=ABC
Python error: "IndexError: string index out of range"
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
time.sleep -- sleeps thread or process?
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep()
, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
What is the difference between private and protected members of C++ classes?
Protected members can be accessed from derived classes. Private ones can't.
class Base {
private:
int MyPrivateInt;
protected:
int MyProtectedInt;
public:
int MyPublicInt;
};
class Derived : Base
{
public:
int foo1() { return MyPrivateInt;} // Won't compile!
int foo2() { return MyProtectedInt;} // OK
int foo3() { return MyPublicInt;} // OK
};??
class Unrelated
{
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.
AJAX post error : Refused to set unsafe header "Connection"
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
logout and redirecting session in php
Only this is necessary
session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");
HTML Upload MAX_FILE_SIZE does not appear to work
To anyone who had been wonderstruck about some files being easily uploaded and some not, it could be a size issue. I'm sharing this as I was stuck with my PHP code not uploading large files and I kept assuming it wasn't uploading any Excel files. So, if you are using PHP and you want to increase the file upload limit, go to the php.ini file and make the following modifications:
to be changed to
or the size required. Then restart the Apache server and the upload will start magically working. Hope this will be of help to someone.
CSS Input field text color of inputted text
Change your second style to this:
input, select, textarea{
color: #ff0000;
}
At the moment, you are telling the form to change the text to black
once the focus is off. The above remedies that.
Also, it is a good idea to place the normal state styles ahead of the :focus
and :hover
styles in your stylesheet. That helps prevent this problem. So
input, select, textarea{
color: #ff0000;
}
textarea:focus, input:focus {
color: #ff0000;
}
How to combine paths in Java?
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path
; Path.resolve
can be used to combine one path with another, or with a string. The Paths
helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File
, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
If you want it back as a string later, you can call getPath()
. Indeed, if you really wanted to mimic Path.Combine
, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
How to pass a type as a method parameter in Java
You could pass a Class<T>
in.
private void foo(Class<?> cls) {
if (cls == String.class) { ... }
else if (cls == int.class) { ... }
}
private void bar() {
foo(String.class);
}
Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo()
and two concrete implementations implementing foo()
and then just call foo()
on the implementation you've at hand. Another way may be a Map<Class<?>, Action>
which you could call by actions.get(cls)
. This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo()
.
Difference between 2 dates in seconds
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
What is the difference between List and ArrayList?
There's no difference between list implementations in both of your examples.
There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface.
If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
How do I remove all null and empty string values from an object?
You're deleting sjonObj.key
, literally. You need to use array access notation:
delete sjonObj[key];
However, that will also delete where value is equal to 0, since you're not using strict comparison. Use ===
instead:
$.each(sjonObj, function(key, value){
if (value === "" || value === null){
delete sjonObj[key];
}
});
However, this will only walk the object shallowly. To do it deeply, you can use recursion:
(function filter(obj) {
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if (Object.prototype.toString.call(value) === '[object Object]') {
filter(value);
} else if ($.isArray(value)) {
$.each(value, function (k,v) { filter(v); });
}
});
})(sjonObj);
_x000D_
_x000D_
var sjonObj = {_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"coreTEEVersion": "3.3.1.4_RC8",_x000D_
"testSuiteId": "yyy",_x000D_
"testSuiteFormatVersion": "1.0.0.0",_x000D_
"testStatus": "IDLE",_x000D_
"reportPath": "",_x000D_
"startTime": 0,_x000D_
"durationBetweenTestCases": 20,_x000D_
"endTime": 0,_x000D_
"lastExecutedTestCaseId": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"fixedTimeSyncSupported": false,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"summaryReportRequired": "true",_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "a",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
},_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
{_x000D_
"commandParameters": {_x000D_
"serverAddress": "www.ggp.com",_x000D_
"echoRequestCount": "",_x000D_
"sendPacketSize": "",_x000D_
"interval": "",_x000D_
"ttl": "",_x000D_
"addFullDataInReport": "True",_x000D_
"maxRTT": "",_x000D_
"failOnTargetHostUnreachable": "True",_x000D_
"failOnTargetHostUnreachableCount": "",_x000D_
"initialDelay": "",_x000D_
"commandTimeout": "",_x000D_
"testDuration": ""_x000D_
},_x000D_
"commandName": "Ping",_x000D_
"testStatus": "IDLE",_x000D_
"label": "",_x000D_
"reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
"endTime": 0,_x000D_
"startTime": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"detailReportRequired": "true",_x000D_
"summaryReportRequired": "true"_x000D_
}_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "dd",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "b",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
(function filter(obj) {_x000D_
$.each(obj, function(key, value){_x000D_
if (value === "" || value === null){_x000D_
delete obj[key];_x000D_
} else if (Object.prototype.toString.call(value) === '[object Object]') {_x000D_
filter(value);_x000D_
} else if (Array.isArray(value)) {_x000D_
value.forEach(function (el) { filter(el); });_x000D_
}_x000D_
});_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj)
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_
Note that if you're willing to use a library like lodash/underscore.js, you can use _.pick
instead. However, you will still need to use recursion to filter deeply, since neither library provides a deep filter function.
sjonObj = (function filter(obj) {
var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);
This variant has the added advantage of leaving the original object unmodified, but it does create an entirely new copy, which would be less efficient if you don't need the original object.
_x000D_
_x000D_
var sjonObj = {_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"coreTEEVersion": "3.3.1.4_RC8",_x000D_
"testSuiteId": "yyy",_x000D_
"testSuiteFormatVersion": "1.0.0.0",_x000D_
"testStatus": "IDLE",_x000D_
"reportPath": "",_x000D_
"startTime": 0,_x000D_
"durationBetweenTestCases": 20,_x000D_
"endTime": 0,_x000D_
"lastExecutedTestCaseId": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"fixedTimeSyncSupported": false,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"summaryReportRequired": "true",_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "a",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
},_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
{_x000D_
"commandParameters": {_x000D_
"serverAddress": "www.ggp.com",_x000D_
"echoRequestCount": "",_x000D_
"sendPacketSize": "",_x000D_
"interval": "",_x000D_
"ttl": "",_x000D_
"addFullDataInReport": "True",_x000D_
"maxRTT": "",_x000D_
"failOnTargetHostUnreachable": "True",_x000D_
"failOnTargetHostUnreachableCount": "",_x000D_
"initialDelay": "",_x000D_
"commandTimeout": "",_x000D_
"testDuration": ""_x000D_
},_x000D_
"commandName": "Ping",_x000D_
"testStatus": "IDLE",_x000D_
"label": "",_x000D_
"reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
"endTime": 0,_x000D_
"startTime": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"detailReportRequired": "true",_x000D_
"summaryReportRequired": "true"_x000D_
}_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "dd",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "b",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
sjonObj = (function filter(obj) {_x000D_
var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });_x000D_
return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
_x000D_
_x000D_
_x000D_
How can I run an EXE program from a Windows Service using C#?
First, we are going to create a Windows Service that runs under the
System account. This service will be responsible for spawning an
interactive process within the currently active User’s Session. This
newly created process will display a UI and run with full admin
rights. When the first User logs on to the computer, this service will
be started and will be running in Session0; however the process that
this service spawns will be running on the desktop of the currently
logged on User. We will refer to this service as the LoaderService.
Next, the winlogon.exe process is responsible for managing User login
and logout procedures. We know that every User who logs on to the
computer will have a unique Session ID and a corresponding
winlogon.exe process associated with their Session. Now, we mentioned
above, the LoaderService runs under the System account. We also
confirmed that each winlogon.exe process on the computer runs under
the System account. Because the System account is the owner of both
the LoaderService and the winlogon.exe processes, our LoaderService
can copy the access token (and Session ID) of the winlogon.exe process
and then call the Win32 API function CreateProcessAsUser to launch a
process into the currently active Session of the logged on User. Since
the Session ID located within the access token of the copied
winlogon.exe process is greater than 0, we can launch an interactive
process using that token.
Try this one.
Subverting Vista UAC in Both 32 and 64 bit Architectures
How to add screenshot to READMEs in github repository?
The markdown syntax for displaying images is indeed:
![image](https://{url})
BUT: How to provide the url
?
- You probably do not want to clutter your repo with screenshots, they have nothing to do with code
- you might not want either to deal with the hassle of making your image available on the web... (upload it to a server... ).
So... you can use this awesome trick to make github host your image file. TDLR:
- create an issue on the issue list of your repo
- drag and drop your screenshot on this issue
- copy the markdown code that github has just created for you to display your image
- paste it on your readme (or wherever you want)
http://solutionoptimist.com/2013/12/28/awesome-github-tricks/
mysqli_fetch_array while loop columns
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
subsampling every nth entry in a numpy array
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
How can I iterate JSONObject to get individual items
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
Preferred method to store PHP arrays (json_encode vs serialize)
JSON is better if you want to backup Data and restore it on a different machine or via FTP.
For example with serialize if you store data on a Windows server, download it via FTP and restore it on a Linux one it could not work any more due to the charachter re-encoding, because serialize stores the length of the strings and in the Unicode > UTF-8 transcoding some 1 byte charachter could became 2 bytes long making the algorithm crash.
Where do I put image files, css, js, etc. in Codeigniter?
(I am new to Codeigniter, so I don't know if this is the best advice)
I keep publicly available files in my public folder.
It is logical for them to be there, and I don't want to use Codeigniter for something I don't need to use it for.
The directory tree looks likes this:
- /application/
- /public/
- /public/css/
- /public/img/
- /public/js/
- /system/
The only files I keep in /public/ are Codeigniter's index.php, and my .htaccess file:
RewriteEngine On
RewriteBase /
RewriteRule ^css/ - [L]
RewriteRule ^img/ - [L]
RewriteRule ^js/ - [L]
RewriteRule ^index.php(.*)$ - [L]
RewriteRule ^(.*)$ /index.php?/$1 [L]
How to make inactive content inside a div?
div[disabled]
{
pointer-events: none;
opacity: 0.6;
background: rgba(200, 54, 54, 0.5);
background-color: yellow;
filter: alpha(opacity=50);
zoom: 1;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
-moz-opacity: 0.5;
-khtml-opacity: 0.5;
}
How to call external JavaScript function in HTML
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page.
Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Result :
How to create empty folder in java?
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
How to set a cell to NaN in a pandas dataframe
df.loc[df.y == 'N/A',['y']] = np.nan
This solve your problem. With the double [], you are working on a copy of the DataFrame. You have to specify exact location in one call to be able to modify it.
Pip install - Python 2.7 - Windows 7
pip is installed by default when we install Python in windows.
After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD
After that, we can directly use the python command with pip option to install further packages as following:-
C:\ python -m pip install python_module_name
This will install the module using pip.
How to read .pem file to get private and public key
Well, my code is like yours, with little diferences...
public static X509Certificate loadPublicX509(String fileName)
throws GeneralSecurityException {
InputStream is = null;
X509Certificate crt = null;
try {
is = fileName.getClass().getResourceAsStream("/" + fileName);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
crt = (X509Certificate)cf.generateCertificate(is);
} finally {
closeSilent(is);
}
return crt;
}
public static PrivateKey loadPrivateKey(String fileName)
throws IOException, GeneralSecurityException {
PrivateKey key = null;
InputStream is = null;
try {
is = fileName.getClass().getResourceAsStream("/" + fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
boolean inKey = false;
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (!inKey) {
if (line.startsWith("-----BEGIN ") &&
line.endsWith(" PRIVATE KEY-----")) {
inKey = true;
}
continue;
}
else {
if (line.startsWith("-----END ") &&
line.endsWith(" PRIVATE KEY-----")) {
inKey = false;
break;
}
builder.append(line);
}
}
//
byte[] encoded = DatatypeConverter.parseBase64Binary(builder.toString());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
key = kf.generatePrivate(keySpec);
} finally {
closeSilent(is);
}
return key;
}
public static void closeSilent(final InputStream is) {
if (is == null) return;
try { is.close(); } catch (Exception ign) {}
}
Use a list of values to select rows from a pandas dataframe
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
Send Message in C#
It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...
Bootstrap: adding gaps between divs
Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap
. However, .col-md-offset-*
does the job most of the times for me, allowing me to precisely leave a gap between the divs.
As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }
. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.
How can I clear an HTML file input with JavaScript?
U need replace it with new file input.
Here is how it can be done with jQuery:
var inputFile = $('input[type=field]');
inputFile.wrap('<div />');
and use this line when you need to clear input field (on some event for example):
inputFile.parent().html( inputFile.parent().html() );
How to calculate a Mod b in Casio fx-991ES calculator
This calculator does not have any modulo function. However there is quite simple way how to compute modulo using display mode ab/c
(instead of traditional d/c
).
How to switch display mode to ab/c
:
- Go to settings (Shift + Mode).
- Press arrow down (to view more settings).
- Select
ab/c
(number 1).
Now do your calculation (in comp mode), like 50 / 3
and you will see 16 2/3
, thus, mod is 2
. Or try 54 / 7
which is 7 5/7
(mod is 5
).
If you don't see any fraction then the mod is 0
like 50 / 5 = 10
(mod is 0
).
The remainder fraction is shown in reduced form, so 60 / 8
will result in 7 1/2
. Remainder is 1/2
which is 4/8
so mod is 4
.
EDIT:
As @lawal correctly pointed out, this method is a little bit tricky for negative numbers because the sign of the result would be negative.
For example -121 / 26 = -4 17/26
, thus, mod is -17
which is +9
in mod 26. Alternatively you can add the modulo base to the computation for negative numbers: -121 / 26 + 26 = 21 9/26
(mod is 9
).
EDIT2: As @simpatico pointed out, this method will not work for numbers that are out of calculator's precision. If you want to compute say 200^5 mod 391
then some tricks from algebra are needed. For example, using rule
(A * B) mod C = ((A mod C) * B) mod C
we can write:
200^5 mod 391 = (200^3 * 200^2) mod 391 = ((200^3 mod 391) * 200^2) mod 391 = 98
console.writeline and System.out.println
They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:
public class ConsoleTest {
public static void main(String[] args) {
System.out.println("Console is: " + System.console());
}
}
results in:
$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null
The reason Console
exists is to provide features that are useful in the specific case that you're being run from an interactive command line:
- secure password entry (hard to do cross-platform)
- synchronisation (multiple threads can prompt for input and
Console
will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).
Notice above that redirecting even one of the streams results in System.console()
returning null
; another irritation is that there's often no Console
object available when spawned from another program such as Eclipse or Maven.
Convert seconds to Hour:Minute:Second
If you want to create a audio/video duration string like YouTube, etc. you can do:
($seconds >= 60) ? ltrim(gmdate("H:i:s", $seconds), ":0") : gmdate("0:s", $seconds)
Will return strings like:
55.55 => '0:55'
100 => '1:40'
Probably won't work well for time >= 24 hours.
How do I get the first element from an IEnumerable<T> in .net?
Use FirstOrDefault or a foreach loop as already mentioned. Manually fetching an enumerator and calling Current should be avoided. foreach will dispose your enumerator for you if it implements IDisposable. When calling MoveNext and Current you have to dispose it manually (if aplicable).
How to change button text or link text in JavaScript?
Change .text
to .textContent
to get/set the text content.
Or since you're dealing with a single text node, use .firstChild.data
in the same manner.
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById
.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
How can I run a function from a script in command line?
Well, while the other answers are right - you can certainly do something else: if you have access to the bash script, you can modify it, and simply place at the end the special parameter "$@"
- which will expand to the arguments of the command line you specify, and since it's "alone" the shell will try to call them verbatim; and here you could specify the function name as the first argument. Example:
$ cat test.sh
testA() {
echo "TEST A $1";
}
testB() {
echo "TEST B $2";
}
"$@"
$ bash test.sh
$ bash test.sh testA
TEST A
$ bash test.sh testA arg1 arg2
TEST A arg1
$ bash test.sh testB arg1 arg2
TEST B arg2
For polish, you can first verify that the command exists and is a function:
# Check if the function exists (bash specific)
if declare -f "$1" > /dev/null
then
# call arguments verbatim
"$@"
else
# Show a helpful error
echo "'$1' is not a known function name" >&2
exit 1
fi
Converting from a string to boolean in Python?
I just had to do this... so maybe late to the party - but someone may find it useful
def str_to_bool(input, default):
"""
| Default | not_default_str | input | result
| T | "false" | "true" | T
| T | "false" | "false" | F
| F | "true" | "true" | T
| F | "true" | "false" | F
"""
if default:
not_default_str = "false"
else:
not_default_str = "true"
if input.lower() == not_default_str:
return not default
else:
return default
Controlling number of decimal digits in print output in R
One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))
For example, if you have a vector as elements
and would like to get sum
of it
elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432
Apparently, the last digital as 1
been truncated, the ideal result should be -876.54321
, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements))
, redundant zero(s) generate as -876.5432100000
Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321
, there are 5 decimal digits need to print, then we can set up a parameter for format
function as below:
decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321
We can change the decimal_length
based on each time query, so it can satisfy different decimal printing requirement.
Checking whether a string starts with XXXX
Can also be done this way..
regex=re.compile('^hello')
## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')
if re.match(regex, somestring):
print("Yes")
In Angular, how do you determine the active route?
I was seeking a way to use a Twitter Bootstrap style nav with Angular2, but had trouble getting the active
class applied to the parent element of the selected link. Found that @alex-correia-santos's solution works perfectly!
The component containing your tabs has to import the router and define it in its constructor before you can make the necessary calls.
Here's a simplified version of my implementation...
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HomeComponent} from './home.component';
import {LoginComponent} from './login.component';
import {FeedComponent} from './feed.component';
@Component({
selector: 'my-app',
template: `
<ul class="nav nav-tabs">
<li [class.active]="_r.isRouteActive(_r.generate(['Home']))">
<a [routerLink]="['Home']">Home</a>
</li>
<li [class.active]="_r.isRouteActive(_r.generate(['Login']))">
<a [routerLink]="['Login']">Sign In</a>
</li>
<li [class.active]="_r.isRouteActive(_r.generate(['Feed']))">
<a [routerLink]="['Feed']">Feed</a>
</li>
</ul>`,
styleUrls: ['app/app.component.css'],
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path:'/', component:HomeComponent, name:'Home', useAsDefault:true },
{ path:'/login', component:LoginComponent, name:'Login' },
{ path:'/feed', component:FeedComponent, name:'Feed' }
])
export class AppComponent {
title = 'My App';
constructor( private _r:Router ){}
}
How do I split a string, breaking at a particular character?
According to ECMAScript6 ES6
, the clean way is destructuring arrays:
_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, unit, city, state, zip] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(unit); // Apt 4_x000D_
console.log(city); // New York_x000D_
console.log(state); // NY_x000D_
console.log(zip); // 12345
_x000D_
_x000D_
_x000D_
You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:
_x000D_
_x000D_
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
_x000D_
const [name, street, ...others] = input.split('~');_x000D_
_x000D_
console.log(name); // john smith_x000D_
console.log(street); // 123 Street_x000D_
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
_x000D_
_x000D_
_x000D_
I supposed a read-only reference for values and used the const
declaration.
Enjoy ES6!
How to disable PHP Error reporting in CodeIgniter?
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
Frame Buster Buster ... buster code needed
Came up with this, and it seems to work at least in Firefox and the Opera browser.
if(top != self) {
top.onbeforeunload = function() {};
top.location.replace(self.location.href);
}
How can I find matching values in two arrays?
Done as a answer so I can do formatting...
This is the the process you need to go through. Looping through an array for the specifics.
create an empty array
loop through array1, element by element. {
loop through array2, element by element {
if array1.element == array2.element {
add to your new array
}
}
}
Facebook share link without JavaScript
It is possible to include JavaScript in your code and still support non-JavaScript users.
If a user clicks any of the following links without JavaScript enabled, it will simply open a new tab:
<!-- Remember to change URL_HERE, TITLE_HERE and TWITTER_HANDLE_HERE -->
<a href="http://www.facebook.com/sharer/sharer.php?u=URL_HERE&t=TITLE_HERE" target="_blank" class="share-popup">Share on Facebook</a>
<a href="http://www.twitter.com/intent/tweet?url=URL_HERE&via=TWITTER_HANDLE_HERE&text=TITLE_HERE" target="_blank" class="share-popup">Share on Twitter</a>
<a href="http://plus.google.com/share?url=URL_HERE" target="_blank" class="share-popup">Share on Googleplus</a>
Because they contain the share-popup
class, we can easily reference these in jQuery, and change the window size to suit the domain we are sharing from:
$(".share-popup").click(function(){
var window_size = "width=585,height=511";
var url = this.href;
var domain = url.split("/")[2];
switch(domain) {
case "www.facebook.com":
window_size = "width=585,height=368";
break;
case "www.twitter.com":
window_size = "width=585,height=261";
break;
case "plus.google.com":
window_size = "width=517,height=511";
break;
}
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' + window_size);
return false;
});
No more ugly inline JavaScript, or countless window sizing alterations. And it still supports non-JavaScript users.
Why is Github asking for username/password when following the instructions on screen and pushing a new repo?
I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.
Edit your_repo_dir/.git/config
(remember: .git
folder is hidden)
Change:
https://github.com/WEMP/project-slideshow.git
to:
https://*username*@github.com/WEMP/project-slideshow.git
Save the file. Do a git pull
to test it.
The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.
keytool error Keystore was tampered with, or password was incorrect
From your description I assume you are on windows machine and your home is abc
So Now : Cause
When you run this command
keytool -genkey -alias tomcat -keyalg RSA
because you are not specifying an explicit keystore it will try to generate (and in your case as you are getting exception so to update) keystore C:\users\abc>.keystore
and of course you need to provide old password for .keystore while I believe you are providing your version (a new one).
Solution
Either delete .keystore
from C:\users\abc>
location and try the command
or try following command which will create a new xyzkeystore:
keytool -genkey -keystore xyzkeystore -alias tomcat -keyalg RSA
Note: -genkey
is old now rather use -genkeypair
althought both work equally.
HTML meta tag for content language
You asked for differences, but you can’t quite compare those two.
Note that <meta http-equiv="content-language" content="es">
is obsolete and removed in HTML5. It was used to specify “a document-wide default language”, with its http-equiv
attribute making it a pragma directive (which simulates an HTTP response header like Content-Language
that hasn’t been sent from the server, since it cannot override a real one).
Regarding <meta name="language" content="Spanish">
, you hardly find any reliable information. It’s non-standard and was probably invented as a SEO makeshift.
However, the HTML5 W3C Recommendation encourages authors to use the lang
attribute on html
root elements (attribute values must be valid BCP 47 language tags):
<!DOCTYPE html>
<html lang="es-ES">
<head>
…
Anyway, if you want to specify the content language to instruct search engine robots, you should consider this quote from Google Search Console Help on multilingual sites:
Google uses only the visible content of your page to determine its language. We don’t use any code-level language information such as lang
attributes.
In-place edits with sed on OS X
I've similar problem with MacOS
sed -i '' 's/oldword/newword/' file1.txt
doesn't works, but
sed -i"any_symbol" 's/oldword/newword/' file1.txt
works well.
jQuery.css() - marginLeft vs. margin-left?
I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...
$(".element").css( { marginLeft : "200px", marginRight : "200px" } );
as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...
$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );
without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.
EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];
How to convert List<string> to List<int>?
Convert string value into integer list
var myString = "010";
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();
Java Ordered Map
Modern Java version of Steffi Keran's answer
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
// sort the linked list using Collections.sort()
list.sort(Comparator.comparing(Map.Entry::getValue));
list.forEach(System.out::println);
}
}
C# Create New T()
Take a look at new Constraint
public class MyClass<T> where T : new()
{
protected T GetObject()
{
return new T();
}
}
T
could be a class that does not have a default constructor: in this case new T()
would be an invalid statement. The new()
constraint says that T
must have a default constructor, which makes new T()
legal.
You can apply the same constraint to a generic method:
public static T GetObject<T>() where T : new()
{
return new T();
}
If you need to pass parameters:
protected T GetObject(params object[] args)
{
return (T)Activator.CreateInstance(typeof(T), args);
}
Clone only one branch
“--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check
#git --version
If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch
#git clone -b branch --single-branch git://github/repository.git
By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.
sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version
Once 1.8.X is installed now simply do:
git clone -b branch --single-branch git://github/repository.git
Git will now only download a single branch from the server.
Change image size with JavaScript
Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length;
for(i=0;i<L;++i){
document.images[i].style.height = 'auto'; //setting CSS value
document.images[i].style.width = 'auto'; //setting CSS value
// document.images[i].height = ''; (don't need this, would be setting img.attribute)
// document.images[i].width = ''; (don't need this, would be setting img.attribute)
}
Multiple conditions in an IF statement in Excel VBA
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
Loop through files in a directory using PowerShell
If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc
file type
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
If you need to do the filteration on multiple types, use the below command.
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
Now $fileNames
variable act as an array from which you can loop and apply your business logic.
Getting Keyboard Input
You can use Scanner class like this:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
TypeError: string indices must be integers, not str // working with dict
Actually I think that more general approach to loop through dictionary is to use iteritems():
# get tuples of term, courses
for term, term_courses in courses.iteritems():
# get tuples of course number, info
for course, info in term_courses.iteritems():
# loop through info
for k, v in info.iteritems():
print k, v
output:
assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian
Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():
for term_courses in courses.itervalues():
for info in term_courses.itervalues():
for k, v in info.iteritems():
print k, v
Creating a REST API using PHP
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
(WAMP/XAMP) send Mail using SMTP localhost
you can directly send mail from php mail() function if you specified the smtp server and smtp port in php.ini, first ask the SMTP server credential to your ISP.
SMTP = smtp.wlink.com.np //put your ISP's smtp server
smtp_port = 25 // your ISP's smtp port.
then just restart the apache server and it will start working. ENjoy ...
CSS image overlay with color and transparency
JSFiddle Demo
HTML:
<div class="image-holder">
<img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>
CSS:
.image-holder {
display:inline-block;
position: relative;
}
.image-holder:after {
content:'';
top: 0;
left: 0;
z-index: 10;
width: 100%;
height: 100%;
display: block;
position: absolute;
background: blue;
opacity: 0.1;
}
.image-holder:hover:after {
opacity: 0;
}
Marker in leaflet, click event
Additional relevant info:
A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.
It seems that when we do:
marker.on('click', function(e) {...
The e
points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this
object which strangely, requires us to use this.options
to get to the options
object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid
then within the function above, we can get the value by invoking: this.options.objid
VBA Excel Provide current Date in Text box
The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.
From VBA you might try using:
textbox.Value = Format(Date(),"mm/dd/yy")
How to read a config file using python
If you need to read all values from a section in properties file in a simple manner:
Your config.cfg
file layout :
[SECTION_NAME]
key1 = value1
key2 = value2
You code:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.cfg file')
details_dict = dict(config.items('SECTION_NAME'))
This will give you a dictionary where keys are same as in config file and their corresponding values.
details_dict
is :
{'key1':'value1', 'key2':'value2'}
Now to get key1's value :
details_dict['key1']
Putting it all in a method which reads sections from config file only once(the first time the method is called during a program run).
def get_config_dict():
if not hasattr(get_config_dict, 'config_dict'):
get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
return get_config_dict.config_dict
Now call the above function and get the required key's value :
config_details = get_config_dict()
key_1_value = config_details['key1']
Generic Multi Section approach:
[SECTION_NAME_1]
key1 = value1
key2 = value2
[SECTION_NAME_2]
key1 = value1
key2 = value2
Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = collections.defaultdict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
To access:
config_dict = get_config_section()
port = config_dict['DB']['port']
(here 'DB' is a section name in config file
and 'port' is a key under section 'DB'.)
Maximum length for MySQL type text
How many characters can a type text field store?
According to Documentation You can use maximum of 21,844 characters if the charset is UTF8
If a lot, would I be able to specify length in the db text type field as I would with varchar?
You dont need to specify the length. If you need more character use data types MEDIUMTEXT or LONGTEXT. With VARCHAR, specifieng length is not for Storage requirement, it is only for how the data is retrieved from data base.
Monitor network activity in Android Phones
Note: tcpdump requires root privileges, so you'll have to root your phone if not done already. Here's an ARM binary of tcpdump (this works for my Samsung Captivate). If you prefer to build your own binary, instructions are here (yes, you'd likely need to cross compile).
Also, check out Shark For Root (an Android packet capture tool based on tcpdump).
I don't believe tcpdump can monitor traffic by specific process ID. The strace method that Chris Stratton refers to seems like more effort than its worth. It would be simpler to monitor specific IPs and ports used by the target process. If that info isn't known, capture all traffic during a period of process activity and then sift through the resulting pcap with Wireshark.
JavaScript - Hide a Div at startup (load)
This method I've used a lot, not sure if it is a very good way but it works fine for my needs.
<html>
<head>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<div id="HiddenStuff1" style="display:none">
CONTENT TO HIDE 1
</div>
<div id="HiddenStuff2" style="display:none">
CONTENT TO HIDE 2
</div>
<div id="HiddenStuff3" style="display:none">
CONTENT TO HIDE 3
</div>
<input id="YOUR ID" title="HIDDEN STUFF 1" type=button name=type value='HIDDEN STUFF 1' onclick="setVisibility('HiddenStuff1', 'inline');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 2" type=button name=type value='HIDDEN STUFF 2' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'inline');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 3" type=button name=type value='HIDDEN STUFF 3' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'inline');";>
</body>
</html>
Split files using tar, gz, zip, or bzip2
You can use the split
command with the -b
option:
split -b 1024m file.tar.gz
It can be reassembled on a Windows machine using @Joshua's answer.
copy /b file1 + file2 + file3 + file4 filetogether
Edit: As @Charlie stated in the comment below, you might want to set a prefix explicitly because it will use x
otherwise, which can be confusing.
split -b 1024m "file.tar.gz" "file.tar.gz.part-"
// Creates files: file.tar.gz.part-aa, file.tar.gz.part-ab, file.tar.gz.part-ac, ...
Edit: Editing the post because question is closed and the most effective solution is very close to the content of this answer:
# create archives
$ tar cz my_large_file_1 my_large_file_2 | split -b 1024MiB - myfiles_split.tgz_
# uncompress
$ cat myfiles_split.tgz_* | tar xz
This solution avoids the need to use an intermediate large file when (de)compressing. Use the tar -C option to use a different directory for the resulting files. btw if the archive consists from only a single file, tar could be avoided and only gzip used:
# create archives
$ gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
# uncompress
$ cat myfile_split.gz_* | gunzip -c > my_large_file
For windows you can download ported versions of the same commands or use cygwin.
MySQL CONCAT returns NULL if any field contain NULL
CONCAT_WS
still produces null for me if the first field is Null. I solved this by adding a zero length string at the beginning as in
CONCAT_WS("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`)
however
CONCAT("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`)
produces Null when the first field is Null.
Classes vs. Modules in VB.NET
It is acceptable to use Module
. Module
is not used as a replacement for Class
. Module
serves its own purpose. The purpose of Module
is to use as a container for
- extension methods,
- variables that are not specific to any
Class
, or
- variables that do not fit properly in any
Class
.
Module
is not like a Class
since you cannot
- inherit from a
Module
,
- implement an
Interface
with a Module
,
- nor create an instance of a
Module
.
Anything inside a Module
can be directly accessed within the Module
assembly without referring to the Module
by its name. By default, the access level for a Module
is Friend
.
How to navigate to to different directories in the terminal (mac)?
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
What is the reason behind "non-static method cannot be referenced from a static context"?
if a method is not static, that "tells" the compiler that the method requires access to instance-level data in the class, (like a non-static field). This data would not be available unless an instance of the class has been created. So the compiler throws an error if you try to call the method from a static method.. If in fact the method does NOT reference any non-static member of the class, make the method static.
In Resharper, for example, just creating a non-static method that does NOT reference any static member of the class generates a warning message "This method can be made static"
How to navigate to a directory in C:\ with Cygwin?
On a related note, you may also like:
shopt -s autocd
This allows you to cd a dir by just typing in the dir
[user@host ~]$ /cygdrive/d
cd /cygdrive/d
[user@host /cygdrive/d]$
To make is persistent you should add it to your ~/.bashrc
How to store directory files listing into an array?
Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.
files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
printf " %s\n" $item
done
How to save a new sheet in an existing excel file, using Pandas?
You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>
# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()
If you want to preserve all existing sheets, you can replace above code between begin and end with:
# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
df = xlsx.parse(sheet_name=sheet, index_col=0)
df.to_excel(writer, sheet_name=sheet)
Assigning default value while creating migration file
You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...
def change
change_column :widgets, :colour, :string, default: 'red'
end
List changes unexpectedly after assignment. How do I clone or copy it to prevent this?
A slight practical perspective to look into memory through id and gc.
>>> b = a = ['hell', 'word']
>>> c = ['hell', 'word']
>>> id(a), id(b), id(c)
(4424020872, 4424020872, 4423979272)
| |
-----------
>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # all referring to same 'hell'
| | |
-----------------------
>>> id(a[0][0]), id(b[0][0]), id(c[0][0])
(4422785208, 4422785208, 4422785208) # all referring to same 'h'
| | |
-----------------------
>>> a[0] += 'o'
>>> a,b,c
(['hello', 'word'], ['hello', 'word'], ['hell', 'word']) # b changed too
>>> id(a[0]), id(b[0]), id(c[0])
(4424018384, 4424018384, 4424018328) # augmented assignment changed a[0],b[0]
| |
-----------
>>> b = a = ['hell', 'word']
>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # the same hell
| | |
-----------------------
>>> import gc
>>> gc.get_referrers(a[0])
[['hell', 'word'], ['hell', 'word']] # one copy belong to a,b, the another for c
>>> gc.get_referrers(('hell'))
[['hell', 'word'], ['hell', 'word'], ('hell', None)] # ('hello', None)
set date in input type date
Update: I'm doing this with date.toISOString().substr(0, 10)
. Gives the same result as the accepted answer and has good support.
How to handle floats and decimal separators with html5 input type number
I have not found a perfect solution but the best I could do was to use type="tel" and disable html5 validation (formnovalidate):
<input name="txtTest" type="tel" value="1,200.00" formnovalidate="formnovalidate" />
If the user puts in a comma it will output with the comma in every modern browser i tried (latest FF, IE, edge, opera, chrome, safari desktop, android chrome).
The main problem is:
- Mobile users will see their phone keyboard which may be different
than the number keyboard.
- Even worse the phone keyboard may not even have a key for a comma.
For my use case I only had to:
- Display the initial value with a comma (firefox strips it out for
type=number)
- Not fail html5 validation (if there is a comma)
- Have the field read exactly as input (with a possible comma)
If you have a similar requirement this should work for you.
Note: I did not like the support of the pattern attribute. The formnovalidate seems to work much better.
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
Here are some examples for insert ... on conflict ...
(pg 9.5+) :
- Insert, on conflict - do nothing.
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict do nothing;`
- Insert, on conflict - do update, specify conflict target via column.
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict(id)
do update set name = 'new_name', size = 3;
- Insert, on conflict - do update, specify conflict target via constraint name.
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict on constraint dummy_pkey
do update set name = 'new_name', size = 4;
unknown type name 'uint8_t', MinGW
EDIT:
To Be Clear: If the order of your #include
s matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include
to the header file causing problems.
At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.
END EDIT
You need to #include
the stdint.h
BEFORE you #include
any other library interfaces that need it.
Example:
My LCD library uses uint8_t types. I wrote my library with an interface (Display.h
) and an implementation (Display.c
)
In display.c, I have the following includes.
#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
And this works.
However, if I re-arrange them like so:
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>
I get the error you describe. This is because Display.h
needs things from stdint.h
but can't access it because that information is compiled AFTER Display.h is compiled.
So move stdint.h
above any library that need it and you shouldn't get the error anymore.
How do you make strings "XML safe"?
By either escaping those characters with htmlspecialchars
, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.
Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>
.
Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).
How to adjust an UIButton's imageSize?
If I understand correctly what you're trying to do, you need to play with the buttons image edge inset. Something like:
myLikesButton.imageEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
Numbering rows within groups in a data frame
Another base R solution would be to split
the data frame per cat
, after that using lapply
: add a column with number 1:nrow(x)
. The last step is to have your final data frame back with do.call
, that is:
df_split <- split(df, df$cat)
df_lapply <- lapply(df_split, function(x) {
x$num <- seq_len(nrow(x))
return(x)
})
df <- do.call(rbind, df_lapply)
How to select only 1 row from oracle sql?
This syntax is available in Oracle 12c:
select * from some_table fetch first 1 row only;
select * from some_table fetch first 1 rows only;
select * from some_table fetch first 10 row only;
select * from some_table fetch first 10 rows only;
^^I just wanted to demonstrate that either row or rows (plural) can be used regardless of the plurality of the desired number of rows.)
python convert list to dictionary
Not sure whether it would help you or not but it works to me:
l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))
Show dialog from fragment?
For me, it was the following-
MyFragment:
public class MyFragment extends Fragment implements MyDialog.Callback
{
ShowDialog activity_showDialog;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_showDialog = (ShowDialog)activity;
}
catch(ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "ShowDialog interface needs to be implemented by Activity.", e);
throw e;
}
}
@Override
public void onClick(View view)
{
...
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(this, 1); //request code
activity_showDialog.showDialog(dialog);
...
}
@Override
public void accept()
{
//accept
}
@Override
public void decline()
{
//decline
}
@Override
public void cancel()
{
//cancel
}
}
MyDialog:
public class MyDialog extends DialogFragment implements View.OnClickListener
{
private EditText mEditText;
private Button acceptButton;
private Button rejectButton;
private Button cancelButton;
public static interface Callback
{
public void accept();
public void decline();
public void cancel();
}
public MyDialog()
{
// Empty constructor required for DialogFragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.dialogfragment, container);
acceptButton = (Button) view.findViewById(R.id.dialogfragment_acceptbtn);
rejectButton = (Button) view.findViewById(R.id.dialogfragment_rejectbtn);
cancelButton = (Button) view.findViewById(R.id.dialogfragment_cancelbtn);
acceptButton.setOnClickListener(this);
rejectButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
getDialog().setTitle(R.string.dialog_title);
return view;
}
@Override
public void onClick(View v)
{
Callback callback = null;
try
{
callback = (Callback) getTargetFragment();
}
catch (ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "Callback of this class must be implemented by target fragment!", e);
throw e;
}
if (callback != null)
{
if (v == acceptButton)
{
callback.accept();
this.dismiss();
}
else if (v == rejectButton)
{
callback.decline();
this.dismiss();
}
else if (v == cancelButton)
{
callback.cancel();
this.dismiss();
}
}
}
}
Activity:
public class MyActivity extends ActionBarActivity implements ShowDialog
{
..
@Override
public void showDialog(DialogFragment dialogFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
dialogFragment.show(fragmentManager, "dialog");
}
}
DialogFragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/dialogfragment_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="@string/example"/>
<Button
android:id="@+id/dialogfragment_acceptbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/dialogfragment_textview"
android:text="@string/accept"
/>
<Button
android:id="@+id/dialogfragment_rejectbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignLeft="@+id/dialogfragment_acceptbtn"
android:layout_below="@+id/dialogfragment_acceptbtn"
android:text="@string/decline" />
<Button
android:id="@+id/dialogfragment_cancelbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_rejectbtn"
android:layout_below="@+id/dialogfragment_rejectbtn"
android:text="@string/cancel" />
<Button
android:id="@+id/dialogfragment_heightfixhiddenbtn"
android:layout_width="200dp"
android:layout_height="20dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_cancelbtn"
android:layout_below="@+id/dialogfragment_cancelbtn"
android:background="@android:color/transparent"
android:enabled="false"
android:text=" " />
</RelativeLayout>
As the name dialogfragment_heightfixhiddenbtn
shows, I just couldn't figure out a way to fix that the bottom button's height was cut in half despite saying wrap_content
, so I added a hidden button to be "cut" in half instead. Sorry for the hack.
PHP header() redirect with POST variables
// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)
I have done the following on a Citrix XenDesktop VM, however you could just do this on your local PC:
Microsoft Virtual PC
If you are running Windows 7, you can download Microsoft virtual PC and create as many copies of Virtual PC as you need for testing without any licensing issues:
This requires no additional Windows licenses; you simply set up multiple machines with different browsers on them. You can run the browsers out of the window by following the tutorial available here:
Installing Browsers
You will need to create at least 3 virtual PC's (tip: keep the memory down to 256mb for each virtual PC to avoid wasting memory on the virtual desktops).
On the first VPC I installed this:
along with Chrome 1, Safari 3.1, Opera 8.
On the second I installed Internet Explorer 7, Chrome 3, Safari 3.2.1, Opera 9.
On the third I installed Internet Explorer 8, Chrome 8. Safari 4.0.5, Opera 10.
On Windows 7 (native machine) I had Internet Explorer 9, Chrome 11, Safari 5, Opera 11 and for Firefox I install the following app natively too:
Personally I would not go back further than 5 years with compatibility (other than IE for government networks) unless you have a specific requirement (I split Chrome & Opera across years as I decided there were just to many releases). However, if you find that someone has a specific issue with a site using a specific version of the browser it becomes very easy to install additional virtual machines to run additional browser versions.
Obtaining Older Browsers
You can download older versions of Chrome from here:
and Opera here:
Virtualizing The Test Platform (Optional)
I use Xen Desktop to virtualize the testing platform so that I can use it anywhere and have included my favorite development tools on there as well:
The express edition is available for free.
A Good Commercial Alternative
Another great product I recently came accross is Stylizer which is a CSS editor that installs multiple versions of browsers for testing purposes, however this is a commercial paid for product but is very good and worth the small fee they require to run it.
How to retrieve a module's path?
From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.
some_dir/
maincli.py
top_package/
__init__.py
level_one_a/
__init__.py
my_lib_a.py
level_two/
__init__.py
hello_world.py
level_one_b/
__init__.py
my_lib_b.py
So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.py:
import sys
import os
import imp
class ConfigurationException(Exception):
pass
# inside of my_lib_a.py
def get_maincli_path():
maincli_path = os.path.abspath(imp.find_module('maincli')[1])
# top_package = __package__.split('.')[0]
# mod = sys.modules.get(top_package)
# modfile = mod.__file__
# pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))
# maincli_path = os.path.join(pkg_in_dir, 'maincli.py')
if not os.path.exists(maincli_path):
err_msg = 'This script expects that "maincli.py" be installed to the '\
'same directory: "{0}"'.format(maincli_path)
raise ConfigurationException(err_msg)
return maincli_path
Based on posting by PlasmaBinturong I modified the code.
How to access nested elements of json object using getJSONArray method
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
Python pandas Filtering out nan from a data selection of a column of strings
Just drop them:
nms.dropna(thresh=2)
this will drop all rows where there are at least two non-NaN
.
Then you could then drop where name is NaN
:
In [87]:
nms
Out[87]:
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN NaN
[5 rows x 3 columns]
In [89]:
nms = nms.dropna(thresh=2)
In [90]:
nms[nms.name.notnull()]
Out[90]:
movie name rating
0 thg John 3
3 mol Graham NaN
[2 rows x 3 columns]
EDIT
Actually looking at what you originally want you can do just this without the dropna
call:
nms[nms.name.notnull()]
UPDATE
Looking at this question 3 years later, there is a mistake, firstly thresh
arg looks for at least n
non-NaN
values so in fact the output should be:
In [4]:
nms.dropna(thresh=2)
Out[4]:
movie name rating
0 thg John 3.0
1 thg NaN 4.0
3 mol Graham NaN
It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.
How to use the switch statement in R functions?
I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {}
statements.
Each time the switch function is the same but the command we supply changes.
do.this <- "T1"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
Here it is inside a function:
FUN <- function(df, do.this){
switch(do.this,
T1={X <- t(df)
P <- colSums(df)%*%X
},
T2={X <- colMeans(df)
P <- outer(X, X)
},
stop("Enter something that switches me!")
)
return(P)
}
FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")
Is there a way to collapse all code blocks in Eclipse?
There is a hotkey, mapped by default to Ctrl+Shift+NUM_KEYPAD_DIVIDE.
You can change it to something else via Window -> Preferences, search for "Keys", then for "Collapse All".
To open all code blocks the shortcut is Ctrl+Shift+NUM_KEYPAD_MULTIPLY.
In the Eclipse extension PyDev, close all code blocks is
Ctrl + 9
To open all blocks, is Ctrl + 0
Node.js client for a socket.io server
Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.
PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
When you're working with strings in PHP you'll need to pay special attention to the formation, using "
or '
$string = 'Hello, world!';
$string = "Hello, world!";
Both of these are valid, the following is not:
$string = "Hello, world';
You must also note that '
inside of a literal started with "
will not end the string, and vice versa. So when you have a string which contains '
, it is generally best practice to use double quotation marks.
$string = "It's ok here";
Escaping the string is also an option
$string = 'It\'s ok here too';
More information on this can be found within the documentation
Send Post Request with params using Retrofit
This is a simple solution where we do not need to use JSON
public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
@Field("name") String name,
@Field("username") String username,
@Field("password") String password,
@Field("email") String email,
Callback<Response> callback);
}
method to send data
private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
editTextName.getText().toString(),
editTextUsername.getText().toString(),
editTextPassword.getText().toString(),
editTextEmail.getText().toString(),
//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
Now we can get the post request using php aur any other server side scripting.
Source Android Retrofit Tutorial
What is aria-label and how should I use it?
The title
attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).
As such, the mindful approach here would be to serve all users. I would add both title
and aria-label
attributes (serving different types of users and different types of usage of the web).
Here's a good article that explains aria-label
in depth
Writing outputs to log file and console
I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a)
, because I was wondering how to accomplish this using exec
. I came across a creative solution using here-doc syntax and .
: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script
I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:
#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged
It is not as readable as the exec
solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh
implements multios, but it may have less overhead than tee
. Unfortunately it seems that one cannot use multios with exec
.
How to add dll in c# project
The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.
I usually create a libs
folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.
(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)
PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...
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 :)
Swift 3: Display Image from URL
Use extension for UIImageView to Load URL Images.
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func imageURLLoad(url: URL) {
DispatchQueue.global().async { [weak self] in
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
How to save all files from source code of a web site?
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
Purpose of returning by const value?
In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that +
returned a non-const value, and you could write:
(a + b).expensive();
In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.
In summary, there is a rationale for this practice, but it is essentially obsolete.
Unix command-line JSON parser?
I just made jkid which is a small command-line json explorer that I made to easily explore big json objects. Objects can be explored "transversally" and a "preview" option is there to avoid console overflow.
$ echo '{"john":{"size":20, "eyes":"green"}, "bob":{"size":30, "eyes":"brown"}}' > test3.json
$ jkid . eyes test3.json
object[.]["eyes"]
{
"bob": "brown",
"john": "green"
}
How to get name of the computer in VBA?
Looks like I'm late to the game, but this is a common question...
This is probably the code you want.
Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.
Public Function ComputerName() As String
'' Returns the host name
'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:
' Dim objNetwork As IWshRuntimeLibrary.WshNetwork
' Set objNetwork = New IWshRuntimeLibrary.WshNetwork
Dim objNetwork As Object
Set objNetwork = CreateObject("WScript.Network")
ComputerName = objNetwork.ComputerName
Set objNetwork = Nothing
End Function
You'll probably need this, too:
Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name
'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:
' Dim objNetwork As IWshRuntimeLibrary.WshNetwork
' Set objNetwork = New IWshRuntimeLibrary.WshNetwork
Dim objNetwork As Object
Set objNetwork = CreateObject("WScript.Network")
If WithDomain Then
UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
Else
UserName = objNetwork.UserName
End If
Set objNetwork = Nothing
End Function
How do I upload a file with the JS fetch API?
To submit a single file, you can simply use the File
object from the input
's .files
array directly as the value of body:
in your fetch()
initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File
inherits from Blob
, and Blob
is one of the permissible BodyInit
types defined in the Fetch Standard.
OperationalError, no such column. Django
In my case, in admin.py
I was querying from the table in which new ForeignKey
field was added. So comment out admin.py
then run makemigrations and migrate command as usual. Finally uncomment admin.py
.
Styles.Render in MVC4
As defined in App_start.BundleConfig, it's just calling
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Nothing happens even if you remove that section.
$(this).serialize() -- How to add a value?
Instead of
data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
you probably want
data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
You should be careful to URL-encode the value of NonFormValue
if it might contain any special characters.
Nullable property to entity field, Entity Framework through Code First
The other option is to tell EF to allow the column to be null:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();
base.OnModelCreating(modelBuilder);
}
This code should be in the object that inherits from DbContext
.
What's the best visual merge tool for Git?
You can change the tool used by git mergetool by passing git mergetool -t=<tool>
or --tool=<tool>
. To change the default (from vimdiff) use git config merge.tool <tool>
.
Pass arguments into C program from command line
Instead of getopt()
, you may also consider using argp_parse()
(an alternative interface to the same library).
From libc manual:
getopt
is more standard (the
short-option only version of it is a
part of the POSIX standard), but using
argp_parse
is often easier, both for
very simple and very complex option
structures, because it does more of
the dirty work for you.
But I was always happy with the standard getopt
.
N.B. GNU getopt
with getopt_long
is GNU LGPL.
How to return JSON with ASP.NET & jQuery
This structure works for me - I used it in a small tasks management application.
The controller:
public JsonResult taskCount(string fDate)
{
// do some stuff based on the date
// totalTasks is a count of the things I need to do today
// tasksDone is a count of the tasks I actually did
// pcDone is the percentage of tasks done
return Json(new {
totalTasks = totalTasks,
tasksDone = tasksDone,
percentDone = pcDone
});
}
In the AJAX call I access the data like this:
.done(function (data) {
// data.totalTasks
// data.tasksDone
// data.percentDone
});
SSL certificate is not trusted - on mobile only
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
How do I show a running clock in Excel?
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
How are SSL certificate server names resolved/Can I add alternative names using keytool?
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST
be used as the identity. Otherwise, the (most specific) Common Name
field in the Subject field of the certificate MUST be used. Although
the use of the Common Name is existing practice, it is deprecated and
Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a
hostname. In this case, the iPAddress subjectAltName must be present
in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
How to pass anonymous types as parameters?
I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:
public void LogEmployees (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}
Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.
JPanel setBackground(Color.BLACK) does nothing
I just tried a bare-bones implementation and it just works:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello");
frame.setPreferredSize(new Dimension(200, 200));
frame.add(new Board());
frame.pack();
frame.setVisible(true);
}
}
public class Board extends JPanel {
private Player player = new Player();
public Board(){
setBackground(Color.BLACK);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getCenter().x, player.getCenter().y,
player.getRadius(), player.getRadius());
}
}
public class Player {
private Point center = new Point(50, 50);
public Point getCenter() {
return center;
}
private int radius = 10;
public int getRadius() {
return radius;
}
}
AngularJS - get element attributes values
If you are using Angular2+ following code will help
You can use following syntax to get attribute value from html element
//to retrieve html element
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
//get attribute value from that element
const attributeValue = element.attributeName // like textContent/href