JQuery ajax call default timeout value
There doesn't seem to be a standardized default value. I have the feeling the default is 0
, and the timeout event left totally dependent on browser and network settings.
For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).
Add placeholder text inside UITextView in Swift?
SET value in view load
txtVw!.autocorrectionType = UITextAutocorrectionType.No
txtVw!.text = "Write your Placeholder"
txtVw!.textColor = UIColor.lightGrayColor()
func textViewDidBeginEditing(textView: UITextView) {
if (txtVw?.text == "Write your Placeholder")
{
txtVw!.text = nil
txtVw!.textColor = UIColor.blackColor()
}
}
func textViewDidEndEditing(textView: UITextView) {
if txtVw!.text.isEmpty
{
txtVw!.text = "Write your Placeholder"
txtVw!.textColor = UIColor.lightGrayColor()
}
textView.resignFirstResponder()
}
Escape double quotes in a string
In C#, there are at least 4 ways to embed a quote within a string:
- Escape quote with a backslash
- Precede string with @ and use double quotes
- Use the corresponding ASCII character
- Use the Hexadecimal Unicode character
Please refer this document for detailed explanation.
HTML button to NOT submit form
return false;
at the end of the onclick handler will do the job. However, it's be better to simply add type="button"
to the <button>
- that way it behaves properly even without any JavaScript.
Finding CN of users in Active Directory
Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:
cn=admin,cn=users,DC=domain,DC=company,DC=com
Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin)
. If so, you should get the full DN back in that query.
How to find out when a particular table was created in Oracle?
You copy and paste the following code. It will display all the tables with Name and Created Date
SELECT object_name,created FROM user_objects
WHERE object_name LIKE '%table_name%'
AND object_type = 'TABLE';
Note: Replace '%table_name%' with the table name you are looking for.
Network usage top/htop on Linux
Also iftop:
display bandwidth usage on an interface
iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...
Amazon S3 exception: "The specified key does not exist"
Don't forget buckets are region specific. That might be an issue.
Also try using the S3 console to navigate to the actual object, and then click on Copy Path
, you will get something like:
s3://<bucket-name>/<path>/object.txt
As long as whatever you are passing it to parses that properly I find that is the safest thing to do.
How to check if all inputs are not empty with jQuery
You can do it.here is code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;
$(".bs-example input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
$(this).focus();
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
alert("Please fill in all the required fields (indicated by *)");
}
return isFormValid;
}
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
How can I add an empty directory to a Git repository?
Let's say you need an empty directory named tmp :
$ mkdir tmp
$ touch tmp/.gitignore
$ git add tmp
$ echo '*' > tmp/.gitignore
$ git commit -m 'Empty directory' tmp
In other words, you need to add the .gitignore file to the index before you can tell Git to ignore it (and everything else in the empty directory).
What is the naming convention in Python for variable and function names?
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething()
than SomeClass.do_something()
. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
Why does one use dependency injection?
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH
environment variable (or other language equivalent, like PYTHONPATH
, LD_LIBRARY_PATH
) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.
How can I pretty-print JSON using node.js?
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
Detecting when user scrolls to bottom of div with jQuery
Guys this is the solution to the zoom issue, it works with all zoom levels, in case you need it:
if ( Math.abs(elem.offset().top) + elem.height() + elem.offset().top >= elem.outerHeight() ) {
console.log("bottom");
// We're at the bottom!
}
});
}
Homebrew install specific version of formula?
Update on the Library/Formula/postgresql.rb line 8 to
http://ftp2.uk.postgresql.org/sites/ftp.postgresql.org/source/v8.4.6/postgresql-8.4.6.tar.bz2
And MD5 on line 9 to
fcc3daaf2292fa6bf1185ec45e512db6
Save and exit.
brew install postgres
initdb /usr/local/var/postgres
Now in this stage you might face the postgresql could not create shared memory segment
error, to work around that update the /etc/sysctl.conf
like this:
kern.sysv.shmall=65536
kern.sysv.shmmax=16777216
Try initdb /usr/local/var/postgres
again, and it should run smooth.
To run postgresql on start
launchctl load -w /usr/local/Cellar/postgresql/8.4.6/org.postgresql.postgres.plist
Hope that helps :)
Return multiple values from a SQL Server function
Here's the Query Analyzer template for an in-line function - it returns 2 values by default:
-- =============================================
-- Create inline function (IF)
-- =============================================
IF EXISTS (SELECT *
FROM sysobjects
WHERE name = N'<inline_function_name, sysname, test_function>')
DROP FUNCTION <inline_function_name, sysname, test_function>
GO
CREATE FUNCTION <inline_function_name, sysname, test_function>
(<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>)
RETURNS TABLE
AS
RETURN SELECT @p1 AS c1,
@p2 AS c2
GO
-- =============================================
-- Example to execute function
-- =============================================
SELECT *
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>
(<value_for_@param1, , 1>,
<value_for_@param2, , 'a'>)
GO
Add timer to a Windows Forms application
Something like this in your form main. Double click the form in the visual editor to create the form load event.
Timer Clock=new Timer();
Clock.Interval=2700000; // not sure if this length of time will work
Clock.Start();
Clock.Tick+=new EventHandler(Timer_Tick);
Then add an event handler to do something when the timer fires.
public void Timer_Tick(object sender,EventArgs eArgs)
{
if(sender==Clock)
{
// do something here
}
}
String.Format like functionality in T-SQL?
If you are using SQL Server 2012 and above, you can use FORMATMESSAGE
. eg.
DECLARE @s NVARCHAR(50) = 'World';
DECLARE @d INT = 123;
SELECT FORMATMESSAGE('Hello %s, %d', @s, @d)
-- RETURNS 'Hello World, 123'
More examples from MSDN: FORMATMESSAGE
SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);
SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Hello %s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
NOTES:
- Undocumented in 2012
- Limited to 2044 characters
- To escape the % sign, you need to double it.
- If you are logging errors in extended events, calling
FORMATMESSAGE
comes up as a (harmless) error
Python Array with String Indices
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
Convert character to ASCII code in JavaScript
For those that want to get a sum of all the ASCII codes for a string:
'Foobar'
.split('')
.map(x=>x.charCodeAt(0))
.reduce((a,b)=>a+b);
Or, ES6:
[...'Foobar']
.map(char => char.charCodeAt(0))
.reduce((current, previous) => previous + current)
Dynamic tabs with user-click chosen components
there is component ready to use (rc5 compatible)
ng2-steps
which uses Compiler
to inject component to step container
and service for wiring everything together (data sync)
import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';
import { StepsService } from './ng2-steps';
@Directive({
selector:'[ng2-step]'
})
export class StepDirective implements OnInit{
@Input('content') content:any;
@Input('index') index:string;
public instance;
constructor(
private compiler:Compiler,
private viewContainerRef:ViewContainerRef,
private sds:StepsService
){}
ngOnInit(){
//Magic!
this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
const injector = this.viewContainerRef.injector;
this.viewContainerRef.createComponent(cmpFactory, 0, injector);
});
}
}
Could not find main class HelloWorld
I had the same problem. Perhaps, the problem is that you have compiled and executed the class with different Java versions.
Make sure the version of the compiler is the same as the command "java":
javac -version
java -version
In Linux, use
sudo update-alternatives --config java
to change the version of Java.
How to do a deep comparison between 2 objects with lodash?
Deep compare using a template of (nested) properties to check
function objetcsDeepEqualByTemplate(objectA, objectB, comparisonTemplate) {
if (!objectA || !objectB) return false
let areDifferent = false
Object.keys(comparisonTemplate).some((key) => {
if (typeof comparisonTemplate[key] === 'object') {
areDifferent = !objetcsDeepEqualByTemplate(objectA[key], objectB[key], comparisonTemplate[key])
return areDifferent
} else if (comparisonTemplate[key] === true) {
areDifferent = objectA[key] !== objectB[key]
return areDifferent
} else {
return false
}
})
return !areDifferent
}
const objA = {
a: 1,
b: {
a: 21,
b: 22,
},
c: 3,
}
const objB = {
a: 1,
b: {
a: 21,
b: 25,
},
c: true,
}
// template tells which props to compare
const comparisonTemplateA = {
a: true,
b: {
a: true
}
}
objetcsDeepEqualByTemplate(objA, objB, comparisonTemplateA)
// returns true
const comparisonTemplateB = {
a: true,
c: true
}
// returns false
objetcsDeepEqualByTemplate(objA, objB, comparisonTemplateB)
This will work in the console. Array support could be added if needed
Can I grep only the first n lines of a file?
Or use awk
for a single process without |
:
awk '/your_regexp/ && NR < 11' INPUTFILE
On each line, if your_regexp
matches, and the number of records (lines) is less than 11, it executes the default action (which is printing the input line).
Or use sed
:
sed -n '/your_regexp/p;10q' INPUTFILE
Checks your regexp and prints the line (-n
means don't print the input, which is otherwise the default), and quits right after the 10th line.
Delete a database in phpMyAdmin
How to delete a database in phpMyAdmin?
From the Operations tab of the database, look for (and click) the text Drop the database (DROP)
.
file_get_contents() Breaks Up UTF-8 Characters
In Turkish language, mb_convert_encoding or any other charset conversion did not work.
And also urlencode did not work because of space char converted to + char. It must be %20 for percent encoding.
This one worked!
$url = rawurlencode($url);
$url = str_replace("%3A", ":", $url);
$url = str_replace("%2F", "/", $url);
$data = file_get_contents($url);
Get contentEditable caret index position
A straight forward way, that iterates through all the chidren of the contenteditable div until it hits the endContainer. Then I add the end container offset and we have the character index. Should work with any number of nestings. uses recursion.
Note: requires a poly fill for ie to support Element.closest('div[contenteditable]')
https://codepen.io/alockwood05/pen/vMpdmZ
function caretPositionIndex() {
const range = window.getSelection().getRangeAt(0);
const { endContainer, endOffset } = range;
// get contenteditableDiv from our endContainer node
let contenteditableDiv;
const contenteditableSelector = "div[contenteditable]";
switch (endContainer.nodeType) {
case Node.TEXT_NODE:
contenteditableDiv = endContainer.parentElement.closest(contenteditableSelector);
break;
case Node.ELEMENT_NODE:
contenteditableDiv = endContainer.closest(contenteditableSelector);
break;
}
if (!contenteditableDiv) return '';
const countBeforeEnd = countUntilEndContainer(contenteditableDiv, endContainer);
if (countBeforeEnd.error ) return null;
return countBeforeEnd.count + endOffset;
function countUntilEndContainer(parent, endNode, countingState = {count: 0}) {
for (let node of parent.childNodes) {
if (countingState.done) break;
if (node === endNode) {
countingState.done = true;
return countingState;
}
if (node.nodeType === Node.TEXT_NODE) {
countingState.count += node.length;
} else if (node.nodeType === Node.ELEMENT_NODE) {
countUntilEndContainer(node, endNode, countingState);
} else {
countingState.error = true;
}
}
return countingState;
}
}
Printing prime numbers from 1 through 100
To find whether no. is prime or not C++:
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int n, counter=0;
cout <<"Enter a number to check whether it is prime or not \n";
cin>>n;
for(int i=2; i<=n-1;i++) {
if (n%i==0) {
cout<<n<<" is NOT a prime number \n";
break;
}
counter++;
}
//cout<<"Value n is "<<n<<endl;
//cout << "number of times counter run is "<<counter << endl;
if (counter == n-2)
cout << n<< " is prime \n";
return 0;
}
Logo image and H1 heading on the same line
Steps:
- Surround both the elements with a container div.
- Add
overflow:auto
to container div.
- Add
float:left
to the first element.
- Add
position:relative; top: 0.2em; left: 24em
to the second element (Top and left values can vary according to you).
How to programmatically connect a client to a WCF service?
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
ImportError: no module named win32api
After installing pywin32
Steps to correctly install your module (pywin32)
First search where is your python pip is present
1a. For Example in my case location of pip -
C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
Then open your command prompt and change directory to your pip folder location.
cd C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts>pip install
pypiwin32
Restart your IDE
All done now you can use the module .
Javascript : Send JSON Object with Ajax?
With jQuery:
$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });
Without jQuery:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));
getMinutes() 0-9 - How to display two digit numbers?
Numbers don't have a length, but you can easily convert the number to a string, check the length and then prepend the 0 if it's necessary:
var strMonth = '' + date.getMinutes();
if (strMonth.length == 1) {
strMonth = '0' + strMonth;
}
Sending message through WhatsApp
This works to me:
public static void shareWhatsApp(Activity appActivity, String texto) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, texto);
PackageManager pm = appActivity.getApplicationContext().getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(sendIntent, 0);
boolean temWhatsApp = false;
for (final ResolveInfo info : matches) {
if (info.activityInfo.packageName.startsWith("com.whatsapp")) {
final ComponentName name = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setComponent(name);
temWhatsApp = true;
break;
}
}
if(temWhatsApp) {
//abre whatsapp
appActivity.startActivity(sendIntent);
} else {
//alerta - você deve ter o whatsapp instalado
Toast.makeText(appActivity, appActivity.getString(R.string.share_whatsapp), Toast.LENGTH_SHORT).show();
}
}
tkinter: how to use after method
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep
calling the callback, you need to reregister the callback inside
itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
jQuery Dialog Box
I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.
The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.
So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!
<script type="text/javascript">
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 350,
width: 400,
modal: true,
position: 'center',
autoOpen:false,
title:'Hello World',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
//if the contents have been hidden with css, you need this
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
//function to close dialog, probably called by a button in the dialog
var closeDialog = function() {
$myWindow.dialog("close");
}
</script>
</head>
<body>
<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
<p>I am a modal dialog</p>
</div>
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
No REAL easy way to do this. Lots of ideas out there, though.
Best one I've found:
SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
SELECT column_name + ','
FROM information_schema.columns AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;
Or a version that works correctly if the data might contain characters such as <
WITH extern
AS (SELECT DISTINCT table_name
FROM INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM extern
CROSS APPLY (SELECT column_name + ','
FROM INFORMATION_SCHEMA.COLUMNS AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH(''), TYPE) x (column_names)
CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names)
Plot smooth line with PyPlot
Here is a simple solution for dates:
from scipy.interpolate import make_interp_spline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from datetime import datetime
data = {
datetime(2016, 9, 26, 0, 0): 26060, datetime(2016, 9, 27, 0, 0): 23243,
datetime(2016, 9, 28, 0, 0): 22534, datetime(2016, 9, 29, 0, 0): 22841,
datetime(2016, 9, 30, 0, 0): 22441, datetime(2016, 10, 1, 0, 0): 23248
}
#create data
date_np = np.array(list(data.keys()))
value_np = np.array(list(data.values()))
date_num = dates.date2num(date_np)
# smooth
date_num_smooth = np.linspace(date_num.min(), date_num.max(), 100)
spl = make_interp_spline(date_num, value_np, k=3)
value_np_smooth = spl(date_num_smooth)
# print
plt.plot(date_np, value_np)
plt.plot(dates.num2date(date_num_smooth), value_np_smooth)
plt.show()
How to trigger a build only if changes happen on particular set of files
The Git plugin has an option (excluded region) to use regexes to determine whether to skip building based on whether files in the commit match the excluded region regex.
Unfortunately, the stock Git plugin does not have a "included region" feature at this time (1.15). However, someone posted patches on GitHub that work on Jenkins and Hudson that implement the feature you want.
It is a little work to build, but it works as advertised and has been extremely useful since one of my Git trees has multiple independent projects.
https://github.com/jenkinsci/git-plugin/pull/49
Update: The Git plugin (1.16) now has the 'included' region feature.
StringIO in Python3
In order to make examples from here
work with Python 3.5.2, you can rewrite as follows :
import io
data =io.BytesIO(b"1, 2, 3\n4, 5, 6")
import numpy
numpy.genfromtxt(data, delimiter=",")
The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes
may be a better name than genfromtxt
.
When should I use Lazy<T>?
A great real-world example of where lazy loading comes in handy is with ORM's (Object Relation Mappers) such as Entity Framework and NHibernate.
Say you have an entity Customer which has properties for Name, PhoneNumber, and Orders. Name and PhoneNumber are regular strings but Orders is a navigation property that returns a list of every order the customer ever made.
You often might want to go through all your customer's and get their name and phone number to call them. This is a very quick and simple task, but imagine if each time you created a customer it automatically went and did a complex join to return thousands of orders. The worst part is that you aren't even going to use the orders so it is a complete waste of resources!
This is the perfect place for lazy loading because if the Order property is lazy it will not go fetch all the customer's order unless you actually need them. You can enumerate the Customer objects getting only their Name and Phone Number while the Order property is patiently sleeping, ready for when you need it.
Genymotion error at start 'Unable to load virtualbox'
FIXED SOLUTION
Run below command in terminal, It denotes where is your virtualbox install on MAC/Linux.
$ which vboxmanage
/usr/local/bin/VBoxManage
Genymotion search the virtualBox in /usr/bin/VBoxManage while it is located to /usr/local/bin/VBoxManage , you need to create the symlink to that location , Run in terminal to fix it.
sudo ln -s /usr/local/bin/VBoxManage /usr/bin/VBoxManage
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
The only solution that worked for me and $.each
was definitely causing the error. so i used for loop
and it's not throwing error anymore.
Example code
$.ajax({
type: 'GET',
url: 'https://example.com/api',
data: { get_param: 'value' },
success: function (data) {
for (var i = 0; i < data.length; ++i) {
console.log(data[i].NameGerman);
}
}
});
How do I "select Android SDK" in Android Studio?
There are multiple hit & trial solutions for this error. One of them will surely work for you.
Below are the solutions:
1.
Tools -> Android -> Sync Project with Gradle Files (Android Studio
3.0.1)
2.
Go to build.gradle and click sync now
3.
Click this icon to sync gradle enter image description here
or edit any of your module gradle and then sync
4.
File -> Settings -> Android SDK -> Android SDK Location Edit ->
Android SDK
5.
Open build.gradle file, just add a space or press enter. Then sync
project.
6.
File -> Invalidate Caches / Restart
What is PECS (Producer Extends Consumer Super)?
The PECS "rule" just ensures that the following is legal:
- Consumer: whatever
?
is, it can legally refer to T
- Producer: whatever
?
is, it can legally be referred to by T
The typical pairing along the lines of List<? extends T> producer, List<? super T> consumer
is simply ensuring that the compiler can enforce the standard "IS-A" inheritance relationship rules. If we could do so legally, it might be simpler to say <T extends ?>, <? extends T>
(or better yet in Scala, as you can see above, it's [-T], [+T]
. Unfortunately the best we can do is <? super T>, <? extends T>
.
When I first encountered this and broke it down in my head the mechanics made sense but the code itself continued to look confusing to me - I kept thinking "it seems like the bounds shouldn't need to be inverted like that" - even though I was clear on the above - that it's simply about guaranteeing compliance with the standard rules of reference.
What helped me was looking at it using ordinary assignment as an analogy.
Consider the following (not production ready) toy code:
// copies the elements of 'producer' into 'consumer'
static <T> void copy(List<? extends T> producer, List<? super T> consumer) {
for(T t : producer)
consumer.add(t);
}
Illustrating this in terms of the assignment analogy, for consumer
the ?
wildcard (unknown type) is the reference - the "left hand side" of the assignment - and <? super T>
ensures that whatever ?
is, T
"IS-A" ?
- that T
can be assigned to it, because ?
is a super type (or at most the same type) as T
.
For producer
the concern is the same it's just inverted: producer
's ?
wildcard (unknown type) is the referent - the "right hand side" of the assignment - and <? extends T>
ensures that whatever ?
is, ?
"IS-A" T
- that it can be assigned to a T
, because ?
is a sub type (or at least the same type) as T
.
How to read all files in a folder from Java?
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
Service vs IntentService in the Android platform
Android IntentService vs Service
1.Service
- A Service is invoked using startService().
- A Service can be invoked from any thread.
- A Service runs background operations on the Main Thread of the
Application by default. Hence it can block your Application’s UI.
- A Service invoked multiple times would create multiple instances.
- A service needs to be stopped using stopSelf() or stopService().
- Android service can run parallel operations.
2. IntentService
- An IntentService is invoked using Intent.
- An IntentService can in invoked from the Main thread only.
- An IntentService creates a separate worker thread to run background
operations.
- An IntentService invoked multiple times won’t create multiple
instances.
- An IntentService automatically stops after the queue is completed. No
need to trigger stopService() or stopSelf().
- In an IntentService, multiple intent calls are automatically Queued
and they would be executed sequentially.
- An IntentService cannot run parallel operation like a Service.
Refer from Here
Ping with timestamp on Windows CLI
@echo off
ping -t localhost|find /v ""|cmd /q /v:on /c "for /l %%a in (0) do (set "data="&set /p "data="&if defined data echo(!time! !data!)"
note: code to be used inside a batch file. To use from command line replace %%a
with %a
Start the ping, force a correct line buffered output (find /v
), and start a cmd
process with delayed expansion enabled that will do an infinite loop reading the piped data that will be echoed to console prefixed with the current time.
2015-01-08 edited:
In faster/newer machines/os versions there is a synchronization problem in previous code, making the set /p
read a line while the ping
command is still writting it and the result are line cuts.
@echo off
ping -t localhost|cmd /q /v /c "(pause&pause)>nul & for /l %%a in () do (set /p "data=" && echo(!time! !data!)&ping -n 2 localhost>nul"
Two aditional pause
commands are included at the start of the subshell (only one can be used, but as pause
consumes a input character, a CRLF pair is broken and a line with a LF is readed) to wait for input data, and a ping -n 2 localhost
is included to wait a second for each read in the inner loop. The result is a more stable behaviour and less CPU usage.
NOTE: The inner ping
can be replaced with a pause
, but then the first character of each readed line is consumed by the pause
and not retrieved by the set /p
Rails: How to run `rails generate scaffold` when the model already exists?
You can make use of scaffold_controller
and remember to pass the attributes
of the model, or scaffold will be generated without the attributes.
rails g scaffold_controller User name email
# or
rails g scaffold_controller User name:string email:string
This command will generate following files:
create app/controllers/users_controller.rb
invoke haml
create app/views/users
create app/views/users/index.html.haml
create app/views/users/edit.html.haml
create app/views/users/show.html.haml
create app/views/users/new.html.haml
create app/views/users/_form.html.haml
invoke test_unit
create test/controllers/users_controller_test.rb
invoke helper
create app/helpers/users_helper.rb
invoke test_unit
invoke jbuilder
create app/views/users/index.json.jbuilder
create app/views/users/show.json.jbuilder
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 :)
Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"
You can use below class for validation:
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
*/
public boolean validate(final String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
where 6 and 20 are minimum and maximum length for the password.
Magento - Retrieve products with a specific attribute value
I have added line
$this->_productCollection->addAttributeToSelect('releasedate');
in
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
in function _getProductCollection()
and then call it in
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
How can I render inline JavaScript with Jade / Pug?
THIRD VERSION OF MY ANSWER:
Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -
. This is a flash message example that I use in a partial. Hope this helps!
-if(typeof(info) !== 'undefined')
-if (info)
- if(info.length){
ul
-info.forEach(function(info){
li= info
-})
-}
Is the code you're trying to get to compile the code in your question?
If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -
; second, after you type -if
you don't need to type the {
or }
either. That's what makes Jade pretty sweet.
--------------ORIGINAL ANSWER BELOW ---------------
Try prepending if
with -
:
-if(10 == 10)
//do whatever you want here as long as it's indented two spaces from
the `-` above
There are also tons of Jade examples at:
https://github.com/visionmedia/jade/blob/master/examples/
How do you get the cursor position in a textarea?
Here's a cross browser function I have in my standard library:
function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}
Use it in your code like this:
var cursorPosition = getCursorPos($('#myTextarea')[0])
Here's its complementary function:
function setCursorPos(input, start, end) {
if (arguments.length < 3) end = start;
if ("selectionStart" in input) {
setTimeout(function() {
input.selectionStart = start;
input.selectionEnd = end;
}, 1);
}
else if (input.createTextRange) {
var rng = input.createTextRange();
rng.moveStart("character", start);
rng.collapse();
rng.moveEnd("character", end - start);
rng.select();
}
}
http://jsfiddle.net/gilly3/6SUN8/
Including one C source file in another?
You can properly include .C or .CPP files into other source files.
Depending on your IDE, you can usually prevent double-linkage by looking at the source files properties you want to be included, usually by right clicking on it and clicking properties, and uncheck/check compile/link/exclude from build or whatever option it may be. Or you could not include the file in the project itself, thus the IDE wont even know it exists and wont try to compile it. And with makefiles you simply just wouldn't put the file in it for compiling and linking.
EDIT: Sorry I made it an answer instead of a reply onto other answers :(
Tomcat Server Error - Port 8080 already in use
To get rid of this error just click on server tab on eclipse . You will get list of servers as below image (In my case it was tomcat 8 only)
Double click on the respective server. You will get screen as shown below :-
Now change Conflicting port number. In my case I changed 8080 to 8081 (highlighted portion). Save it (ctrl+s) and hence you can start your server now.
Centering a background image, using CSS
if your not satisfied with the answers above then use this
* {margin: 0;padding: 0;}
html
{
height: 100%;
}
body
{
background-image: url("background.png");
background-repeat: no-repeat;
background-position: center center;
background-size: 80%;
}
Select all DIV text with single mouse click
There is pure CSS4 solution:
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
user-select
is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.
_x000D_
_x000D_
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
_x000D_
<div class="selectable">
click and all this will be selected
</div>
_x000D_
_x000D_
_x000D_
Read more on user-select here on MDN and play with it here in w3scools
Send PHP variable to javascript function
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username
and password
:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in
to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data);
line in the success function would alert that message. Of course, you can echo
anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script>
tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?>
at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
Passing a method as a parameter in Ruby
I would recommend to use ampersand to have an access to named blocks within a function. Following the recommendations given in this article you can write something like this (this is a real scrap from my working program):
# Returns a valid hash for html form select element, combined of all entities
# for the given +model+, where only id and name attributes are taken as
# values and keys correspondingly. Provide block returning boolean if you
# need to select only specific entities.
#
# * *Args* :
# - +model+ -> ORM interface for specific entities'
# - +&cond+ -> block {|x| boolean}, filtering entities upon iterations
# * *Returns* :
# - hash of {entity.id => entity.name}
#
def make_select_list( model, &cond )
cond ||= proc { true } # cond defaults to proc { true }
# Entities filtered by cond, followed by filtration by (id, name)
model.all.map do |x|
cond.( x ) ? { x.id => x.name } : {}
end.reduce Hash.new do |memo, e| memo.merge( e ) end
end
Afterwerds, you can call this function like this:
@contests = make_select_list Contest do |contest|
logged_admin? or contest.organizer == @current_user
end
If you don't need to filter your selection, you simply omit the block:
@categories = make_select_list( Category ) # selects all categories
So much for the power of Ruby blocks.
Oracle 12c Installation failed to access the temporary location
The error is caused due to administrative shares are being disabled. If they cannot be enabled then perform the following workaround:
6.2.23 INS-30131 Error When Installing Oracle Database or Oracle Client
If the administrative shares are not enabled when performing a single
instance Oracle Database or Oracle Client installation for 12c Release
1 (12.1) on Microsoft Windows 7, Microsoft Windows 8, and Microsoft
Windows 10, then the installation fails with an INS-30131
error.
Workaround:
Execute the net share
command to ensure that the administrative
shares are enabled. If they are disabled, then enable them by
following the instructions in the Microsoft Windows documentation.
Alternatively, perform the client or server installation by specifying
the following options:
For a client installation:
-ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"
For a server installation:
-ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false"
This issue is tracked with Oracle bug 21452473.
Source: Oracle Database Release Notes (Section 6.2.23)
How to get browser width using JavaScript code?
Update for 2017
My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
_x000D_
_x000D_
function getWidth() {_x000D_
return Math.max(_x000D_
document.body.scrollWidth,_x000D_
document.documentElement.scrollWidth,_x000D_
document.body.offsetWidth,_x000D_
document.documentElement.offsetWidth,_x000D_
document.documentElement.clientWidth_x000D_
);_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
return Math.max(_x000D_
document.body.scrollHeight,_x000D_
document.documentElement.scrollHeight,_x000D_
document.body.offsetHeight,_x000D_
document.documentElement.offsetHeight,_x000D_
document.documentElement.clientHeight_x000D_
);_x000D_
}_x000D_
_x000D_
console.log('Width: ' + getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
_x000D_
_x000D_
Original Answer
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
and similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
Call both of these in your scripts using getWidth()
or getHeight()
. If none of the browser's native properties are defined, it will return undefined
.
Static Vs. Dynamic Binding in Java
Connecting a method call to the method body is known as Binding. As Maulik said "Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding." So this code :
public class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); // prints >> dog is eating...
}
@Override
void eat() {
System.out.println("dog is eating...");
}
}
Will produce the result: dog is eating... because it is using the object reference to find which method to use. If we change the above code to this:
class Animal {
static void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); // prints >> animal is eating...
}
static void eat() {
System.out.println("dog is eating...");
}
}
It will produce : animal is eating... because it is a static method, so it is using Type (in this case Animal) to resolve which static method to call. Beside static methods private and final methods use the same approach.
How to add link to flash banner
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
Git push rejected after feature branch rebase
The following works for me:
git push -f origin branch_name
and it does not remove any of my code.
But, if you want to avoid this then you can do the following:
git checkout master
git pull --rebase
git checkout -b new_branch_name
then you can cherry-pick all your commits to the new branch.
git cherry-pick COMMIT ID
and then push your new branch.
Spring 3 RequestMapping: Get path value
Just found that issue corresponding to my problem. Using HandlerMapping constants I was able to wrote a small utility for that purpose:
/**
* Extract path from a controller mapping. /controllerUrl/** => return matched **
* @param request incoming request.
* @return extracted path
*/
public static String extractPathFromPattern(final HttpServletRequest request){
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
return finalPath;
}
How do I enable index downloads in Eclipse for Maven dependency search?
Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories
, and it should work.
The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.
Click through div to underlying elements
Nope, you can't click ‘through’ an element. You can get the co-ordinates of the click and try to work out what element was underneath the clicked element, but this is really tedious for browsers that don't have document.elementFromPoint
. Then you still have to emulate the default action of clicking, which isn't necessarily trivial depending on what elements you have under there.
Since you've got a fully-transparent window area, you'll probably be better off implementing it as separate border elements around the outside, leaving the centre area free of obstruction so you can really just click straight through.
Generate signed apk android studio
- Go to Build -> Generate Signed APK in Android Studio.
- In the new window appeared, click on Create new... button.
- Next enter details as like shown below and click OK -> Next.
- Select the Build Type as release and click Finish button.
- Wait until APK generated successfully message is displayed as like shown below.
- Click on Show in Explorer to see the signed APK file.
For more details go to this link.
How do you determine the ideal buffer size when using FileInputStream?
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
How to store the hostname in a variable in a .bat file?
I usually read command output in to variables using the FOR
command as it saves having to create temporary files. For example:
FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i
Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the %
in the FOR
statement by putting them twice:
FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%
There's a lot more you can do with FOR
. For more details just type HELP FOR
at command prompt.
CSS "color" vs. "font-color"
I know this is an old post but as MisterZimbu stated, the color
property is defining the values of other properties, as the border-color
and, with CSS3, of currentColor
.
currentColor
is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).
Example:
_x000D_
_x000D_
.element {_x000D_
color: green;_x000D_
background: red;_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
border: solid 10px;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
background: currentColor;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
<div class="innerElement1"></div>_x000D_
<div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How does createOrReplaceTempView work in Spark?
CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.
first we read data in csv format and then convert to data frame and create a temp view
Reading data in csv format
val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")
printing the schema
data.printSchema
data.createOrReplaceTempView("Data")
Now we can run sql queries on top the table view we just created
%sql select Week as Date,Campaign Type,Engagements,Country from Data order by Date asc
Safest way to convert float to integer in python?
You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.
IDLE output.
>>> round(2.99999999999)
3
>>> round(2.6)
3
>>> round(2.5)
3
>>> round(2.4)
2
jQuery $(".class").click(); - multiple elements, click event once
I just had the same problem.
In my case PHP code generated few times the same jQuery code and that was the multiple trigger.
<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zglos</a>
(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)
<script type="text/javascript">
$('.report').click(function(){...});
</script>
My solution was to separate script in another php file and load that file ONE TIME.
How do I convert a String to an InputStream in Java?
Like this:
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.
For versions of Java less than 7, replace StandardCharsets.UTF_8
with "UTF-8"
.
How to find and replace with regex in excel
Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.
To answer your question:
- Copy the data from Excel and paste into Google Sheets
- Use the find and replace dialog with regex
- Copy the data from Google Sheets and paste back into Excel
How do you implement a class in C?
GTK is built entirely on C and it uses many OOP concepts. I have read through the source code of GTK and it is pretty impressive, and definitely easier to read. The basic concept is that each "class" is simply a struct, and associated static functions. The static functions all accept the "instance" struct as a parameter, do whatever then need, and return results if necessary. For Example, you may have a function "GetPosition(CircleStruct obj)". The function would simply dig through the struct, extract the position numbers, probably build a new PositionStruct object, stick the x and y in the new PositionStruct, and return it. GTK even implements inheritance this way by embedding structs inside structs. pretty clever.
Stop setInterval
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
iPhone Debugging: How to resolve 'failed to get the task for process'?
If you are getting such error, the only reason could be you using a Distribution profile rather than a development profile in Xcode or a missing Entitlement property. If you are not using the Entitlements.plist, then the only possible error could be the app is getting packaged with a distribution profile. You could verify this confirming the build logs. To change this, go to Build Setting of the project and verify Code Signing Entity setting. For debugging to work, this setting should be a developer profile for the configuration that you are currently using.
https://developer.apple.com/library/ios/#qa/qa1682/_index.html
For instant results, delete all mobile provisioning profiles from xcode and install the developer profile that you intend to use.
Populating Spring @Value during Unit Test
In springboot 2.4.1 im just added annotation @SpringBootTest
in my test, and obviously, setted spring.profiles.active = test
in my src/test/resources/application.yml
Im using @ExtendWith({SpringExtension.class})
and @ContextConfiguration(classes = {RabbitMQ.class, GenericMapToObject.class, ModelMapper.class, StringUtils.class})
for external confs
Angular ng-click with call to a controller function not working
Use alias when defining Controller in your angular configuration. For example:
NOTE: I'm using TypeScript here
Just take note of the Controller, it has an alias of homeCtrl.
module MongoAngular {
var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);
app.config([
'$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
$routeProvider
.when('/Home', {
templateUrl: '/PartialViews/Home/home.html',
controller: 'HomeController as homeCtrl'
})
.otherwise({ redirectTo: '/Home' });
}])
.config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
restangularProvider.setBaseUrl('/api');
}]);
}
And here's the way to use it...
ng-click="homeCtrl.addCustomer(customer)"
Try it.. It might work for you as it worked for me... ;)
What is a typedef enum in Objective-C?
Apple recommends defining enums like this since Xcode 4.4:
typedef enum ShapeType : NSUInteger {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
They also provide a handy macro NS_ENUM
:
typedef NS_ENUM(NSUInteger, ShapeType) {
kCircle,
kRectangle,
kOblateSpheroid
};
These definitions provide stronger type checking and better code completion. I could not find official documentation of NS_ENUM
, but you can watch the "Modern Objective-C" video from WWDC 2012 session here.
UPDATE
Link to official documentation here.
Triggering change detection manually in Angular
I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:
Import NgZone
:
import { Component, NgZone } from '@angular/core';
Add it to your class constructor
constructor(public zone: NgZone, ...args){}
Run code with zone.run
:
this.zone.run(() => this.donations = donations)
Get user profile picture by Id
Through the Javascript SDK (v2.12 - April, 2017) you can get the details of the picture request this way:
FB.api("/" + uid + "/picture?redirect=0", function (response) {
console.log(response);
// prints the following:
//data: {
// height: 50
// is_silhouette: false
// url: "https://lookaside.facebook.com/platform/profilepic/?asid=…&height=50&width=50&ext=…&hash…"
// width: 50
//}
if (response && !response.error) {
// change the src attribute of img elements
[...document.getElementsByClassName('fb-user-img')].forEach(
i => i.src = response.data.url
);
// OR redirect to the URL above
location.assign(response.data.url);
}
});
For getting the JSON response the parameter redirect
with 0 (zero) as value is important since the request redirects to the image by default. You may still add other parameters in the same URL. Examples:
"/" + uid + "/picture?redirect=0&width=100&height=100"
: a 100x100 image will be returned;
"/" + uid + "/picture?redirect=0&type=large"
: a 200x200 image is returned. Other possible type values include: small, normal, album, and square.
"psql: could not connect to server: Connection refused" Error when connecting to remote database
I have struggled with this when trying to remotely connect to a new PostgreSQL installation on my Raspberry Pi. Here's the full breakdown of what I did to resolve this issue:
First, open the PostgreSQL configuration file and make sure that the service is going to listen outside of localhost.
sudo [editor] /etc/postgresql/[version]/main/postgresql.conf
I used nano
, but you can use the editor of your choice, and while I have version 9.1
installed, that directory will be for whichever version you have installed.
Search down to the section titled 'Connections and Authentication'. The first setting should be 'listen_addresses'
, and might look like this:
#listen_addresses = 'localhost' # what IP address(es) to listen on;
The comments to the right give good instructions on how to change this field, and using the suggested '*'
for all will work well.
Please note that this field is commented out with #. Per the comments, it will default to 'localhost', so just changing the value to '*'
isn't enough, you also need to uncomment the setting by removing the leading #
.
It should now look like this:
listen_addresses = '*' # what IP address(es) to listen on;
You can also check the next setting, 'port', to make sure that you're connecting correctly. 5432 is the default, and is the port that psql will try to connect to if you don't specify one.
Save and close the file, then open the Client Authentication config file, which is in the same directory:
sudo [editor] /etc/postgresql/[version]/main/pg_hba.conf
I recommend reading the file if you want to restrict access, but for basic open connections you'll jump to the bottom of the file and add a line like this:
host all all all md5
You can press tab instead of space to line the fields up with the existing columns if you like.
Personally, I instead added a row that looked like this:
host [database_name] pi 192.168.1.0/24 md5
This restricts the connection to just the one user and just the one database on the local area network subnet.
Once you've saved changes to the file you will need to restart the service to implement the changes.
sudo service postgresql restart
Now you can check to make sure that the service is openly listening on the correct port by using the following command:
sudo netstat -ltpn
If you don't run it as elevated (using sudo
) it doesn't tell you the names of the processes listening on those ports.
One of the processes should be Postgres, and the Local Address should be open (0.0.0.0) and not restricted to local traffic only (127.0.0.1). If it isn't open, then you'll need to double check your config files and restart the service. You can again confirm that the service is listening on the correct port (default is 5432
, but your configuration could be different).
Finally you'll be able to successfully connect from a remote computer using the command:
psql -h [server ip address] -p [port number, optional if 5432] -U [postgres user name] [database name]
Microsoft Advertising SDK doesn't deliverer ads
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
- Remove the XAML for the ad
- Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
- Remove the bad DLL (the one ending in .SDK )
- Do a Clean and then Build (clean out anything remaining from the DLL)
- Add the xmlns reference (actual reference is below)
- Add the ad to the page (example below)
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Converting a list to a set changes element order
You can remove the duplicated values and keep the list order of insertion with one line of code, Python 3.8.2
mylist = ['b', 'b', 'a', 'd', 'd', 'c']
results = list({value:"" for value in mylist})
print(results)
>>> ['b', 'a', 'd', 'c']
results = list(dict.fromkeys(mylist))
print(results)
>>> ['b', 'a', 'd', 'c']
How to sort multidimensional array by column?
You can use list.sort
with its optional key
parameter and a lambda
expression:
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
This will sort the list in-place.
Note that for large lists, it will be faster to use operator.itemgetter
instead of a lambda
:
>>> from operator import itemgetter
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
PHP: Show yes/no confirmation dialog
You can handle the attribute onClick for both i.e. 'ok' & 'cancel' condition like ternary operator
Scenario:
Here is the scenario that I wants to show confirm box which will ask for 'ok' or 'cancel' while performing a delete action. In that I want if user click on 'ok' then the form action will redirect to page location and on cancel page will not respond.
Adding further explanation i'm having one button with type="submit" which is originally use default form action of form tag. and I want above scenario on delete button with same input type.
So below code is working properly for me
onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;"
Full code
<input type="submit" name="action" id="Delete" value="Delete" onClick="return confirm('Are you sure you want to Delete ?')?this.form.action='<?php echo $_SERVER['PHP_SELF'] ?>':false;">
And by the way I'm implementing this code as inline in html element using PHP. so that's why I used 'echo $_SERVER['PHP_SELF']'.
I hope it will work for you also.
Thank You
canvas.toDataURL() SecurityError
Unless google serves this image with the correct Access-Control-Allow-Origin
header, then you wont be able to use their image in canvas. This is due to not having CORS
approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
java.io.FileNotFoundException: the system cannot find the file specified
Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
File myFile = new File("word.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
}
}
This code should print the folder where it is looking for. Place the file there and you'll be good to go.
go get results in 'terminal prompts disabled' error for github private repo
If you just want go get
to work real fast, and move along with your work...
Just export GIT_TERMINAL_PROMPT=1
$ export GIT_TERMINAL_PROMPT=1
$ go get [whatever]
It will now prompt you for a user/pass for the rest of your shell session. Put this in your .profile
or setup git
as above for a more permanent solution.
SQL conditional SELECT
In SQL
, you do it this way:
SELECT CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM Table
Relational model does not imply dynamic field count.
Instead, if you are not interested in a field value, you just select a NULL
instead and parse it on the client.
How to get file path in iPhone app
If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);
How do I fix MSB3073 error in my post-build event?
Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.
PHP compare two arrays and get the matched values not the difference
I think the better answer for this questions is
array_diff()
because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.
Whereas
array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.
How to use Java property files?
Here is another way to iterate over the properties:
Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) {
String key = (String) eProps.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
How to sort a file in-place
The sort
command prints the result of the sorting operation to standard output by default. In order to achieve an "in-place" sort, you can do this:
sort -o file file
This overwrites the input file
with the sorted output. The -o
switch, used to specify an output, is defined by POSIX, so should be available on all version of sort
:
-o Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.
If you are unfortunate enough to have a version of sort
without the -o
switch (Luis assures me that they exist), you can achieve an "in-place" edit in the standard way:
sort file > tmp && mv tmp file
JavaScript: get code to run every minute
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
Is it possible to have multiple styles inside a TextView?
The list of supported tags is:
If you use a string resource, you can add some simple styling, such as bold or italic using HTML notation. The currently supported tags are: B
(bold), I
(italic), U
(underline), TT
(monospace), BIG
, SMALL
, SUP
(superscript), SUB
(subscript), and STRIKE
(strikethrough). So, for example, in res/values/strings.xml
you could declare this:
<resource>
<string id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>
(From http://developer.android.com/guide/faq/commontasks.html#selectingtext — Web Archive link, <resource>
typo is in original!)
It also shows that Html.fromHtml
isn't really needed in simple cases.
PHP String to Float
If you need to handle values that cannot be converted separately, you can use this method:
try {
$valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
// bail here if you need to
}
Using regular expression in css?
You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:
#sections div[id^='s'] {
color: red;
}
That says select any div elements inside the #sections div that have an ID starting with the letter 's'.
See fiddle here.
W3 CSS selector docs here.
Microsoft Azure: How to create sub directory in a blob container
Wanted to add the UI portal Way to do as well.
In case you want to create the folder structure, you would have to do it with the complete path for each file.
You need to Click on Upload Blob, Expand the Advanced and put it the path saying "Upload to Folder"
So Lets say you have a folder assets you want to upload and the content of the folder look like below
And if you have a folder under js folder with name main.js, you need to type in the path "assets/js" in upload to folder.
Now This has to be done for each file. In case you have a lot of file, its recommended you do it programmatically.
Replace words in a string - Ruby
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
How to call webmethod in Asp.net C#
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
how to get the last part of a string before a certain character?
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
Following code is the simple example to change the timezone
public static void main(String[] args) {
//get time zone
TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
Calendar calendar = new GregorianCalendar();
//setting required timeZone
calendar.setTimeZone(timeZone1);
System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));
}
if you want see the list of timezones, here is the follwing code
public static void main(String[] args) {
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
}
System.out.println("\nTotal TimeZone ID " + ids.length);
}
private static String displayTimeZone(TimeZone tz) {
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
- TimeUnit.HOURS.toMinutes(hours);
// avoid -4:-30 issue
minutes = Math.abs(minutes);
String result = "";
if (hours > 0) {
result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
} else {
result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
}
return result;
}
What does the DOCKER_HOST variable do?
It points to the docker host! I followed these steps:
$ boot2docker start
Waiting for VM and Docker daemon to start...
..............................
Started.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp://192.168.59.103:2375
$ export DOCKER_HOST=tcp://192.168.59.103:2375
$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete
511136ea3c5a: Download complete
97fd97495e49: Download complete
2dcbbf65536c: Download complete
6a459d727ebb: Download complete
8f321fc43180: Download complete
03db2b23cf03: Download complete
Hello world
See:
http://docs.docker.com/userguide/dockerizing/
ListBox with ItemTemplate (and ScrollBar!)
Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)
-pom-
Best way to list files in Java, sorted by Date Modified?
Imports :
org.apache.commons.io.comparator.LastModifiedFileComparator
Apache Commons
Code :
public static void main(String[] args) throws IOException {
File directory = new File(".");
// get just files, not directories
File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);
System.out.println("Default order");
displayFiles(files);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
System.out.println("\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)");
displayFiles(files);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
System.out.println("\nLast Modified Descending Order (LASTMODIFIED_REVERSE)");
displayFiles(files);
}
How to highlight cell if value duplicate in same column for google spreadsheet?
Try this:
- Select the whole column
- Click Format
- Click Conditional formatting
- Click Add another rule (or edit the existing/default one)
- Set Format cells if to:
Custom formula is
- Set value to:
=countif(A:A,A1)>1
(or change A
to your chosen column)
- Set the formatting style.
- Ensure the range applies to your column (e.g.,
A1:A100
).
- Click Done
Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
Passing parameter to controller from route in laravel
You don't need anything special for adding paramaters. Just like you had it.
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}
Set min-width either by content or 200px (whichever is greater) together with max-width
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
_x000D_
_x000D_
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
json_encode is returning NULL?
few day ago I have the SAME problem with 1 table.
Firstly try:
echo json_encode($rows);
echo json_last_error(); // returns 5 ?
If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.
Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.
You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...
Is there a constraint that restricts my generic method to numeric types?
C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:
And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a Matrix<T>
, for example, and in that Matrix
you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply two T
s, but you can't say that as a constraint, at least not if T
is int
, double
, or float
. But what you could do is have your Matrix
take as an argument a Calculator<T>
, and in Calculator<T>
, have a method called multiply
. You go implement that and you pass it to the Matrix
.
However, this leads to fairly convoluted code, where the user has to supply their own Calculator<T>
implementation, for each T
that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as int
and double
, you can get away with a relatively simple interface:
var mat = new Matrix<int>(w, h);
(Minimal implementation in a GitHub Gist.)
However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own Calculator
instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, DFP
, you’d have to write this code:
var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);
… and implement all the members for DfpCalculator : ICalculator<DFP>
.
An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.
When to use throws in a Java method declaration?
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws
is
unnecesary.
Remove the try/catch
; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
Use tab to indent in textarea
var textareas = document.getElementsByTagName('textarea');
var count = textareas.length;
for(var i=0;i<count;i++){
textareas[i].onkeydown = function(e){
if(e.keyCode==9 || e.which==9){
e.preventDefault();
var s = this.selectionStart;
this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
this.selectionEnd = s+1;
}
}
}
This solution does not require jQuery and will enable tab functionality on all textareas on a page.
WaitAll vs WhenAll
As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll()
then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll()
then the UI thread is not blocked, and the UI will be updated.
How to copy a dictionary and only edit the copy
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1
There are many ways to copy Dict object, I simply use
dict_1 = {
'a':1,
'b':2
}
dict_2 = {}
dict_2.update(dict_1)
Please initialize the log4j system properly warning
Add the code
BasicConfigurator.configure();
in your static main class as below..
Note:
add " \hadoop-2.7.1\share\hadoop\common\lib\commons-logging-1.1.3.jar &
\hadoop-2.7.1\share\hadoop\common\lib\log4j-1.2.17.jar "
as the external references
import org.apache.log4j.BasicConfigurator;
public class ViewCountDriver extends Configured implements Tool{
public static void main(String[]args) throws Exception{
BasicConfigurator.configure();
int exitcode = ToolRunner.run(new ViewCountDriver(), args);
System.exit(exitcode);
}
}
Counting no of rows returned by a select query
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
VBA - Run Time Error 1004 'Application Defined or Object Defined Error'
Solution #1:
Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
python pip on Windows - command 'cl.exe' failed
If you want it really easy and a joy to automate, check out Chocolatey.org/install and you can basically copy and paste these commands and tweak it based on what versions of VC++ you need.
This command is taken from https://chocolatey.org/install
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Once you have chocolatey installed you can either close and reopen your Powershell terminal or run this command:
Import-Module "$env:ChocolateyInstall\helpers\chocolateyInstaller.psm1" ; Update-SessionEnvironment
Now you can use Chocolatey to install Python (latest version of 3.x is default).
choco install python
# This next command installs the latest VisualStudio installer that lets you get specific versions of the build
# Microsoft has replaced the 2015 and 2017 installer links with this one, and we can still use it to install the 2015 and 2017 components
choco install visualstudio2019buildtools --package-parameters "--add Microsoft.VisualStudio.Component.VC.140 --passive --locale en-US --add Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build) --no-includeRecommended" -y --timeout 0
# Usually need the "unlimited" timeout aka "0" because Visual Studio Installer takes forever
# Tool portion
# Microsoft.VisualStudio.Product.BuildTools
# Component portion(s)
# Microsoft.VisualStudio.Component.VC.140
# Win10SDK needs to match your current Win10 build version
# $($PSVersionTable.BuildVersion.Build)
# Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build)
# Because VS2019 Build Tools are dumb, need to manually link a couple files between the SDK and the VC++ dirs
# You may need to tweak the version here, but it has been updated to be as dynamic as possible
# Use an elevated Powershell or elevated cmd prompt (if using cmd.exe just use the bits after /c)
cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rc.exe" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rc.exe"
cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rcdll.dll" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rcdll.dll"
Once you have this installed, you should reboot. I've occasionally had things work without a reboot, but your pip install
commands will work best if you reboot first.
Now you can pip install pipenv
or pip install complex-package
and should be good to go.
<embed> vs. <object>
Some other options:
<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>
<object type="application/pdf" data="#request.localhost#_includes/filename.pdf"
width="100%" height="100%">
<param name="src" value="#request.localhost#_includes/filename.pdf">
</object>
Delete empty lines using sed
Another option without sed
, awk
, perl
, etc
strings $file > $output
strings - print the strings of printable characters in files.
What is the difference between Python and IPython?
Even after viewing this thread, I had thought that ipython was a synonym for the python shell, in other words that typing python at the command line put one into ipython mode.
It is in fact, as referenced above, a very cool interactive shell (command line program) that can be installed from iPython.org or simply by running
pip install ipython
or the more extensive:
pip install ipython[notebook]
from the command line.
What's the difference between struct and class in .NET?
Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.
Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.
The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.
PHPExcel how to set cell value dynamically
I asume you have connected to your database already.
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
$col = 0;
foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
bind/unbind service example (android)
Add these methods to your Activity:
private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
myServiceBinder = ((MyService.MyBinder) binder).getService();
Log.d("ServiceConnection","connected");
showServiceData();
}
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
};
public Handler myHandler = new Handler() {
public void handleMessage(Message message) {
Bundle data = message.getData();
}
};
public void doBindService() {
Intent intent = null;
intent = new Intent(this, BTService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
Messenger messenger = new Messenger(myHandler);
intent.putExtra("MESSENGER", messenger);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (myService == null) {
doBindService();
}
super.onResume();
}
@Override
protected void onPause() {
//FIXME put back
Log.d("activity", "onPause");
if (myService != null) {
unbindService(myConnection);
myService = null;
}
super.onPause();
}
Note, that when binding to a service only the onCreate()
method is called in the service class.
In your Service class you need to define the myBinder method:
private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;
@Override
public IBinder onBind(Intent arg0) {
Bundle extras = arg0.getExtras();
Log.d("service","onBind");
// Get messager from the Activity
if (extras != null) {
Log.d("service","onBind with extra");
outMessenger = (Messenger) extras.get("MESSENGER");
}
return mBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
After you defined these methods you can reach the methods of your service at your Activity:
private void showServiceData() {
myServiceBinder.myMethod();
}
and finally you can start your service when some event occurs like _BOOT_COMPLETED_
public class MyReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, myService.class);
context.startService(service);
}
}
}
note that when starting a service the onCreate()
and onStartCommand()
is called in service class
and you can stop your service when another event occurs by stopService()
note that your event listener should be registerd in your Android manifest file:
<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Using jquery to get element's position relative to viewport
I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset)
didn't trigger if the client had scrolled right, but not down - because 0
is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft
/Top
, but this is no longer working for me (on Firefox 26.0).
Here's my modified solution:
var getPageScroll = function(document_el, window_el) {
var xScroll = 0, yScroll = 0;
if (window_el.pageYOffset !== undefined) {
yScroll = window_el.pageYOffset;
xScroll = window_el.pageXOffset;
} else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
yScroll = document_el.documentElement.scrollTop;
xScroll = document_el.documentElement.scrollLeft;
} else if (document_el.body !== undefined) {// all other Explorers
yScroll = document_el.body.scrollTop;
xScroll = document_el.body.scrollLeft;
}
return [xScroll,yScroll];
};
Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.
Import Excel to Datagridview
try this following snippet, its working fine.
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openfile1.FileName;
}
{
string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
OleDbConnection conn = new OleDbConnection(pathconn);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
MyDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch { }
}
How do I capture response of form.submit
You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit()
function doesn't actually return anything, it just sends the form data to the server.
If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.
Here's how you'd use jQuery and that plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
How can I multiply and divide using only bit shifting and adding?
Try this. https://gist.github.com/swguru/5219592
import sys
# implement divide operation without using built-in divide operator
def divAndMod_slow(y,x, debug=0):
r = 0
while y >= x:
r += 1
y -= x
return r,y
# implement divide operation without using built-in divide operator
def divAndMod(y,x, debug=0):
## find the highest position of positive bit of the ratio
pos = -1
while y >= x:
pos += 1
x <<= 1
x >>= 1
if debug: print "y=%d, x=%d, pos=%d" % (y,x,pos)
if pos == -1:
return 0, y
r = 0
while pos >= 0:
if y >= x:
r += (1 << pos)
y -= x
if debug: print "y=%d, x=%d, r=%d, pos=%d" % (y,x,r,pos)
x >>= 1
pos -= 1
return r, y
if __name__ =="__main__":
if len(sys.argv) == 3:
y = int(sys.argv[1])
x = int(sys.argv[2])
else:
y = 313271356
x = 7
print "=== Slow Version ...."
res = divAndMod_slow( y, x)
print "%d = %d * %d + %d" % (y, x, res[0], res[1])
print "=== Fast Version ...."
res = divAndMod( y, x, debug=1)
print "%d = %d * %d + %d" % (y, x, res[0], res[1])
VirtualBox: mount.vboxsf: mounting failed with the error: No such device
In addition to @Mats answer, I'm adding some more info (it helped me on Debian 8).
My shared folder/clipboard stopped to work for some reason (probably due to a patch installation on my virtual machine).
sudo mount -t vboxsf Shared_Folder ~/SF/
Gave me following result:
VirtualBox: mount.vboxsf: mounting failed with the error: No such device
The solution for me was to stop vboxadd and do a setup after that:
cd /opt/VBoxGuestAdditions-*/init
sudo ./vboxadd setup
At this point, if you still get the following error:
No such device. The Guest Additions installation may have failed. The error has been logged in /var/log/vboxadd-install.log
You need to install linux headers:
apt-get install linux-headers-$(uname -r)
then you can install Guest Additions:
sh /media/cdrom/VBoxLinuxAdditions.run --nox11
and restart your Linux by:
reboot
then you will be able to mount your shared folder!
mount -t vboxsf Shared_Folder ~/SF/
More informations (in French), check this page.
Find by key deep in a nested array
We use object-scan for our data processing. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your specific question
_x000D_
_x000D_
// const objectScan = require('object-scan');
const find = (id, input) => objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.id === id
})(input);
const data = [{ title: 'some title', channel_id: '123we', options: [{ channel_id: 'abc', image: 'http://asdasd.com/all-inclusive-block-img.jpg', title: 'All-Inclusive', options: [{ channel_id: 'dsa2', title: 'Some Recommends', options: [{ image: 'http://www.asdasd.com', title: 'Sandals', id: '1', content: {} }] }] }] }];
console.log(find('1', data));
// => { image: 'http://www.asdasd.com', title: 'Sandals', id: '1', content: {} }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_
Disclaimer: I'm the author of object-scan
How to style input and submit button with CSS?
http://jsfiddle.net/vfUvZ/
Here's a starting point
CSS:
input[type=text] {
padding:5px;
border:2px solid #ccc;
-webkit-border-radius: 5px;
border-radius: 5px;
}
input[type=text]:focus {
border-color:#333;
}
input[type=submit] {
padding:5px 15px;
background:#ccc;
border:0 none;
cursor:pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
}
How do I include a Perl module that's in a different directory?
From perlfaq8:
How do I add the directory my program lives in to the module/library search path?
(contributed by brian d foy)
If you know the directory already, you can add it to @INC as you would for any other directory. You might use lib if you know the directory at compile time:
use lib $directory;
The trick in this task is to find the directory. Before your script does anything else (such as a chdir), you can get the current working directory with the Cwd module, which comes with Perl:
BEGIN {
use Cwd;
our $directory = cwd;
}
use lib $directory;
You can do a similar thing with the value of $0, which holds the script name. That might hold a relative path, but rel2abs can turn it into an absolute path. Once you have the
BEGIN {
use File::Spec::Functions qw(rel2abs);
use File::Basename qw(dirname);
my $path = rel2abs( $0 );
our $directory = dirname( $path );
}
use lib $directory;
The FindBin module, which comes with Perl, might work. It finds the directory of the currently running script and puts it in $Bin, which you can then use to construct the right library path:
use FindBin qw($Bin);
IIS_IUSRS and IUSR permissions in IIS8
I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).
Specific User setting is specifically meant for accessing local resources.
Python: print a generator expression?
Quick answer:
Doing list()
around a generator expression is (almost) exactly equivalent to having []
brackets around it. So yeah, you can do
>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))
But you can just as well do
>>> [x for x in string.letters if x in (y for y in "BigMan on campus")]
Yes, that will turn the generator expression into a list comprehension. It's the same thing and calling list() on it. So the way to make a generator expression into a list is to put brackets around it.
Detailed explanation:
A generator expression is a "naked" for
expression. Like so:
x*x for x in range(10)
Now, you can't stick that on a line by itself, you'll get a syntax error. But you can put parenthesis around it.
>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7485464>
This is sometimes called a generator comprehension, although I think the official name still is generator expression, there isn't really any difference, the parenthesis are only there to make the syntax valid. You do not need them if you are passing it in as the only parameter to a function for example:
>>> sorted(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Basically all the other comprehensions available in Python 3 and Python 2.7 is just syntactic sugar around a generator expression. Set comprehensions:
>>> {x*x for x in range(10)}
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> set(x*x for x in range(10))
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
Dict comprehensions:
>>> dict((x, x*x) for x in range(10))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {x: x*x for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
And list comprehensions under Python 3:
>>> list(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Under Python 2, list comprehensions is not just syntactic sugar. But the only difference is that x will under Python 2 leak into the namespace.
>>> x
9
While under Python 3 you'll get
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
This means that the best way to get a nice printout of the content of your generator expression in Python is to make a list comprehension out of it! However, this will obviously not work if you already have a generator object. Doing that will just make a list of one generator:
>>> foo = (x*x for x in range(10))
>>> [foo]
[<generator object <genexpr> at 0xb7559504>]
In that case you will need to call list()
:
>>> list(foo)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Although this works, but is kinda stupid:
>>> [x for x in foo]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
How to set time to a date object in java
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
oracle - what statements need to be committed?
DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.
Data Manipulation Language (DML) statements are used for managing data
within schema objects. Some examples:
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
jquery click event not firing?
Is this markup added to the DOM asynchronously? You will need to use live
in that case:
NOTE: .live
has been deprecated and removed in the latest versions of jQuery (for good reason). Please refer to the event delegation strategy below for usage and solution.
<script>
$(document).ready(function(){
$('.play_navigation a').live('click', function(){
console.log("this is the click");
return false;
});
});
</script>
The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live
(or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.
Using jQuery 1.7 event delegation:
$(function () {
$('.play_navigation').on('click', 'a', function (e) {
console.log('this is the click');
e.preventDefault();
});
});
You can also delegate events up to the document if you feel that you would like to bind the event before the document is ready (note that this also causes jQuery to examine every click event to determine if the element matches the appropriate selector):
$(document).on('click', '.play_navigation a', function (e) {
console.log('this is the click');
e.preventDefault();
});
What is the fastest way to transpose a matrix in C++?
This is a good question. There are many reason you would want to actually transpose the matrix in memory rather than just swap coordinates, e.g. in matrix multiplication and Gaussian smearing.
First let me list one of the functions I use for the transpose (EDIT: please see the end of my answer where I found a much faster solution)
void transpose(float *src, float *dst, const int N, const int M) {
#pragma omp parallel for
for(int n = 0; n<N*M; n++) {
int i = n/N;
int j = n%N;
dst[n] = src[M*j + i];
}
}
Now let's see why the transpose is useful. Consider matrix multiplication C = A*B. We could do it this way.
for(int i=0; i<N; i++) {
for(int j=0; j<K; j++) {
float tmp = 0;
for(int l=0; l<M; l++) {
tmp += A[M*i+l]*B[K*l+j];
}
C[K*i + j] = tmp;
}
}
That way, however, is going to have a lot of cache misses. A much faster solution is to take the transpose of B first
transpose(B);
for(int i=0; i<N; i++) {
for(int j=0; j<K; j++) {
float tmp = 0;
for(int l=0; l<M; l++) {
tmp += A[M*i+l]*B[K*j+l];
}
C[K*i + j] = tmp;
}
}
transpose(B);
Matrix multiplication is O(n^3) and the transpose is O(n^2), so taking the transpose should have a negligible effect on the computation time (for large n
). In matrix multiplication loop tiling is even more effective than taking the transpose but that's much more complicated.
I wish I knew a faster way to do the transpose (Edit: I found a faster solution, see the end of my answer). When Haswell/AVX2 comes out in a few weeks it will have a gather function. I don't know if that will be helpful in this case but I could image gathering a column and writing out a row. Maybe it will make the transpose unnecessary.
For Gaussian smearing what you do is smear horizontally and then smear vertically. But smearing vertically has the cache problem so what you do is
Smear image horizontally
transpose output
Smear output horizontally
transpose output
Here is a paper by Intel explaining that
http://software.intel.com/en-us/articles/iir-gaussian-blur-filter-implementation-using-intel-advanced-vector-extensions
Lastly, what I actually do in matrix multiplication (and in Gaussian smearing) is not take exactly the transpose but take the transpose in widths of a certain vector size (e.g. 4 or 8 for SSE/AVX). Here is the function I use
void reorder_matrix(const float* A, float* B, const int N, const int M, const int vec_size) {
#pragma omp parallel for
for(int n=0; n<M*N; n++) {
int k = vec_size*(n/N/vec_size);
int i = (n/vec_size)%N;
int j = n%vec_size;
B[n] = A[M*i + k + j];
}
}
EDIT:
I tried several function to find the fastest transpose for large matrices. In the end the fastest result is to use loop blocking with block_size=16
(Edit: I found a faster solution using SSE and loop blocking - see below). This code works for any NxM matrix (i.e. the matrix does not have to be square).
inline void transpose_scalar_block(float *A, float *B, const int lda, const int ldb, const int block_size) {
#pragma omp parallel for
for(int i=0; i<block_size; i++) {
for(int j=0; j<block_size; j++) {
B[j*ldb + i] = A[i*lda +j];
}
}
}
inline void transpose_block(float *A, float *B, const int n, const int m, const int lda, const int ldb, const int block_size) {
#pragma omp parallel for
for(int i=0; i<n; i+=block_size) {
for(int j=0; j<m; j+=block_size) {
transpose_scalar_block(&A[i*lda +j], &B[j*ldb + i], lda, ldb, block_size);
}
}
}
The values lda
and ldb
are the width of the matrix. These need to be multiples of the block size. To find the values and allocate the memory for e.g. a 3000x1001 matrix I do something like this
#define ROUND_UP(x, s) (((x)+((s)-1)) & -(s))
const int n = 3000;
const int m = 1001;
int lda = ROUND_UP(m, 16);
int ldb = ROUND_UP(n, 16);
float *A = (float*)_mm_malloc(sizeof(float)*lda*ldb, 64);
float *B = (float*)_mm_malloc(sizeof(float)*lda*ldb, 64);
For 3000x1001 this returns ldb = 3008
and lda = 1008
Edit:
I found an even faster solution using SSE intrinsics:
inline void transpose4x4_SSE(float *A, float *B, const int lda, const int ldb) {
__m128 row1 = _mm_load_ps(&A[0*lda]);
__m128 row2 = _mm_load_ps(&A[1*lda]);
__m128 row3 = _mm_load_ps(&A[2*lda]);
__m128 row4 = _mm_load_ps(&A[3*lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_store_ps(&B[0*ldb], row1);
_mm_store_ps(&B[1*ldb], row2);
_mm_store_ps(&B[2*ldb], row3);
_mm_store_ps(&B[3*ldb], row4);
}
inline void transpose_block_SSE4x4(float *A, float *B, const int n, const int m, const int lda, const int ldb ,const int block_size) {
#pragma omp parallel for
for(int i=0; i<n; i+=block_size) {
for(int j=0; j<m; j+=block_size) {
int max_i2 = i+block_size < n ? i + block_size : n;
int max_j2 = j+block_size < m ? j + block_size : m;
for(int i2=i; i2<max_i2; i2+=4) {
for(int j2=j; j2<max_j2; j2+=4) {
transpose4x4_SSE(&A[i2*lda +j2], &B[j2*ldb + i2], lda, ldb);
}
}
}
}
}
Notepad++ Regular expression find and delete a line
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$
- Enable the checkbox
Bookmark line
- Enable the checkbox
Regular expression
(under Search Mode
)
- Click
Mark All
(this will find the regex and highlights all the lines and bookmark them)
Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
Best way to make WPF ListView/GridView sort on column-header clicking?
I wrote a set of attached properties to automatically sort a GridView
, you can check it out here. It doesn't handle the up/down arrow, but it could easily be added.
<ListView ItemsSource="{Binding Persons}"
IsSynchronizedWithCurrentItem="True"
util:GridViewSort.AutoSort="True">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}"
util:GridViewSort.PropertyName="Name"/>
<GridViewColumn Header="First name"
DisplayMemberBinding="{Binding FirstName}"
util:GridViewSort.PropertyName="FirstName"/>
<GridViewColumn Header="Date of birth"
DisplayMemberBinding="{Binding DateOfBirth}"
util:GridViewSort.PropertyName="DateOfBirth"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
How to get a cross-origin resource sharing (CORS) post request working
This is a summary of what worked for me:
Define a new function (wrapped $.ajax
to simplify):
jQuery.postCORS = function(url, data, func) {
if(func == undefined) func = function(){};
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
xhrFields: { withCredentials: true },
success: function(res) { func(res) },
error: function() {
func({})
}
});
}
Usage:
$.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
if(obj.ok) {
...
}
});
Also works with .done
,.fail
,etc:
$.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
if(obj.ok) {
...
}
}).fail(function(){
alert("Error!");
});
Server side (in this case where example.com is hosted), set these headers (added some sample code in PHP):
header('Access-Control-Allow-Origin: https://not-example.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
$array = array("ok" => $_POST["x"]);
echo json_encode($array);
This is the only way I know to truly POST cross-domain from JS.
JSONP converts the POST into GET which may display sensitive information at server logs.
View JSON file in Browser
For Safari 12 and later, you can try the JSONBeautifier bookmarklet. Also works with other browsers.
I created this because JSON Formatter for Safari stopped working in Safari 12. There are a few new options for Safari 12, but I didn't find an open source one in the App Store, and I do not trust closed source browser extensions.
This can be used as a bookmarklet or the source, json-beautifier.js, can be copied and pasted into the browser console. The code is freely available for review and is less than 100 lines of code including comments. Runs entirely on your device and never sends your data over a network.
Works with local files too.
Parallel.ForEach vs Task.Factory.StartNew
The first is a much better option.
Parallel.ForEach, internally, uses a Partitioner<T>
to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.
The second option will schedule a single Task
per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.
FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.
The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:
Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));
By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.