summary
stringlengths 15
147
| text
stringlengths 1
19.3k
| answer
stringlengths 32
22.6k
| labels
float64 0.33
1
| answer_summary
stringlengths 5
164
|
---|---|---|---|---|
Declaring a globally-visible array in CodeIgniter for routing
|
(Totally new to CodeIgniter and php, not new to programming)
In CodeIgniter, how or where can I declare an array that will be accessible in the router (CI_Router), in my custom controller and in the view loader (CI_Loader)? I want to avoid hard-coding data in the router and specifying the same data more than once (in the router and in the controller and/or view).
(Explanation follows; perhaps there is a better way to do what I'm trying to do.)
I have a site where I publish my freeware apps. The site is all static, but maintaining plain html by hand is a nightmare, so I'm trying to use CodeIgniter to generate the pages dynamically. Apart from a few loose ends like 'welcome' or 'contact info', the bulk of the site consists of highly structured application sections. Each app has the same set of pages: about, download, screenshots, etc. These pages all have the same exact layout and only differ in contents.
My main concern is maintainability and the amount of work that required to add a new app (or a new page for all apps). I see no reason to use multiple controllers (or even multiple views), because the only difference is in data (application identifiers), not in behavior or page layout.
My problem is with routing. I could do something like
$route['app1'] = 'main/apps/app1';
$route['app2'] = 'main/apps/app2';
...or loop over an array of app identifiers, but that seems really bad. When I add an application, I should not have to modify the router, since it's just another identifier added to a list, that will be used to pick page contents from an appropriate file.
What I would like to do instead is (pseudocode):
foreach (app in list_of_apps) {
foreach (app_page in list_of_pages) {
route['app/app_page'] = 'main/index/app/app_page'
}
}
This would take care of all requests for 'app1/download' or 'app2/screenshots', etc. So where can I declare the arrays $list_of_apps and $list_of_pages so that they are visible in the router, in the controller, and later in view as well?
|
This should be a simple regular expressions solution:
// set this to whatever controller/method you want as the index for the app
$route['([^/])'] = 'main/apps/$1';
// this is a sample "subpage" handler
$route['([^/])/(.*)'] = 'main/index/$1/$2';
If all "apps" follow the same URL structure, it shouldn't be too hard to make this very modular.
| 0.888889 |
Using a regular expressions solution
|
Ad layout for programs - Illustrator or InDesign
|
today I'm looking for some advice from folks who have laid out event programs.
In this case, the client (a local nonprofit) has a famous keynote speaker at their event, and have solicited donations from local businesses. Each donation over a certain level = a full page ad in the program for the event. Most of them are "Congratulations to on your anniversary", etc. with a company logo sitting somewhere (the businesses that send in their own camera-ready artwork will just have them dropped into place).
I'm going to be laying each ad out in a template so they look consistent; my question to the GD crowd is, "Should I lay the template out in Illustrator and bring each ad individually in to InDesign or should I create a template page for an ad in InDesign and lay each ad out in InDesign?"
Based on your experience, what are the pros and cons of each approach? Obviously it would be easier to lay each ad out in Illustrator (that's what it's there for) but I lose a certain amount of flexibility once I hit InDesign (the program will ultimately be laid out in InDesign).
|
Either one.
Obviously it would be easier to lay each ad out in Illustrator (that's what it's there for)
Actually, that's not really it's specific purpose. But it does just fine. If you'll be doing any kind of vector work in your ads it may be easier to have such a simple thing all in one doc.
On the other hand, InD does have the better type tools. And templated layout is very straightforward. If you wanted to share styles or colors across the ads (it works in some programs) you could even set them up as a book to make syncing painless.
It all comes down to where you're most comfortable. They are both capable layout environments for simple 1-page pieces. You'll be faster where you know the tool best.
I would avoid saving out the ads as PDF. Since you're controlling the whole scope (program and ads), link directly to the source files and if you have to make updates you can open them directly from the program and updating won't require another PDF export.
| 0.888889 |
How to lay ad in Illustrator?
|
Is the particular skill of singing the melody correctly necessary to be able to play the trumpet?
|
I mean, there are people who can't sing melodies correctly but they are able to play the guitar perfectly. Will such person be able to play the trumpet? When you hit the note on the trumpet do you have to worry about the correctness of the note or trumpet does it for you? I play the guitar, I even sing sometimes but I'm worried, will my musical hearing be good enough for the trumpet? Hope I made myself clear.
|
I have owned a Holton T602 trumpet. I bought it new 20 years ago or so. Very nice sounding trumpet although it needed more frequent cleaning than other brands I played. It originally came with a "Frank Holton 7C" mouthpiece but I have been using all sorts of trumpet mouthpieces on it with no problem. The only thing it wasn't very fond of is very big mouthpieces like Bach 1C and bigger, wich would make the tuning too low. After trying out many many mouthpieces I settled on a Bach 10.5C wich is considered quite small by modern standards (not by older standards), but perfect for me, even though I am a tall guy. No idea about you, mouthpieces are like shoes, they have to fit. For some reason, the general consensus is that bigger(lower number) is better, based on a 1920ties recommendation from Vincent Bach that everyone keeps repeating, but I don't agree with that. I'm sounding better than ever on this small piece and it's less straining also.
| 1 |
a Holton T602 trumpet
|
saving new category programmatically with setPath
|
Now this is the sort of problem I would help others with but I am flummoxed.
I am creating new categories in an import routine, e.g.
$this->magObject = Mage::getModel("catalog/category");
$this->magObject->setName($item["name"]);
$this->magObject->setData("agilityId",$item["id"]);
$this->magObject->setIsActive($this->isActive);
$this->magObject->setIsAnchor($this->isAnchor);
$this->magObject->setPageLayout($this->pageLayout);
$this->magObject->setStoreId(Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID));
//$this->magObject->setPath ("1/2/6") ); //actually got by getting path of specific required parent
$this->magObject->save();
Without the setPath it saves fine, but with the wrong path (obviously). When the setPath is included, nothing happens. I know that there are devious magento elements at work that prevent writing to _entity tables unless certain circumstances are met but I thought I was meeting them . I am already performing the usual
define("ADMIN_STORE_ID",1);
//...
Mage::app();
Mage::setIsDeveloperMode(true);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
at the start but in this instance it just is not working. I have similar scripts on other sites that do work. Only difference with this site is that there are multiple store fronts
3 UK
7 Spanish
5 German
6 French
1 Default Store View
Anyone spot something obvious that I am missing, whilst I still have some hair left?
Oh this is using Magento 1.9.1.1.
|
You are not supposed to set the path. This is calculated based on the parent. Same goes for the level.
Instead you should set the parent id.
So you can do this:
$this->magObject = Mage::getModel("catalog/category");
$this->magObject->setName($item["name"]);
$this->magObject->setData("agilityId",$item["id"]);
$this->magObject->setIsActive($this->isActive);
$this->magObject->setIsAnchor($this->isAnchor);
$this->magObject->setPageLayout($this->pageLayout);
$this->magObject->setStoreId(Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID));
$this->magObject->setParentId(2);
$this->magObject->save();
| 0.666667 |
How to set the path?
|
Why is the 't' in Hash Table(Hashtable) in Java not capitalized
|
Everything in Java seems to follow capitalization rules except for Hashtable.
Hashtable<String, String> ht = new Hashtable<String, String>();
as opposed to
ArrayList<String> a = new ArrayList<String>();
or
HashMap<String,Integer> a = new HashMap<String,Integer>();
Why is this ? Is Hash Table read as just one word (Hashtable) ?
|
Hashtable was created in Java v1. The consistent naming conventions for collections were established later, in Java2, when the other classes were published as part of the brand new Java Collection Framework.
Which btw made Hashtable obsolete, so it should not be used in new code.
Hope that helps.
| 0.666667 |
Hashtable was created in Java v1 when the other classes were published in the brand new Java Collection Framework
|
Where was the Scottish Skyfall scene filmed?
|
I know Scotland very well and have several theories of my own but can anyone tell me where this iconic shot was taken?
Ideally I'm after as accurate a location as possible as I'm fairly sure I can narrow it to one of two valleys (bonus points for a streetview link!)
|
The shot was taken in Glen Etive, Highland, Scotland. The water to the left is the River Etive. I believe this link is the exact spot, but not entirely sure.
Google Maps
| 1 |
Photo taken in Glen Etive, Highland, Scotland
|
How do I make shelf stable legume dishes in vacuum bags?
|
how do I make shelf stable cooked legumes in vacuum sealed bags at home?
|
If you want to shelf store the cooked legumes in plastic, you need to buy boilable pouches
They are a great space saver, and somewhat environmentally friendly as the oil/energy required to make one glass preserving jar can make 50 to 100 of these bags. And how many preserving jars survive 50 times without breaking!
You will find plenty of sources on the Internet, typical prices $50 to $200 per 1000
The process varies from each bag supplier and vacuum system, but is similar to normal home preserving
If you get the foil lined (light proof) pouches they will preserve food for many years
Example suppliers caspak pacrite
This process is popular in NZ and AU, but as I have just discovered, not so in the USA? So it maybe easier to order from here
The energy, weight, and space saving of plastic pouches is significant
| 1 |
How many preserving jars survive 50 times without breaking
|
Is ZIP archive capable of storing permissions?
|
I am using Maven Assembly plugin to bundle my application along with configuration/settings files. It allows to specify persmissions to be stored along with files, which is quite convenient.
Still I never found a confirmation, that ZIP archive is capable of storing UNIX permissions. Is it? (please, post some proof if you answer either yes or no).
|
Yes,
Create you deployment.
Transfer it to another machine.
Deploy the application.
Compare the permissions on the reference machine with the lab machine.
Profit!
| 1 |
Yes, Create you deployment
|
Login users/start session with PDO
|
Im trying to create a login section on my website using PDO.
So far I've the following...
config.php
// Connect to DB
$username = '[email protected]';
$password = 'pass';
try {
$conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
header.php
// DB Config
include '/assets/config.php';
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}
?>
My browser doesn't display the page however, and when I view my source theres no data contained within, can anybody see where im going wrong?
|
try this:
// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
echo $sth->rowCount();
}
make sure you have username "liam" and pass "password" in the database
| 1 |
User Session $login = 'liam'
|
Integrating expressions with several terms and delta functions
|
So I want to integrate an expression that looks something like this:
Integrate[f[x]+DiracDelta[x-y]g[x],{x,-Infinity,Infinity}]
With some more terms added with delta functions after g[x]. Even after expanding and simplifying Mathematica won't break up the expression and evaluate the delta function, it just leaves it in exactly the form I have above. How do I make Mathematica evaluate the integral term by term?
Cheers :)
|
I would try to see if you can use Distribute for this:
Distribute@
Integrate[f[x] + DiracDelta[x - y] g[x], {x, -Infinity, Infinity}]
Unlike Map, Distribute is especially (though not exclusively) intended for use with sums.
| 0.666667 |
Distribute is intended for use with sums
|
How best to handle a popup gaining focus in the middle of the user typing?
|
Often I'll set some process off, then change focus to another program and be typing away in a textbox (for example), when the first thing pops up into view, maybe with a Yes / No box which I'd then accidentally interact with as I'm still typing.
I just accidentally sent a license agreement for something that was downloading & installing, to the printer as it popped up once it had downloaded, while I was typing a url into Chrome. If I didn't quickly cancel it I'd have had to wait while 53 pages printed while I reflected on what had happened.
What can application developers, or the OS itself do to minimize these problems?
|
My view is prevent applications being 'arrogant' and demanding immediate attention. A well mannered application will wait it's time whilst somehow making you aware it's there. On macs this is done by bouncing the application icon. Too many applications assume they have your full and undivided attention when, increasingly, we're bouncing beween multiple applications.
| 0.888889 |
bouncing the application icon on macs
|
tree view properties in web application
|
i open a web application in visual studio 2008...
it contain the tree view properties as,
TreeNodeType type;
type = new TreeNodeType();
type.Type = "folder";
type.ImageUrl = "Images/" + "folder.gif";
type.ExpandedImageUrl = "Images/" + "folderopen.gif";
i dont know how this image tag comes.. and how to chage that...
|
If your image directory is in the root of the application you should use the tilde character '~' at the start:
type.ImageUrl = "~/Images/" + "folder.gif";
you should include the full path to the image from the root, so if the image is in Content/Images:
type.ImageUrl = "~/Content/Images/" + "folder.gif";
At runtime, the '~/' is translated to the correct path to the image and rendered to the page.
If this is not working, you need to post the relevant markup of the page and the codebehind. Alos, it would help if you rightclick the image in IE and slect properties. You can see the expected path there. Or open the page in Firefox, with the Firebug Addon installed, right click the image and select Inspect Element. This will show you the path that was rendered and you can compare this to where the image actually is in your project.
| 0.777778 |
If your image directory is in root, you should include the full path to the image from the root .
|
Is it safe to eat freshwater fish raw?
|
According to this question freshwater fish should not be used in Ceviche--why not?
|
In addition to hobodaves fine answer, freshwater fish usually contains a lot more mercury and other very unhelathy substances caused by human pollution. Some doctors recommend you to only eat freshwater fish twice a month.
| 0.888889 |
Freshwater fish usually contains more mercury and other very unhelathy substances caused by human pollution
|
How to find first element of array matching a boolean condition in JavaScript?
|
I'm wondering if there's a known, built-in/elegant way to find the first element of a JS array matching a given condition. A C# equivalent would be List.Find.
So far I've been using a two-function combo like this:
// Returns the first element of an array that satisfies given predicate
Array.prototype.findFirst = function (predicateCallback) {
if (typeof predicateCallback !== 'function') {
return undefined;
}
for (var i = 0; i < arr.length; i++) {
if (i in this && predicateCallback(this[i])) return this[i];
}
return undefined;
};
// Check if element is not undefined && not null
isNotNullNorUndefined = function (o) {
return (typeof (o) !== 'undefined' && o !== null);
};
And then I can use:
var result = someArray.findFirst(isNotNullNorUndefined);
But since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this? I imagine lots of people have to implement stuff like this all the time...
|
It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:
Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.
Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.
Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.
Both solutions above don't support offset searching either, so I've decided to write this:
(function(ns) {
ns.search = function(array, callback, offset) {
var size = array.length;
offset = offset || 0;
if (offset >= size || offset <= -size) {
return -1;
} else if (offset < 0) {
offset = size - offset;
}
while (offset < size) {
if (callback(array[offset], offset, array)) {
return offset;
}
++offset;
}
return -1;
};
}(this));
search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3
| 0.666667 |
Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient
|
Is it safe to look indirectly at the Sun?
|
I.e., is exposure of sunlight onto the peripheral vision less damaging than exposure onto the fovea?
|
Behar-Cohen et al. notes the periphery of the cornea has a focusing effect:
UVR incident from the periphery is refracted into the eye, and due to the focusing effect of the cornea, UV radiation is on average 22-fold stronger at the nasal limbus, which is the typical site for pterygium and pinguecula. Moreover, UV radiation is on average eight times stronger at the nasal lens cortex, the typical site for cortical cataract.
Authors note this in further papers as peripheral light focusing. Essentially, the light is refracted from the periphery of the cornea into the anterior segment of the eye. By this notion, I'd say indirectly looking at the sun is no less damaging than directly looking at it (given there are no other restrictions, such as special lenses, etc.).
| 1 |
UVR incident from the periphery of the cornea is refracted into the eye
|
Loadkeys gives permission denied for normal user
|
I am trying to perform loadkeys operation. For normal user, I am getting permission denied
error.
the error is as follows.
<tim@testps>~% loadkeys mykeys
Loading /usr/tim/mykeys
Keymap 0: Permission denied
Keymap 1: Permission denied
Keymap 2: Permission denied
KDSKBENT: Operation not permitted
loadkeys: could not deallocate keymap 3
|
You need root capabilities to use loadkeys. It is common to set the setuid permission bit on loadkeys. Setting this bit will cause any processes spawned by executing the loadkeys file to run as the owner of the file (usually root).
For added security, you should change loadkeys's permissions to 750, make a group for it, and add any users that need to use loadkeys to that group.
$ chmod 4750 /bin/loadkeys # setuid, group- and user-only read and execution
$ groupadd loadkeys # you can use any group name
$ chgrp loadkeys /bin/loadkeys
$ gpasswd -a user loadkeys # add user to the group
| 0.777778 |
Setuid permission bit on loadkeys
|
How to configure ssh tunneling with Putty between two RHEL servers?
|
I'm trying to allow ssh access from a remote RHEL server to a local RHEL box via Win/Putty gateway. Basically, I'd like to be able to do 'ssh localhost -p 512' on a remote server so that it would connect to the RHEL server in the local network. The local network is beyond a firewall so I can connect from my Win PC to the remote server with Putty/ssh but not vice verse.
LclSrv----WinXP/Putty-----||-----RmtSrv
So, I've added the following tunneling settings to the current RmtSrv session in Putty (actually I use Kitty but doesn't matter):
R512 LclSrv:22
I expect that this would create a process on the remote server that listens port 512 and transfers the connections to a local network/LclSrv port 22.
After pressing start button, Putty opens a regular ssh terminal session successfully but nothing happens. (options show active port forwarding). I've checked with netstat -l that port 512 is not listening on RmtSrv. ssh on this port returns 'connection refused'. What am I doing wrong? May be there is something in the sshd_config that needs to be changed in order to allow the tunneling? Could it be user privileges on RmtSrv that prevents me from creating tunnels? I have sudo btw.
Cheers, Vlad.
|
On the left side of the Putty window you have a Menu. On it, SSH has a + to its left. Click there. Go to Tunnels. Configure them. Voilà.
| 0.777778 |
SSH has a + to its left side.
|
netstat: n: unknown or uninstrumented protocol
|
I always use netstat on ubuntu to check which processes are listening on specific ports. I use the following switches with netstat that work fine on ubuntu but on mac fail:
sudo netstat -tulpn
netstat: n: unknown or uninstrumented protocol
|
You can let your Mac "listen" on a network interface:
Type sudo tcpdump -i en0 (followed by your administrator password)
| 0.777778 |
"listen" on a network interface
|
How to find out if my hosting's speed is good enough?
|
There are lots of different online performance tests:
Google PageSpeed Insights
iWebTool Speed Test
AlertFox Page Load Time
WebPageTest
Also there are several desktop/client software such as:
ping tool
YSlow
Firebug's Net console
Fiddler
Http Watch
I just want to decide if my hosting provider has a good enough performance or if I need to switch my hosting to another provider.
So, which tool should I use to compare my hosting provider with other hosting providers?
|
as other have already pointed out, 'speed' can mean many thing.
in those cases i suggest a so-called 'stresstest', that is pushing the server to its limits to see ho many pages it can serve when many browsers are connected and different pages are requested at the same tima.
I normally use Jakarta Jmeter finding it a really effective tool
| 1 |
'speed' can mean many things - 'stresstest'
|
Correlating /var/log/* timestamps
|
/var/log/messages, /var/log/syslog, and some other log files use a timestamp which contains an absolute time, like Jan 13 14:13:10.
/var/log/Xorg.0.log and /var/log/dmesg, as well as the output of $ dmesg, use a format that looks like
[50595.991610] malkovich: malkovich malkovich malkovich malkovich
I'm guessing/gathering that the numbers represent seconds and microseconds since startup.
However, my attempt to correlate these two sets of timestamps (using the output from uptime) gave a discrepancy of about 5000 seconds.
This is roughly the amount of time my computer was suspended for.
Is there a convenient way to map the numeric timestamps used by dmesg and Xorg into absolute timestamps?
update
As a preliminary step towards getting this figured out, and also to hopefully make my question a bit more clear, I've written a Python script to parse /var/log/syslog and output the time skew. On my machine, running ubuntu 10.10, that file contains numerous kernel-originated lines which are stamped both with the dmesg timestamp and the syslog timestamp. The script outputs a line for each line in that file which contains a kernel timestamp.
Usage:
python syslogdriver.py /var/log/syslog | column -nts $'\t'
Expurgated output (see below for column definitions):
abs abs_since_boot rel_time rel_offset message
Jan 13 07:49:15 32842.1276569 32842.301498 0 malkovich malkovich
... rel_offset is 0 for all intervening lines ...
Jan 13 09:55:14 40401.1276569 40401.306386 0 PM: Syncing filesystems ... done.
Jan 13 09:55:14 40401.1276569 40401.347469 0 PM: Preparing system for mem sleep
Jan 13 11:23:21 45688.1276569 40402.128198 -5280 Skipping EDID probe due to cached edid
Jan 13 11:23:21 45688.1276569 40402.729152 -5280 Freezing user space processes ... (elapsed 0.03 seconds) done.
Jan 13 11:23:21 45688.1276569 40402.760110 -5280 Freezing remaining freezable tasks ... (elapsed 0.01 seconds) done.
Jan 13 11:23:21 45688.1276569 40402.776102 -5280 PM: Entering mem sleep
... rel_offset is -5280 for all remaining lines ...
Jan 13 11:23:21 45688.1276569 40403.149074 -5280 ACPI: Preparing to enter system sleep state S3
Jan 13 11:23:21 45688.1276569 40403.149477 -5280 PM: Saving platform NVS memory
Jan 13 11:23:21 45688.1276569 40403.149495 -5280 Disabling non-boot CPUs ...
Jan 13 11:23:21 45688.1276569 40403.149495 -5280 Back to C!
Jan 13 11:23:21 45688.1276569 40403.149495 -5280 PM: Restoring platform NVS memory
Jan 13 11:23:21 45688.1276569 40403.151034 -5280 ACPI: Waking up from system sleep state S3
... The final lines are from a bit further down, still well above the end of the output. Some of them presumably got written to dmesg's circular buffer before the suspend happened, and were only propagated to syslog afterwards. This explains why all of them have the same syslog timestamp.
Column definitions:
abs is the time logged by syslog.
abs_since_boot is that same time in seconds since system startup, based on the contents of /proc/uptime and the value of time.time().
rel_time is the kernel timestamp.
rel_offset is the difference between abs_since_boot and rel_time. I'm rounding this to the tens of seconds so as to avoid one-off errors due to the absolute (i.e. syslog-generated) timestamps only having seconds precision. That's actually not the right way to do it, since it really (I think..) just results in a smaller chance of having an off-by-10 error. If somebody has a better idea, please let me know.
I also have some questions about syslog's date format; in particular, I'm wondering if a year ever shows up in it. I'm guessing no, and in any case could most likely help myself to that information in TFM, but if somebody happens to know it would be useful. ..Assuming, of course, that someone uses this script at some point in the future, instead of just busting out a couple of lines of Perl code.
Next:
So unless some welcome revelation is unto me given by one of You, my next step will be to add a function to get the time skew for a given kernel timestamp. I should be able to feed the script one or a set of syslogs, along with a kernel timestamp, to get an absolute timestamp. Then I can get back to debugging my Xorg issues, which escape me at the moment.
|
You can give this a try :
First, get the timestamp of the dmesg file (my assumption is this will be dmesg's time 0). You'll use ls -l --time-style=+%s
/var/log$ ls -l --time-style=+%s dmesg
-rw-r----- 1 root adm 56181 1294941018 dmesg
You can convert the seconds into a human-readable date with
perl -e 'print scalar localtime(1294941018)'
So to see a readable event time, add in the seconds from the event in dmesg. If the dmesg event was 55.290387 seconds in, add 55 or 55.290387 :
perl -e 'print scalar localtime(1294953978 + 55)'
Another way to transform epochal-rooted seconds into readable time is to use date -d as suggested.
If you tell 'date' to represent a time supplied with -d , you can indicate that the time to be converted is in seconds-since-the-epoch by using @ .
date -d "@1294953978"
This gives you something like "Thu Jan 13 15:26:18 CST 2011" as output.
date +%s will print the current time in the seconds-since-epoch format.
I can't remember how to do shell math, so I typically use the perl method as above. :)
| 0.5 |
How to convert epochal-rooted seconds into readable time?
|
adobe illustrator - linework and paintbucket on different layers
|
I would like to have my brush strokes on one layer and coloring done by live paint bucket on another layer. When I select the strokes and make a live paint group to color with everything, strokes and colors inside strokes become one object. Is there any way to seperate my brush linework and colors on different layers?
|
Duplicate the line art layer and color that.
Live Paint objects have to be on the current layer.
| 0.888889 |
Duplicate the line art layer and color that.
|
Why do objects fall at the same acceleration?
|
I read these two posts and now I am more confused.
Do heavier objects fall faster?
Don't heavier objects actually fall faster because they exert their own gravity?
I was going to ask: if mass is an objects tendency to resist acceleration then why do two objects of different masses fall to the Earth at the same acceleration?
Then I read those posts and it seems that even though it is very small, the more massive object falls faster. Okay I understand, both objects attract each other.
If two cars of different masses collide doesn't the car with less mass accelerate more even though both cars received the same Force. Then that implies you need more force to accelerate a large mass than to accelerate a small mass. Because that is how I see it, the Moon attracts the Earth with the same Force as the Earth attracts the Moon but the Earth accelerates less due to its larger mass.
So then how is mass an object's tendency to resist acceleration? I am aware of $F_1 = F_2 = GMm/r^2$. So should we not really be able to see the difference in acceleration when dropping a massive object?
|
Although Pranav Hosangadi has explained, I will try to explain where you might be going wrong. I think this will be helpful for you. And I think it will not be waste of time in typing the answer for you.
I was going to ask: if mass is an objects tendency to resist acceleration then why do two objects of different masses fall to the Earth at the same acceleration?
Yes, you are right. If we want to push a feather we need less force and the feather resists the acceleration to less extent, and then if you want to push a iron ball we need more force and the iron ball resists the acceleration to more extent.
So, it is correct that mass is the tendency of object to resist acceleration.
Then, why do feather and iron ball gets accelerated to same extent towards the earth?
Isn't iron ball's mass greater than feather's mass, so iron ball should have greater tendency to resist acceleration than feather, thus iron ball should fall first than feather?
Here, if we would had applied same force on iron ball and feather, iron ball would had greater tendency to resist acceleration than feather, so iron ball would get accelerated to less extent than feather. Here, although iron ball gets accelerated to less extent, its greater mass than feather makes force to be equal to force exerted on feather, where acceleration of feather is more but mass is less.
But, earth doesn't exert same force on feather and iron ball. Force exerted on iron ball is greater than force exerted on feather. As it is confirmed from Pranav Hosangdi's answer that acceleration due to gravity is independent of mass of the body to which earth exerts force.
Then I read those posts and it seems that even though it is very small, the more massive object falls faster. Okay I understand, both objects attract each other.
Seeing your comment, I hope you have understood that because of air resistance iron ball falls first than feather.
If two cars of different masses collide doesn't the car with less mass accelerate more even though both cars received the same Force.
Yes, the car with less mass accelerates to greater extent than the car with greater mass as you stated force to be same on both.
Then that implies you need more force to accelerate a large mass than to accelerate a small mass. Because that is how I see it, the Moon attracts the Earth with the same Force as the Earth attracts the Moon but the Earth accelerates less due to its larger mass.
Yes, you need more force to accelerate a large mass than to accelerate a small mass. That is the reason earth exerts more force on massive objects than on tiny objects. You are also correct in saying about earth moon interaction.
So then how is mass an object's tendency to resist acceleration?
So far there is nothing which has contradicted with how mass can't be tendency to resist acceleration. If there is any thing you can comment.
. So should we not really be able to see the difference in acceleration when dropping a massive object?
Massive object and tiny objects are not exerted with the same force by the earth, you are thinking that on both the object force is same. Earth exerts different force on massive objects and tiny objects. Acceleration due to gravity has constant value at different points in space, just like electric field has constant value at different points in space. Acceleration due to gravity can be considered as gravitational field. So, no matter what mass you keep, it will be accelerated to same extent.
| 1 |
Why do two objects of different masses fall to the Earth at the same acceleration?
|
How to Enable Ports 25 - 28 on a Cisco Catalyst 3750
|
I am trying to enable ports 25 - 28 on my 28 port Catalyst 3750. These four ports are my fiber ports. I am using the following command to bring up that interface.
interface range Gi1/0/25 - 28
That works and it dumps me in the config-if-interface prompt. This is where I get stuck. I just want to enable these four ports and have them be in VLAN1 and On just like ports 1 - 24.
How do I do this?
|
Do the ports require GBICs (and, if so, do you have GBICs installed)? Do you have cables attached to the ports? If you're using fibre, you MAY have to swap the connectors around (I don't think this is possible for SFP connectors, so you'd have to have a cross-over cable or a connector that allows you to connect RX on one cable to TX on the other).
| 1 |
Do the ports require GBICs?
|
Ubuntu 12.04.2 LTS vs. Ubuntu 12.10?
|
should I pick Ubuntu 12.04.2 LTS or 12.10 for my home machine?
I know that Ubuntu 12.04 is LTS but 12.10 is newer.
But what should I pick now?
Can I use Gnome 3 Shell (apt-get install gnome-shell) without any problems in Ubuntu or is it recommend to use Unity?
Greetings,
Majestro
|
Since 12.04 is LTS. I'd suggest 12.04, if you're not willing to upgrade. 12.10(And 13.04 soon), I'd suggest those two if you'd want a more "fancy" feature-updated machine.
New features in 12.10 is listed here: http://www.ubuntu.com/ubuntu/whats-new - And if you can go without those, I'd install 12.04.
| 1 |
If you want a more "fancy" feature-updated machine, install 12.04
|
Find orphaned users
|
In SQL Server 2005, is there a way to find users that either don't exist at the server level (an account that was deleted at server level but wasn't disassociated from databases before it was deleted) or accounts that aren't linked (an account may have been deleted at the server level but not db level, then readded but the db level was never cleaned up).
I've got a very messy server and it would be awesome if there was a query to run to find these.
|
Apologies to the creator of this script for not giving credit but I've no idea where I sourced it from. It's been in the toolbox for a while.
This iterates through all databases and lists the orphaned users by database, along with the drop command to remove them. There may be a neater/newer way of handling this but this appears to function correctly on 2005-2012.
DECLARE @SQL nvarchar(2000)
DECLARE @name nvarchar(128)
DECLARE @database_id int
SET NOCOUNT ON;
IF NOT EXISTS
(SELECT name FROM tempdb.sys.tables WHERE name like '%#orphan_users%')
BEGIN
CREATE TABLE #orphan_users
(
database_name nvarchar(128) NOT NULL,
[user_name] nvarchar(128) NOT NULL,
drop_command_text nvarchar(200) NOT NULL
)
END
CREATE TABLE #databases
(
database_id int NOT NULL
, database_name nvarchar(128) NOT NULL
, processed bit NOT NULL
)
INSERT
#databases
( database_id
, database_name
, processed )
SELECT
database_id
, name
, 0
FROM
master.sys.databases
WHERE
name NOT IN
('master'
, 'tempdb'
, 'msdb'
, 'distribution'
, 'model')
WHILE (SELECT COUNT(processed) FROM #databases WHERE processed = 0) > 0
BEGIN
SELECT TOP 1
@name = database_name,
@database_id = database_id
FROM #databases
WHERE processed = 0
ORDER BY database_id
SELECT @SQL =
'USE [' + @name + '];
INSERT INTO #orphan_users (database_name, user_name, drop_command_text)
SELECT
DB_NAME()
, u.name
, ' + ''''
+ 'USE [' + @name + ']; '
+ 'DROP USER ['
+ '''' + ' + u.name
+ ' + '''' + '] '
+ '''' + '
FROM
master..syslogins l
RIGHT JOIN
sysusers u
ON l.sid = u.sid
WHERE
l.sid IS NULL
AND issqlrole <> 1
AND isapprole <> 1
AND ( u.name <> ' + '''' + 'INFORMATION_SCHEMA' + ''''
+ ' AND u.name <> ' + '''' + 'guest' + ''''
+ ' AND u.name <> ' + '''' + 'dbo' + ''''
+ ' AND u.name <> ' + '''' + 'sys' + ''''
+ ' AND u.name <> ' + '''' + 'system_function_schema' + '''' + ')'
PRINT @SQL;
EXEC sys.sp_executesql @SQL
UPDATE
#databases
SET
processed = 1
WHERE
database_id = @database_id;
END
SELECT
database_name
, [user_name]
, drop_command_text
FROM
#orphan_users
ORDER BY
[database_name]
, [user_name];
DROP TABLE #databases;
DROP TABLE #orphan_users;
SET NOCOUNT OFF;
| 0.777778 |
DeCLARE @SQL nvarchar
|
how to stop my html page resize
|
i made an HTML page with all widths and heights as percentage "that's primary for my design to work with all resolutions" but when i re-size my web browser everything will be damaged.
is there a way that when i re-size my web browser i can scroll the page?
|
You can give elements min-width and min-height properties:
body { min-width: 900px; }
Now if the browser window has less than 900px of horizontal space, it will show a scroll bar.
| 0.888889 |
You can give elements min-width and min-height properties .
|
XSLT Sort with variable select
|
I have a HTML select dropdown:
<select name="sortby">
<option value=""></option>
<option value="onenightavg">Price: High to Low</option>
<option value="number_bedrooms">Bedrooms: High to Low</option>
<option value="number_bathrooms">Bathrooms: High to Low</option>
<option value="max_sleeps">Sleeps: High to Low</option>
</select>
When the user submits this it sends a URL query string to the page and it gets added to the XML of the page:
<querystring>
<sortby>number_bathrooms</sortby>
</querystring>
I then set an XSL variable in my XSLT:
<xsl:variable name="sortby">
<xsl:choose>
<xsl:when test="/querystring/sortby != ''">
<xsl:value-of select="/querystring/sortby" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'onenightavg'" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
In the above XST I am setting a variable called $sortby and testing whether the querystring exists. If it does exist then set the variable to its value. If it doesn't exist then default it to "onenightavg".
Then I use that variable in my sort:
<xsl:sort data-type="number" order="ascending" select="$sortby" />
This doesn't work. It doesn't sort my items, but when I hardcode the select to any one of the values like this it works:
<xsl:sort data-type="number" order="ascending" select="onenightavg" />
I would like to be able to dynamically sort based on an the value of the selected option in the dropdown.
|
How about this:
<xsl:sort data-type="number" order="ascending" select="*[local-name() = $sortby]" />
| 0.888889 |
<xsl:sort data-type="number"
|
Server compromised - How do I find out what is sending mail
|
A friend of mine has a few small businesses and hosts Wordpress-based sites for them on a dedicated host. The Wordpress installs were neglected for awhile and the host ended up getting compromised. There's now 100's of spam messages going out every second. What can I look at to determine what's generating the mail?
The only way I can get the spam to stop is to shutdown Postfix. We've had it off for a few days to prevent spamming, but this also means he can't send mail from his businesses addresses.
If I shutdown both apache and postfix, netstat shows no remote connections except my SSH login. If I then start postfix (but leave apache stopped), 100's of remote connections to port 25 immediately open. This leads me to believe that some process on the host is doing this, rather than something coming in through Wordpress/some rogue script that we missed in the clean-up. There were also IRC bots on here, but we've removed those, and netstat no longer shows any open connections to IRC.
When I look at ps axjf - all of the smtp processes roll up to /usr/libexec/postfix/master, which has a parent id of 1. This doesn't really give me an idea of where the mail is being generated.
Neither ps nor top show any suspicious processes (as far as I can tell).
What else can I look at to see what's creating/sending the mail? I can post the output of ps whatever_flags_you_want both with and without postfix running, if it will help.
Thanks.
|
Thanks for the responses everyone. We did install and run rkhunter, it didn't find anything.
It looks like we actually did take care of this in the initial clean-up, but postfix was trying to resend messages that had been bounced after the host was blacklisted.
There were 100's of thousands of messages stuck in /var/spool/postfix/deferred. I think when I started postfix, it was moving those back to ./active and trying to resend. I just deleted everything in ./deferred and ./active, then started postfix. It doesn't appear that any new messages are being created or sent. I'm thinking this was just me not understanding how postfix works.
I've been running
watch -d -n 1 'ls -lhart /var/spool/postfix/active'
and
watch 'netstat --program --numeric-hosts --numeric-ports --extend | grep -E ":25|postfix|smtp"'
For about 30 minutes and see no outgoing activity.
| 1 |
Postfix was trying to resend messages that had been bounced after the host was blacklisted .
|
I am planning on going out to Pakistan
|
I am planning on going out to Pakistan soon and I am wondering if I should bring my Xbox 360 for a friend that stays there,
Would the Pakistani games work on my Xbox 360?
|
The Xbox 360 is region locked. Play Asia has a good guide to help determine what games are playable.
| 1 |
The Xbox 360 is region locked
|
How to i update an iPhone 4 with iOS 4.3.5 offline
|
i was able to update my iPhone 4S and iPad via the option on the settings menu however i iPhone 4 which i use as my music player doesn't have that option, my computer with itunes doesn't connect to the internet so i can't download it via itunes
i am wondering if there is an offline installer i can download that itune can detect to use, that way i can download it on a separate computer then transfer it to my main computer
|
If you want to do an offline upgrade iOS to iOS 7.1, follow the steps in this guide
http://echo.com.ng/2013/howto-apple-ios-7-offline-manual-upgrade
| 0.777778 |
iOS 7.1 offline upgrade
|
How to calculate the size of the image circle at infinity focus?
|
How can I determine the diameter of the image circle (i.e. the diagonal size of CCD required to fully utilise a telescope's optics) at near-infinity focus? I have looked around online and found this calculator, but I am more interested in how the figure was calculated than knowing the figure itself.
Background: I am new to astrophotography and recently bought a Celestron Nexstar 130 SLT telescope with a Barlow lens, T-adaptor and T-ring to connect it with my Nikon D80 to take photographs of the night sky in prime focus. The telescope dimensions are 130mm aperture and 650mm focal length. With the 2x Barlow lens (required to diverge the focus enough to mount the camera outside the optical tube assembly) it effectively becomes a telescope with 1300mm focal length. I can measure a picture of an object with known angular size (e.g. the moon) and use crop factors to establish a ratio, but this method doesn't help me understand how a bigger/newer telescope would fare on the same CCD.
Edit:
Since this question now has a bounty, I would like to emphasize the real question is How to calculate the size of the image circle at infinity focus?, and not the follow-up question of
Would the image circle size decrease if I was able to ditch the Barlow lens?
|
I am not sure about the answer to Would the image circle size decrease if I was able to ditch the Barlow lens?
But if you look at the JavaScript of that page you will see
var sensorw = "Sensor Width"
var sensorh = "Sensor Height"
var maxres = "Max Res"
var focleng = "Focal Length"
var thisF = sensorw * 3438/focleng;
var thisF2 = sensorh * 3438/focleng;
var thisF3 = sensorw * 3438/focleng * 60/maxres;
var thisF4 = focleng/Math.sqrt(sensorw * sensorw + sensorh * sensorh);
Values:
thisF = Arc Min of Sky- Width:
thisF2 = Arc Min of Sky- Height:
thisF3 = Arc Seconds/Pixel:
thisF4 = Magnification (X):
This is how that page calculates it
| 1 |
Would the image circle size decrease if I had to ditch the Barlow lens?
|
iMessage Weird Behavior
|
I have multiple mobile devices (2x iPhone, 2x iPad) in my home, all which share the same iTunes account between them. When iMessage is used to exchange messages between two of the devices (e.g. the two iPhones), the messages appear to be sent from and received by the same identity. The only way I have found to correct this by turning off iMessage on one of the devices and only using SMS.
Is there a way to associate iMessage with a different iTunes account than other apps on the same device?
|
If you go into Settings > Messages, you should be able to choose which email addresses you get iMessages to. It's under the Receive At option which let's you input additional email addresses.
Additionally, you can even sign out of your iMessage account without affecting the iTunes account by tapping on the name of the account you are currently signed in as (on the same screen).
Here's what it looks like on an iPhone:
| 1 |
Select which email addresses you get iMessages to
|
Changes made to XSLTListViewWebPart in SharePoint Designer not showing on page
|
I am trying to learn, through trial and error, how to get values from parameters that are declared in the ParameterBindings section in an XSLTListViewWebPart through SharePoint Designer.
I have noticed that occasionally, when I make a change to the web part that I am guessing is not well formed, I see no change to the SharePoint page when I refresh the browser.
What I am wondering is where could I see the error message associated with my ill-formed XSLT?
In SharePoint designer I don't see an Errors or Output window that would show the progress as my saved changes to the web part get published to my site. I also tried looking at my machine's Event Viewer and couldn't find any errors associated with my publishes. Finally, I looked at the ULS logs while I was publishing and while I was requesting the changed page and I don't see any errors coming through at those times.
What is the best approach to track errors when publishing from SharePoint Designer?
|
SharePoint Designer will inform you about ill-formed XSLT. It will pop up an error message, albeit sometimes cryptic.
But, SharePoint Designer has the bad habit to revert to the original xslt in some situations. When you save and close the page in SPD, then open it again, are your changes still there?
If you have customised the XSLT and these changes don't stick, edit the XSLT and find all instances of ddwrt:ghost=hide in any tag. Remove all of these and apply your changes again.
| 1 |
XSLT reverts to original xslt
|
How do I make an endless road in Unity?
|
Basically I created 2 quads side by side and I added a road texture. I used transform.translate so that the road moves, but I am trying to make the road endless by making the 2 quads reposition themselves in front of the current quads repeatedly so that when I add a player the road is endless. Any way I could do this?
|
You could have 2 sufficiently long road segments. Place them one after another. When player moves from one road segment to another, remove the segment which is (now) behind the player, to the front of the current segment.
| 1 |
Place 2 sufficiently long road segments one after another.
|
Should only the left "Rear Fog Light" actually light up in a pair?
|
On a 2003 Saab 9-5 Aero, only the left rear fog light lights up. The right side has a bulb but when I switch the bulbs, the left still is the only side that lights up.
I thought it might be a wiring issue, however a friend mentioned that his Porsche only has wiring and bulbs on the left side for the reverse fog light.
Is the left side really the only side that should light up for a pair of rear fog lights?
(The fact that the right side has a bulb in the Saab seems strange to me, but maybe it was easier to make them symmetric during manufacturing).
|
I did some research on some Saab forums. I found that typically on US bound Saab 9-5 a bulb is installed on both sides. However, the metal circuit on the passenger side is cut to disable that side. This is to prevent the rear fog lights from appearing as brake lights (there are arguments about the legality of dual rear fog lights in certain US locations).
It appears the circuit can be soldered back together and to enable dual rear fog lights.
| 1 |
Dual rear fog lights in US bound Saab
|
MonoTouch: How to save a huge PDF downloaded from an URL incrementally?
|
I need to download a huge PDF file from an URL in my MonoTouch iPhone/iPad newsstand app.
The PDF is too big to fit in memory, so I need to save it incrementally with NSData.
My idea is the following: instead of appending all the downloaded data in NSData and at the very end of the download, when I got all data, to store it to a file, I want to execute the download asynchronously in a separate thread and append to a file each received chunk and free my memory, but be certain that if the connection is dropped or the app crashes the download would resume automatically from the last chunk without corrupting the file.
What do you suggest? Is there a better method? How can I do it in MonoTouch? I did't find any documentation or code example about iOS incremental download/resume on the Xamarin website.
|
You don't need NSData or anything from ObjC.
You can use WebClient (http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) to achieve this in plain C#.
For an example of a chunked download with progress bar, see here: http://devtoolshed.com/content/c-download-file-progress-bar
| 0.888889 |
WebClient is a chunked download with progress bar.
|
How to send an email from command line?
|
How to send an email from command line or script? I want to be able to run the script programmatically by passing the receiver and the message.
|
Since it's Unix based, you can use sendmail command.
| 0.888889 |
Use sendmail command to sendmail
|
Cannot access non-static field
|
I can't figure out why it's looking for something static:
public class DatabaseBase
{
private readonly string connectionString;
public DatabaseBase(string connectionString)
{
this.connectionString = connectionString;
}
}
public class MyDB : DatabaseBase
{
readonly string connectionString = ConfigurationManager.AppSettings["MyConnectionString"];
public MyDB() : base(connectionString)
{
}
}
I get Cannot access non-static field 'connectionString' in static context. I don't see anything static in the base Database class so why??
here's another example of when we did kinda the same thing:
partial class Database : DatabaseBase
{
static string DbConnectionString
{
get
{
if (dbConnectionString == null)
dbConnectionString =
ConfigurationManager.AppSettings["MyConnectionString"];
return dbConnectionString;
}
}
public Database() :base(DbConnectionString)
{
}
ok so why did it have to be a static string for the connection string to be passed?
|
We have worked hard to give error messages that are accurate, so read them carefully. The error message is telling you exactly what is going wrong: you are accessing a non-static field in a context where it is only legal to access statics.
So why is a base constructor call argument list a context where it is only legal to access statics?
When you call a base constructor, the arguments you pass must not reference "this". Why? Because neither the derived constructor nor the base constructor for your "this" has run yet, and therefore "this" is almost certainly in an inconsistent, partially-initialized state. That is a recipe for crazy bugs. We therefore restrict you from accessing "this" until we know that at the very least, the base constructor has run.
This feature encourages sensible, well-ordered, understandable, maintainable and bug-free construction logic; I recommend working with, not against, those safeguards.
| 0.666667 |
Why is a base constructor call argument list a context where it is only legal to access statics
|
Prepare SD card for Wifi on Headless Pi
|
I need to SSH my Pi over wifi but because it is a model A board (using a usb hub is not possible - ever) and I have no ethernet, i can't configure the Pi to connect to my secured wifi network. I want to have the SD card plugged into my laptop and I want to edit a file with the wifi configuration information in it so my Pi will connect to my network automatically at start-up so I can then SSH it to get control. I know how to enable SSH on a headless system thanks to this answer.
Edit.
Ive been searching around and I'm wondering if I'm able to just edit the file /etc/network/interfaces while the SD card is in my PC and put in all the network ssid, psk and wlan0 stuff in it. Will this work? Thanks
|
You need to edit the wpa_supplicant.conf file on the sdcard (it's in /etc or /etc/wpa_supplicant depending on your distribution version). The format of the file is explained here: http://linux.die.net/man/5/wpa_supplicant.conf
| 0.888889 |
Edit the wpa_supplicant.conf file on the sdcard
|
Changing background image one time on responsive background image
|
The code I'm using is this one
background: url(bilder/cover.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
What I'd like to accomplish is that the background image is changed after like 2 sec to a background image that then stays put.
I know there are Jqueries for changing backgrounds like this but I'm not sure how to make something like that work with the code I'm using! It would be awesome if someone hade a solution to this!
My starting point for changing background was the code I found on w3schools:
{
width:100px;
height:100px;
background:red;
animation:myfirst 5s;
-webkit-animation:myfirst 5s; /* Safari and Chrome */
}
@keyframes myfirst
{
from {background:red;}
to {background:yellow;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
from {background:red;}
to {background:yellow;}
}
|
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>demo by roXon</title>
<script src="s.js"></script>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
*{margin:0;padding:0;}
ul{list-style:none;}
a{text-decoration:none;}
body{background:#000;}
.images{
margin:50px;
position:relative;
}
.images img{
position:absolute;
}
.glowed{
box-shadow: 0px 0px 40px 2px #fff
}
</style>
</head>
<body>
<button id="stop">STOP IT!</button>
<div class="images">
<img src="images/9.jpg" />
<img src="images/9red.jpg" class="glowed"/>
</div>
<script>
var stop = false;
function loop(){
if(stop===false){
$('.images img:eq(1)').fadeIn(700, function(){
$(this).fadeOut(700,loop);
});
}
}
loop(); // start loop
$('#stop').click(function(){
stop=true;
});
</script>
</body>
</html>
| 0.888889 |
<!DOCTYPE html>
|
On surjections, idempotence and axiom of choice
|
The following assertion is trivial in ZFC, or even in much weaker theories. Is it also true in ZF?
(I couldn't find it in the Consequences site so far.)
If $A$ is an infinite set such that $A$ can be mapped onto $A\times 2$ then $|A\times 2|=|A|$
The problem is that we cannot necessarily choose from every fiber of $f$, so we cannot construct an injection from $A$ to $f^{-1}(A\times\lbrace 0\rbrace)$, which will prove the assertion.
While I'm on the topic, is it possible for a D-finite set to have such property? It is possible for a D-finite set to be surjected onto a larger set than itself, but what about that large?
|
This is only a partial answer, but it's way too long to go in the comments. I'll describe a permutation model (of ZF with atoms) that seems to give a counterexample $A$ for your statement. It will be easy to see that $A$ maps onto $A\times2$, but I haven't proved that there's no bijection between $A$ and $A\times2$; all I can say is that it looks quite plausible. If the example is correct, it will automatically transfer to ZF (without atoms) by the Jech-Sochor theorem. So here's the model.
Start with a set $U$ of atoms in 1-1 correspondence with the product $2^\omega\times3$ of the Cantor set and the ordinal 3. I'll write [x,i] for the atom that corresponds to the pair $(x,i)$, where $x\in2^\omega$ and $i\in3$. Let $G$ be the group of those permutations of $U$ that leave the first component (in the Cantor set) of each atom unchanged. So $G$ is the direct product of continuum-many copies of the symmetric group $S_3$. To define the class of supports, let me first introduce the terminology "thread" for an $\omega$-sequence of atoms $[x_n,i_n]$ such that, for each $n$, $x_{n+1}$ is obtained from $x_n$ by deleting the first bit, i.e., $x_{n+1}(k)=x_n(k+1)$. Let the supports be those subsets of $U$ that are covered by finitely many threads. This choice of supports (along with the choice of $U$ and $G$) determines a permutation model $M$.
In $M$, let $A$ be the set of all the threads. There is a surjection from $A$ to $A\times 2$, namely the map that sends any thread $T$ to the pair $(T',b)$ where $T'$ is obtained from $T$ by deleting its first term, say $[x_0,i_0]$, and $b=x_0(0)$. (So $b$ is the one component in the real $x_0$ that is omitted when one forms $x_1$.) This surjection is exactly 3 to 1, as it essentially just "forgets" the $i_0$ from $T$.
I believe, but have not proved, that $M$ contains no injection from $A\times2$ into $A$. The idea of the proof would be to assume there is such an injection, fix a finite number of threads that support it, and then look at what the injection could do with threads $T$ whose $x_0$ has no tail in common with anything from the support.
I further believe that the model would also work if I had used 2 instead of 3, but that the missing part of the proof will be easier with 3. The point is that, with 2, each thread would support the "complementary" thread, consisting of the same reals $x_n$ but the other elements $i_n$ in 2. It would also support various "mixtures" of itself and the complementary thread. With 3, a thread should support no threads other than itself and truncations of itself.
Going even further out on a limb, I also believe that the model would work if, instead of the whole Cantor space $2^\omega$, I used only the subspace consisting of the eventually periodic sequences of 0's and 1's and required threads also to be eventually periodic. In this model, $A$ should be Dedekind-finite, thus answering the last part of your question.
| 0.666667 |
Permutation model of ZF with atoms
|
100% Rye Pizza Base Recipes?
|
I'm looking for a 100% rye pizza base recipe. The recipes I can find all combine the rye with other flours (typically wheat based). I know it is possible to create 100% rye based pizza bases as I know of one pizza place in town that sells them.
I understand that they had to do something special to keep the pizza base from falling apart. I don't mind experimenting a bit to find a recipe that works, but I could use some ideas on where to start - what sort of ingredients might bind the rye so that it doesn't crumble as a thin pizza base and maintains a low glycemic index for my diabetic wife.
The only dietary requirements would be that the various ingredients maintain a low glycemic index or a specific ingredient with a high glycemic index can be counteracted by some other ingredient. And only using rye flour.
|
I don't mind experimenting a bit to find a recipe that works, but I could use some ideas on where to start - what sort of ingredients might bind the rye so that it doesn't crumble as a thin pizza base and maintains a low glycemic index for my diabetic wife.
Psyllium husk is the general go-to binder for low-carb bread, but I have not seen a recipe using it in rye pizza dough. Another alternative is to give up on substituting bread and use the same toppings with something else. A frittata does not add much extra work and works well with standard pizza toppings.
| 1 |
What kind of ingredients might bind the rye so that it doesn't crumble as a thin pizza base?
|
Is there an "Appending \let"?
|
After
\def\MyText{\textbf{My Text}}
\let\MySaved\MyText
\MySaved and \MyText have the same \meaning. What I would like to have further down in the document is
% \MyText = \textbf{My Text}
\def\MyText{\textit{More Text}}
\let\MySaved{\MySaved \MyText}
% \MySaved = \textbf{My Text} \textit{More Text}
but obviously \let does not allow a group of tokens in the second argument.
Is there any way to append like this with the same specific (non-)expansion properties \let has?
|
Since the question is about plain TeX, I would suggest using token list registers for this rather than macros, since token lists are there specifically for this purpose, namely to hold token lists. Create one with
\newtoks\MyList
Assign an explicit list to it by for instance
\MyList={\textbf{My text}}
or any other (balanced) token list between the braces; since this is about gathering tokens, you can be sure there is no attempt to expand anything there. Unlike macros, token list registers do no spontaneously expand to the tokens they hold (if TeX encounters the name of a token list register when expecting an action, it will assume this starts an assignment to the register, and protest if no opening brace follows), so to get at the contents, you must explicitly expand with \the. Hence if at the end of the day you want to transfer the tokens to become the body of a macro, you can say
\edef\macro{\the\MyList}
(the \edef is used because the contents of \MyList is wanted here and now, not later when \macro gets expanded). Note that even though \edef usually keeps expanding as far as it can, the result of \the applied to a token list register is explicitly excluded from any further expansion attempts, so you can be sure that \macro will expand to exactly the tokens that were collected in \MyList.
Now to extend to contents of a token list register is fairly simple; you must just ensure the the old contents gets to be expanded into the new token list before the assignment is made. For this a single \expandafter will do:
\MyList=\expandafter{\the\Mylist more tokens here}
When you need to expand something towards the end of the token list, it takes a bit more effort. Say you want to append to the contents of \MyList that of another token list register \AnotherList. Then you could ensure that the rightmost list gets expanded, and then the leftmost one (can you see why this order is necessary?), all this before the assignment takes place, by a whole slough of \expandafters:
\let\x=\expandafter
\MyList=\x\x\x{\x\the\x\MyList\the\AnotherList}
However there is an easier way, that mixes the expansive nature of \edef and the passive nature of token lists to get detailed control over expansion. It needs an auxiliary macro, say \temp:
\edef\temp{\the\MyList\the\AnotherList}
\MyList=\exandafter{\temp}
I final remark about the question; you suggest that \let serves to copy the expansion of one macro to another macro without further expanding that expansion
(as using \edef would do). While \let can be used for that, this is not its main purpose, and in fact this is just a corollary of what \let does in general: transfer the current meaning of one token to another one (provided the latter can have its meaning modified, so it should not be a non-active character). This is not limited to macros: you can make a control sequence stand for a plain character, or for a TeX primitive (as I did above to let \x stand for the primitive \expandafer; note that having instead \x expand to \expandafer would be quite different and quite useless) or for other meanings that a token can have. Just as an example of the last possibility, saying
\let\newname=\MyList
would transfer the current meaning (not the contents!) of \MyList to \newname. Since \MyList stood for an internal token list register of TeX, this makes \newname stand for the same register: it becomes an alias for \MyList, and assigning to one of them changes the contents of the other as well.
| 0.777778 |
To expand to token list registers, you must explicitly expand with the
|
Numerical differentiation methods
|
Is it possible to write code in Mathematica that implements various differentiation methods (like forward, central, extrapolated, etc.)?
|
In the spirit of sharing ancient code I wrote on this topic that is still working and relevant today, here is some code in a notebook I called "difference differentials". You should like this, I certainly got a kick out of it when I did it. It was a 4 beer late night curiosity event that was never shared until now. This was from the early undergrad days, a private curiosity, and I was basically "hacking" the Mathematica with few skills, so don't pick on me, I actually have grown by light years since this.
My original description:
"This code uses central differences to approximate the derivatives of a function. Change lo, hi, del, and f[x_] as you please, then go to Evaluation->Evaluate Notebook for a new result."
lo = -12;
hi = 12;
del = 1;
f[x_] := (x + 16) (x + 5) (x) (x - 11) (x - 14)/10000
plot = Plot[f[x], {x, lo, hi}, AxesLabel -> {"x", "f[x]"},
PlotStyle -> Directive[Opacity[.75], Thick, Blue]];
plottable = Table[{x, (f[x])}, {x, lo, hi, del}];
plot1prime =
Plot[f'[x], {x, lo, hi}, AxesLabel -> {"x", "f[x]"},
PlotStyle -> Directive[Opacity[.75], Thick, Purple]];
plot1primetable = Table[{x, (f'[x])}, {x, lo, hi, del}];
plot2prime =
Plot[f''[x], {x, lo, hi}, AxesLabel -> {"x", "f[x]"},
PlotStyle -> Directive[Opacity[.75], Thick, Brown]];
plot2primetable = Table[{x, (f''[x])}, {x, lo, hi, del}];
dif1plottable =
Table[{x, (f[x + del] - f[x - del])/(2*del)}, {x, lo, hi,
del}];(*centered difference*)
p1plot = ListPlot[dif1plottable, AxesLabel -> {"t", "P(t)"},
PlotStyle -> Directive[PointSize[Medium], Red]];
dif2plottable =
Table[{x, (f[x + del] - 2*f[x] + f[x - del])/(del^2)}, {x, lo, hi,
del}];(*centered second difference*)
p2plot = ListPlot[dif2plottable, AxesLabel -> {"t", "P(t)"},
PlotStyle -> Directive[PointSize[Medium], Black]];
Show[plot, plot1prime, plot2prime, p1plot, p2plot, AxesOrigin -> {0, 0},
PlotRange -> Automatic]
I am entertained by the result of that output even today, but there was alot I did not know about writing good code at that time that could be improved.
Here is the table output (WOW there was so much I did not know back then!):
table = Table[{i}, {i, lo, hi, del}];
Table[AppendTo[table[[i]],
plottable[[i]][[2]]], {i, ((hi - lo)/del) + 1}];
Table[AppendTo[table[[i]],
plot1primetable[[i]][[2]]], {i, ((hi - lo)/del) + 1}];
Table[AppendTo[table[[i]],
dif1plottable[[i]][[2]]], {i, ((hi - lo)/del) + 1}];
Table[AppendTo[table[[i]],
plot2primetable[[i]][[2]]], {i, ((hi - lo)/del) + 1}];
Table[AppendTo[table[[i]],
dif2plottable[[i]][[2]]], {i, ((hi - lo)/del) + 1}];
TableForm[N[table],
TableHeadings -> {None, {"x", "f[x]", "f'[x]", "1st differences",
"f''[x]", "2nd differences"}}, TableAlignments -> Center]
| 0.888889 |
"difference differentials" in a notebook I wrote on this topic
|
Wordpress and Apache 2.4 installation troubles: Cannot Serve Directory
|
I'm having a devil of a time getting Wordpress going on my webhost. When I try to access my virtualhost, I get a "403 Forbidden You don't have permission to access / on this server." error and a "Cannot serve directory..." error in my error_log (see below). Why am I getting "403 Forbidden"? I am missing something, hopefully obvious to you (not to me, naturally). Thanks for any help.
I installed a minimal install of Fedora 20 (ie, no Gnome/KDE but plenty of php packages [710] so it's not that skinny). Then I installed Apache, and followed up with the Wordpress install as per http://codex.wordpress.org/Installing_WordPress#Famous_5-Minute_Install . Since then, I have been hacking around in /etc/httpd trying to find the issue.
I have version 2.4 of Apache, php 5.5.18, Fedora 20, and Wordpress 4.0-1.
I have created my Virtualhost in Apache, and here is the error in my error log (all on one line):
[Sat Nov 15 20:38:16.067198 2014] [autoindex:error] [pid 6745]
[client XX.XX.XX.XX:48419] AH01276: Cannot serve directory /usr/share/wordpress/:
No matching DirectoryIndex (index.html) found, and server-generated directory
index forbidden by Options directive
I have been hacking and hacking the httpd.conf file and my Virtual host's file (found in /etc/httpd/conf.d/myhostname.conf) to no avail. Any ideas? I include a (shortened) copy of my httpd.conf and my virtual host's conf file. First, the virtual host:
<VirtualHost *:80>
ServerName virtual1.myhost.com
ServerAlias virtual1
DocumentRoot /usr/share/wordpress
ErrorLog logs/virtual1_error
CustomLog logs/virtual1_access common
</VirtualHost>
<Directory />
Require all granted
AllowOverride None
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</Directory>
<Directory /usr/share/wordpress>
Require all granted
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Options FollowSymLinks
AllowOverride None
# <IfModule mod_authz_core.c>
# # Apache 2.4
# Require local
# </IfModule>
# <IfModule !mod_authz_core.c>
# # Apache 2.4
# Require all granted
# AllowOverride None
# </IfModule>
</Directory>
<Directory /usr/share/wordpress/wp-content/plugins/akismet>
<FilesMatch "\.(php|txt)$">
Require all granted
AllowOverride None
</FilesMatch>
</Directory>
Now, the httpd.conf:
#
ServerRoot "/etc/httpd"
Listen 80
Include conf.modules.d/*.conf
User apache
Group apache
ServerAdmin root@localhost
<Directory />
AllowOverride none
Require all granted
</Directory>
DocumentRoot "/var/www/html"
<Directory "/var/www">
AllowOverride None
# Allow open access:
Require all granted
</Directory>
<Directory "/var/www/html">
Require all granted
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
<Files ".ht*">
Require all denied
</Files>
ErrorLog "logs/error_log"
LogLevel warn
<IfModule log_config_module>
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>
<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<IfModule mime_module>
TypesConfig /etc/mime.types
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
</IfModule>
AddDefaultCharset UTF-8
<IfModule mime_magic_module>
MIMEMagicFile conf/magic
</IfModule>
EnableSendfile on
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.myhost.com
ServerAlias www
ServerAdmin [email protected]
DocumentRoot /var/www/html
ErrorLog logs/error_log
CustomLog logs/access_log common
</VirtualHost>
IncludeOptional conf.d/*.conf
|
It looks like you have forgotten DirectoryIndex.
This should be added to the <VirtualHost> serving WordPress.
DirectoryIndex index.php
| 1 |
DirectoryIndex index.php
|
Is it possible to withdraw USD from ATMs in Tanzania?
|
I will be In the following Tanzanian towns, Arusha, Dar es Salaam and Stone Town and would like to know where I am best to replenish My stock of USD?
Is it possible to withdraw USD from ATMs in Tanzania or will I need to withdraw local currency and use a currency exchange?
|
There is an ATM at the airport in Kilimanjaro; I can't remember exactly if it gave me USD or local currency. i actually think it was USD as I had to pay for my visa in USD only on arrival. It as $100 at the time and did not have enough USD to cover it.
The best thing to do is to contact the Tanzania Tourist Board or the Airport Authorities in Tanzania.
| 1 |
Tanzania Tourist Board or Airport Authorities in Tanzania
|
What's the difference between Fermi Energy and Fermi Level?
|
I'm a bit confused about the difference between these two concepts. According to Wikipedia the Fermi energy and Fermi level are closely related concepts. From my understanding, the Fermi energy is the highest occupied energy level of a system in absolute zero? Is that correct? Then what's the difference between Fermi energy and Fermi level?
|
Fermi energy is difference of energies of highest and lowest occupied single state particle. But, Fermi level is the sum of total energy of a particle (i.e) the sum of kinetic and potential energies.
| 1 |
Fermi energy is difference of energies of highest and lowest occupied single state particle
|
SQL Help in Access – Looking for the Absence of Data
|
I am trying to find the fastest way to find all of the records in a parent table that do not have certain records in a child table. For example, I want the query to return all of the family records where there are no male children or no children at all.
Example 1
This is painfully slow:
SELECT * FROM Families
WHERE Families.FamilyID NOT IN(SELECT FamilyID FROM Children WHERE Children.Gender="m")
Example 2
This is faster:
SELECT * FROM Families
WHERE NOT EXISTS(SELECT * FROM Children WHERE Children.Gender="m" AND Children.FamilyID = Families.FamilyID)
Example 3
This is the fastest, but I'm worried about investing in it because I can't find any documentation on it. I don't even know what it's called. For want of a better term, we have been calling it an "anonymous query".
SELECT * FROM Families
LEFT JOIN
[SELECT * FROM Children WHERE Gender="m"]. AS AliasChildren
ON Families.FamilyID=AliasChildren.FamilyID
WHERE AliasChildren.FamilyID IS NULL
So my question is this:
What is this thing called in example 3?
Is it a "mainstream" feature of Access that
will be supported in the future?
Where can I find documentation on
it (this might be easier once I know what it's called)?
Thanks!
|
I think you could also try something like this:
SELECT *
FROM Families
WHERE Families.FamilyID IN (
SELECT Children.FamilyID
FROM Children
WHERE Children.Gender<>'m'
GROUP BY Children.FamilyID
)
| 1 |
SELECT * FROM Families WHERE Families.FamilyID
|
What are the pitfalls of buying a used car after an accident?
|
I have the option to buy a car that has been in an accident. There are alternatives, but within my budget the alternatives are usually older/have higher mileage. The seller is a local mechanic who did the restoration work and also showed pictures of the car before restoration. The damage was done to one of the front headlights and to the surrounding bits. The mechanic has convinced me that no damage was done to the internal carrying structure. He fixed the lights and did some paintwork restoration.
Problem: I read that people advice not to buy cars after the accident. This is my first car, so my experience is nonexistent.
Question: What are the cons against buying a car after the accident?
About the car: Opel Astra 2007 1.4 Petrol Manual Hatchback priced £2200, 1 prev owner, chain, 66K miles, 1 year MOT, 6 month tax
|
For what it's worth, I bought my first car (well, first that was actually mine) shortly after college for $100 with accident damage. Started with no knowledge or experience repairing cars. Took me a few months to get it in working shape, but it served me well for 4 years, and I learned a lot from it. However, it had damage to the frame that kept me from ever getting the alignment perfect, and so it burned through tires. This is something you might want to have checked by a professional on any vehicle that's had accident damage.
Anyway, the main thing I have to add on top of what others have said is that, if you can't afford to spend a lot of money and want to buy a car with potential problems as a way to save money, you might want to go the way I did and take "accident damage" over "engine problems". Even if you have to do some work on it later yourself, replacing components that might have been damaged in an accident is a lot easier for a beginner than doing a head gasket job or full engine or transmission rebuild (those issues being the other obvious ways you could get a dirt-cheap vehicle).
| 1 |
repairing a car with accident damage is a lot easier for a beginner .
|
is this possible: Amps feed joining a Regulated V line
|
As we all know linear regulators cannot handle a lot of amperage and tend to waste a lot of energy, so I was thinking if it is possible to create a regulated output then put the amperage after the regulation...
A slight demonstration of a schematic to show what I mean:
Is this possible? If yes is there a schematic I can look at? What should I look for?
sorry for the bad picture, I tried to make it better but failed..
--Edit--
I'm not trying get my circuit to work, just to convey the meaning.. I know this circuit won't work the way I want it, it is just an illustration.
|
I'm afraid Electricity Doesn't Work That Way. A linear regulator is basically a resistor that varies its resistance based on the load drawn, to always keep a consistent voltage. In parallel with that you've put some resistors (and note, multiple parallel resistors are equivalent to one resistor with 1/nth the resistance).
What will actually happen in your circuit is this: if the load is large, current will be drawn via your extra resistors until the voltage across them is such that the side closest to the load is at the voltage provided by the voltage regulator. Any additional current will be drawn through the voltage regulator. Together, your resistors and the voltage regulator will dissipate exactly as much waste power (and heat) as a regulator alone would.
If the load is small, the voltage across your resistors will be small, and the voltage on the output will thus be large - up to the input voltage minus the diode's forward voltage, at no load - and the linear regulator will shut off completely, vainly trying to reduce the voltage by limiting the current through it.
Thus, what you've created is a sort of "lower bound voltage regulator", which provides a voltage between the input voltage and the set voltage at low currents, and exactly the set voltage at high currents, up to the limit of what your regulator plus resistors can dissipate.
There are well established solutions for converting voltages at high current with low waste, called switching regulators. They work by repeatedly charging up an inductor - a coil of wire - and discharging it into a capacitor, which serves to convert from one voltage to another with minimal waste.
| 0.666667 |
a linear regulator is a resistor that varies its resistance based on the load drawn
|
Exception when Importing .csv file from CLI
|
I am able to import my .csv file using Apex Data Loader. When I try importing the same file from CLI I am getting an exception attached in the file.
When the file contents are copied into a new csv file and try importing this new .csv file, this succeeds.
Also If I open my .csv file, click on save, a pop-up comes up "MyFile.csv may contain features that are not compatible with CSV(Comma Delimited).
Do you want to keep the workbook in this format? " And if I click on "Yes" or "No"and close the file without saving it and then try to upload the same file.
The data gets uploaded.
This is something weird and I am not able to get any logic out of it..
This is the error msg i am getting.
|
When you open a CSV file in Excel and click on save, the "Yes" will save the file as CSV again and "No" will prompt you to save the file as XLSX. Excel does save on this "Yes" even though closing the file will prompt you to save again.
Therefore, based on your description, you did save the CSV with Excel, and that will change the formatting of the file contents.
Start over and open your original file with Excel and choose SaveAs to save the file as CSV with a new name.
Use an editor like notepad++, not notepad, and open both files.
You will likely see formatting differences between the files like missing double quotes, changed line terminations, etc.
Based on what you find, you can change the formatting on the initial file and it will probably work.
If formatting isn't the problem, you may need to look for other issues like extra double quotes inside quoted text fields, for one example.
| 0.888889 |
Open a CSV file in Excel and click on save, the "Yes" will save the file as CSV again and "No"
|
Should I have one unified design between mobile and desktop?
|
With a website I'm building, I'm wondering if I should combine the experiences between platforms together. For example, I'm wondering if I should keep this for both mobile and desktop. Here are some examples
I'm mainly wondering about the header. Is it bad to keep a more mobile like design (meaning slide menus, e.t.c.) on desktop, or should I utilize more of the space that mobile would not have?
|
First off all, I appreciate that you seem to design your responsive web with a mobile-first approach (that's how I perceive it anyway).
As Imperative has already stated, consistency is generally a good thing. However, the mobile-sized interface might still be come through as consistent with the desktop-sized ditto even though they don't share the exact same navigation pattern. For instance branding elements, graphical profile, copy, artwork and information architecture might keep it together just fine. Especially important is that the IA is, at least, very similar for the users to find their way around the site. When the content is grouped and structured the same way, a user that is familiar with one of the platforms but new to the second will know what to look for and have a hunch of how too, which helps a lot.
The off-canvas drawer menu is (obviously) a solution that partially solves a common mobile interface problem: the deficit of real estate. But that's a problem that rarely applies when it comes to desktop interfaces. Consistency is valuable, but should you be consistent between your own interfaces, or with the standards for the respective platforms they're being used in?
Off-canvas drawer for mobile:
Access to all top level navigation items in one place
Robust in a sense that new items can be added in infinity (can be a curse too:)
Menu button is in a convenient position (even though it's usually in the "hard" corner)
Off-canvas for desktop:
I guess Fitt's law still applies, and the expedition up the north-western corner of the screen can actually be quite long. A drop in efficiency?
You don't always want to fill the entire width with content as the user can use a very wide screen on a PC, which can make the positioning of the menu and its button really awkward, and actually even hard to see.
A button in the corner can interfere with hot corners, or rather, the other way around.
An extra click, that could have been avoided, is added to reach a menu item.
The menu items are obscured until the user has visited the menu, when they could have been displayed directly.
Based on the arguments above, I would recommend a different pattern than the drawer menu for the desktop site.
| 1 |
Consecvent web design with mobile-first approach
|
Initial state in F# List.scan
|
I have a simple problem and as I'm an F# newbie I can't seem to figure out how to do this. I have a list of tuples:
let l = [ (a, 2); (b, 3); (c, 2); (d, 6) ]
that I want to transform into this:
let r = [ (a, 2); (b, 5); (c, 7); (d, 13) ]
This simply adds the values of the second element in each tuple: 2 + 3 + 2 + 6. The objects a, b, c and d are complex objects that I simply want to keep.
I thought I should use List.scan for this. It takes a list, threads an accumulator through the computation and returns a list:
let r = l |> List.scan (fun (_, s) (o, i) -> (o, s + i)) (??, 0) |> List.tail
But I don't know what to fill in for the question marks. I'm not interested in the initial state except for the 0. And I don't want to specify some 'empty' instance of the first tuple element.
Or is there a simpler way of doing this?
|
You can use first element as an initial state:
let l = [ ("a", 2); ("b", 3); ("c", 2); ("d", 6) ]
let x::xs = l
let res = (x, xs) ||> List.scan (fun (_, x) (o, n) -> o, x + n) // [("a", 2); ("b", 5); ("c", 7); ("d", 13)]
Special case with empty list should be processed separately
| 0.555556 |
First element as initial state: let l = [ ("a", 2); ("b", 3); ("c", 2; ("d",
|
Traveling into Brazil from Bolivia by land/bus
|
I plan on travelling from Bolivia into Western Brazil (Caceres or Cuiaba in Mato Grosso) from Santa Cruz, Bolivia. I have heard that there are a couple of border cities into which to pass over to Brazil.
Does anyone know which is the safest/easiest way to go through?
If so, is travelling by bus the only way? I've heard there's also a train that leaves from Santa Cruz to Brazil, via Corumba? Is this currently running? Does anyone have experience travelling to Brazil like this?
|
RometoRio shows a route for both bus and train. Several, in fact. Each varies by price, and time, for obvious reasons, and it's shown alongside some flight prices as well, if that's a possible consideration.
The bus option looks brutal, however, as they're only finding one that goes via Argentina(!), taking 3 days. The train, on the other hand looks more doable for 43 hours, and looks to be split about 1/3 train 2/3 bus.
There is also a flight option shown.
Bolivian buses, from experience, are a far 'rougher' affair than Argentinian/Chilean/Peruvian buses - I wouldn't worry about several days on those, but in Bolivia, it may be a different thing to consider. Personal preference and all that.
Good luck, let us know what you find!
| 1 |
RometoRio shows a route for both bus and train in Bolivia .
|
Engine Code P1312 on 2001 Saab 9-3
|
I have replaced to brand new spark plugs.
After some research, it seems that the problem might be the direct ignition cassette.
Could there be other possibilities?
Thanks
|
Are you using the correct spark plugs, or aftermarket? OEM makes a huge difference in certain vehicle brands.
| 1 |
Are you using the correct spark plugs?
|
Macro that follows a link and downloads the table into a new sheet
|
I am a geologist working for a small oil company in Louisiana. I constitute our tech department, and unfortunately my experience with coding is quite limited. I have used very basic vba coding in the past, but I dont code that much in my daily job, so I have forgotten most of it.
The louisiana dnr keeps amazing records for every single oil well drilled in the state and all of these records are located at www.Sonris.com. Part of these records are the production records for each well. I would like to create a macro that follows a given url and downloads the table found on the URL (aka the production records). After it downloads the file, I would like it to put the table in a new sheet and then to name this sheet based on the well name.
I have fooled around with the retrieve data from web function, however I cannot make the function dynamic enough. I need the code to copy the hyperlink data found in a cell. Currently, the code just follows the hyperlink that I copy and paste while recording the macro.
Any help would be appreciated
Sincerely,
Josiah
Below is the code generated;
Sub Macro2()
'
' Macro2 Macro
' attempt with multiple well to look at code instead of 1 well
'
'
Range("E27").Select
ActiveWorkbook.Worksheets.Add
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=159392" _
, Destination:=Range("$A$1"))
.Name = "cart_con_wellinfo2?p_WSN=159392"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "1,11"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Sheets("Sheet1").Select
End Sub
|
With all of the methods available to scrub external data, many users forget that you can open a web page full of tables with nothing more than a valid URL and File ► Open. I'm posting the code here but I will also supply a link to a working sample workbook that took ~ 2 minutes to gather the full web page data from 14 sequentially numbered WSN (web serial number) pages. Your own results may vary.
Option Explicit
Public Const csURL As String = "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=×WSN×"
Sub Gather_Well_Data()
Dim rw As Long, lr As Long, w As Long, wsn As String, wb As Workbook
On Error GoTo Fìn
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With ThisWorkbook.Sheets("WSNs")
lr = .Cells(Rows.Count, 1).End(xlUp).Row
For rw = 2 To lr
.Cells(rw, 2) = 0
For w = 1 To .Parent.Sheets.Count
If .Parent.Sheets(w).Name = CStr(.Cells(rw, 1).Value) Then
.Parent.Sheets(w).Delete
Exit For
End If
Next w
wsn = Replace(csURL, "×WSN×", .Cells(rw, 1).Value)
Set wb = Workbooks.Open(Filename:=wsn, ReadOnly:=True, addtomru:=False)
wb.Sheets(1).Range("A1:A3").Font.Size = 12
wb.Sheets(1).Copy After:=.Parent.Sheets(.Parent.Sheets.Count)
.Parent.Sheets(.Parent.Sheets.Count).Name = .Cells(rw, 1).Value
wb.Close savechanges:=False
Set wb = Nothing
.Cells(rw, 2) = 1
Application.ScreenUpdating = True
Application.ScreenUpdating = False
.Parent.Save
Next rw
.Activate
End With
Fìn:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
The list of WSN identifiers are in the WSNs worksheet starting in column 2. Run the macro by tapping Alt+F8 to open the Macros dialog and Run the Gather_Well_Data macro. When it is complete, you will have a workbook filled with worksheets identified by the WSNs similar to below.
The sample workbook is on my public DropBox at:
LA_WSN_Data.xlsb
| 0.888889 |
Open a web page full of tables with nothing more than a valid URL and File Open
|
Getting field data from a Bento database using Applescript
|
I'm having problems getting the field values out of a Bento database using Applescript:
I'mn using the following code to get at the entries but I'm not able to get at the cells or fields associated with the entries. Can anyone point me in the right direction:
tell application "Bento"
repeat with i from 1 to count of libraries
set theName to name of library i
log theName
if theName is equal to "Reconnaissance site report" then
log "The library has been found"
set theLibraryProperties to properties of library i
log theLibraryProperties
tell library i
repeat with j from 1 to count of entries
set theEntryName to id of entry j
set theEntryProperties to properties of entry j
log theEntryName
log theEntryProperties
end repeat
end tell
end if
end repeat
end tell
|
Bento's scripting dictionary is pretty thin. It looks like field, entries and cells all are in the Bento 3 scripting dictionary - so it's hard to tell if they have been there all along or are added for future use.
I'm not really skilled at debugging AppleScript so I can't see any errors with the code you posted.
Have you tried looping over _source_items_ for fields and cells? The dictionary seems to indicate that the data lies there and not as easily accessed from a collection. That and a lot of logging might make up for the lack of an interactive tool to query the scripting bridge.
Scripting is a feature differentiator between Bento and the more full featured Filemaker product from the same people.
Have you tried using sqlite3 to just read the database at ~/Library/Application\ Support/Bento/bento.bentodb/Contents/Resources/Database ?
The schema and tables are all open to whatever SQL tool you like. I hope it's just a matter of constructing the right query if you prefer AppleScript (and there is a lot to prefer about it over command line scripting).
| 0.888889 |
Bento's scripting dictionary is pretty thin .
|
What is my lcd density?
|
How can I figure out what is my tablet's lcd screen density.
It is a cheapy one with no official site...
Is there any settings option I could check to see the display resolution configurations?
Is there any other way for it?
|
Even a cheap tablet with no official specs normally mentions the screen resolution on the box, didn't yours?
If not, then you could visit a web page like http://www.whatismyscreenresolution.com/ (there are many other similar websites out there) or install an app like Android System Info that will tell you your resolution as well as your DPI.
The DPI is just a measurement of how many pixels there are on an inch of your screen, so if you know your screen resolution, you can measure the size of your screen and calculate the DPI from there to get the actual density.
| 0.888889 |
Whatismyscreenresolution.com is a measurement of how many pixels on an inch of screen
|
How do different tissue culture matrices affect background in fluorescent microscopy?
|
In response to my previous question, I've been reading up a little bit on poly-D-lysine, Collagen I, Collagen IV, laminin, and other tissue culture coatings that promote cell adhesion. I've always assumed that anything other than standard TC-treated plastic or glass would significantly increase background, but perhaps my views on background fluorescence are a little outdated. Does anybody have experience with these in a fluorescent microscopy/high-throughput screening environment?
Specifically in my case, I'm looking at endocytosis and trafficking of a labeled protein into the lysosome. I'm labeling the protein with the pH-dependent dye pHrodoTM from Molecular Probes, which supposedly has very little fluorescence at neutral pH, but becomes very bright as the pH drops when endocytic vesicles become lysosomes. This theoretically means that a final wash step is not needed, but with a matrix coating on the plates I'm worried about background.
So, what is the current thinking as far as background fluorescence of the various TC matrices is concerned? Does the background come from the matrix itself, or by the fluorescent dye becoming adsorbed to it? Is it wavelength-dependent? Fortunately I may not be stuck with my poorly-adhering cells, and I may not need supplemental matrix at all in the end, but I still want a better understanding of how it works.
|
Extracellular matrix (ECM) fluoresces, especially Collagen and Laminin. The maximum is in the DAPI and FITC channels and the fluorescence becomes weaker towards longer wavelengths. However, since the coat on the TC flasks is very thin, I would not expect this to be a problem. The best thing is just to try it. There is also a quite famous document available which might be of help:
Autofluorescence: Causes and Cures
| 1 |
Autofluorescence: Causes and Cures
|
Of using /usr/bin/env as Sha-bang
|
I would like to know whether it is good practice, according to you, to use this she-bang:
#!/usr/bin/env bash
instead of
#!/bin/bash
This article seems to advocate for the use of /usr/bin/env but when I use it, skepticism appears.
What is your opinion?
|
env is only useful if the script is going to be used on multiple systems where the location of the binaries can vary. If the script is only used on a single system or in a homogeneous network then it's not necessary.
| 0.5 |
env is only used on multiple systems where the location of binaries can vary
|
How do you open a port on a cisco firewall?
|
I'm sure this is simple but how do you open a port on a cisco firewall?
I want to use fixup to alias a port and then actually open the port. But I don't know how to do it. Thank you.
|
From the "priviledged configuration" command prompt:
static (inside_interface_name,outside_interface_name) (external ip address) (internal ip address)
access-list (access list name) ("permit" or "deny") (tcp or udp) any host (external_ip) eq (port number)
access-group (access list name) in interface (outside_interface)
Simple, right?
Good old Cisco.
The "Static" command tells the pix that the internal machine is attached to the external address, so that it will route traffic accordingly.
The "access-list" command tells the pix that you're creating a new access-list, you're allowing or denying "any" external machine to talk to your new external address on (port number) using tcp or udp packets.
The access-group command associates that access-list with an interface on the pix.
Here is a link to Cisco's Pix Command Reference for Commands starting with A. You can refer to that, if you need to. There is an example command under "access-group".
To wholly open a port for any machine you should do:
access-list open_port_whatever permit tcp any any eq (port number)
access-group open_port_whatever in interface (outside)
| 1 |
static access-list (access list name) in interface (outside_interface)
|
Changing PhD topic and effect on career
|
I'm a PhD student in my third year (4-6 is common in my country) and seriously consider abandoning my current topic.
The new topic is in the same general field (CS related), yet in a vastly different domain and would need a quite different methods. My advisor suggested this switch, he could keep me funded in both cases, yet probably better with the new topic.
Arguments for switching are both personal interest in the new topic (it's recently trending, I was interested from the beginning, yet few positions were available) and lack of progress in the current area:
I could produce some publications, yet not up to my advisors expectations (should be easier with the new topic, given the impact factors of the journals my advisor suggested)
For the last 6-8 month I made barely any progress (lots of failed experiments)
I would probably have to abandon my current methods anyway due to 1./2., so half a year or so will be lost learning new methods no matter how I decide
Yet I shy away from switching, mainly due to already being quite old (combination of personal problems and a switch of my major as an undergraduate) and fearing how my C.V. would look if I did take about a year longer and had this second switch...
Thanks for any input.
|
Most people won't care.
The time to PhD isn't really considered all that important unless it's highly anomalous (much shorter or longer than standard), and if you get good publications out of it, nobody is going to make a big deal about switching topics. It happens for all kinds of reasons—funding changes, or because the original project doesn't pan out for whatever reason (technical or logistical).
It will also not impact your career much, unless you're planning to continue studying one of those areas as your post-graduation career. Again, the overall quality tends to matter much more than the actual topic in most cases (particularly if you're moving into a different area from your graduate work).
| 0.777778 |
The time to PhD isn't really considered all that important unless it's highly anomalous
|
How to synchronize actions like jump in multiplayer?
|
I am a newbie game developer and I have been researching about multiplayer games. I observed that there's always some latency, the players always get updates from past actions. But there are techniques like dead reckoning to handle the latency. I can predict the movement and make movements smooth. But how would I make actions synchronize like jumping, stopped walking, etc.
Suppose, client A was moving, he was at 100m at 10.2 time with 100m/sec velocity and sended this information. Client B would receive this information somewhat later, let it be 10.4. So at client B, I can use prediction and place client A at 120m. But what if, client made a jump at 110m at 10.3. I can't predict that and since I have been using prediction I can't show client A jump in past.
I may deal with this problem by not sending jump action at all. But what if my game has some voids where players can fall and die. So, If I don't sync jump actions, other players will observe that one player was running then he falls in void and then again appear on the screen destroying the visual engagement.
Jump is just an example, there might many scenarios where prediction can't work. So, How do deal with them. One such example can be Multiplayer Online battle arena games like Awesomenauts.
|
Dead reckoning may not be the best idea in this case; you should do entity interpolation (effectively rendering the other players in the past, which always gives you real, valid positions). I've written about this with much more detail here. Whether or not seeing players slightly in the past is acceptable or not depends on the details of what you're trying to do.
| 0.888889 |
Is it acceptable to see players slightly in the past?
|
Looking up for an item in a list and different table styles in iOS
|
I have a settings view with a grouped table. One of the cells of such table is intended to show a very long list of items from where I want the user to select one. Due to the length of the list, I need to provide a way to make easier to find a certain item.
One of the options I think there are, is to show letters of alphabet as indexes at the right side of a plain table. Since my first table is a grouped one, my navigation hierarchy would be then like this:
Would it be inconsistent to navigate from a grouped table to a plain table? If so, could somebody give an existing example? I didn't find anything related to this in iOS Human Interface Guidelines, maybe it is described somewhere else and this navigation pattern breaks the guidelines.
Another option could be having a search bar. Can a search bar be used in both a plain table and a grouped table? The existing example of such bar I found is in Contacts app and it is a plain table. In a plain table, could both an alphabet index and a search bar be shown?
|
IDEA 1: Grouping
Can you group items in the second table (plain table) further? If so, the interface is much simplified.
IDEA 2: Filtering
If IDEA 1 is impossible to follow, then you can do another thing. Implement a filter feature to the long list. Just place an icon at the top of the list. Clicking on it should bring a new page. Provide checkboxes, sliders, or some other facility according to your situation. Avoid the search bar if possible -- users don't know what words you have used in your list.
IDEA 3: Sorting
If IDEA 2 fails, then you must sort and present the list manually. Think about the options again and decide which are the most used options? Guess what most users want. Show those options first!
IDEA 4: Visual cues
Use icons or pictures relating to the actions/properties of the items in the list. This allows easy scanning.
| 0.833333 |
IDEA 1: Grouping Can you group items in the second table further?
|
Automatic internationalization in Java
|
I have an issue with automatic internationalization in java, using netbeans. In actionListener I am chaging locale with this:
String s = (String)langBox.getSelectedItem();
switch(s){
case "Čeština":
BP_evolution.language = "cs";
BP_evolution.currentLocale = new Locale(BP_evolution.language);
break;
case "English":
BP_evolution.language = "en";
BP_evolution.currentLocale = new Locale(BP_evolution.language);
break;
}
Actually, the issue is, that I don't know what function should I call for switching language in my application. I am using Java SE and Swing. Like I already said, ResourceBundle has been created automatically.
|
My issue with this has been resolved by SwingWorkers. When I put the function of switching languages, it started to work.
You can read about it here -> java doc
Problem was probably that main thread stucked with running GUI itself and it was not able to do anything else.
| 1 |
SwingWorkers solved my problem with switching languages
|
Reading File From Network Location
|
I am having Bunch of Files in A folder which is shared on Network Drive . I am trying to Access those Files into my Code . But It is giving an error:
System.IO.DirectoryNotFoundException was unhandled by user code
Fname = txtwbs.Text;
DirectoryInfo objDir = new DirectoryInfo("Y:\\");
_xmlpath = objDir + "\\" + Fname + "\\" + Fname + ".xml";
if (File.Exists(_xmlpath ))
{
reader(_xmlpath);
}
I have Also used:
file = fopen("\\\\10.0.2.20\\smartjobs\\Eto\\"+Fname);
I am Able to Read File from My Local PC But it is giving Exception Only for Network Location .Please let me know how can I read File From Network Shared Location .
And Also How Can I Make A tree view of Folders into Asp.net Web Application .
Directory Structure is Like that
\\10.0.2.20\Smartjobs\Eto\
this is Parent Directory It is congaing Nos of Folder having XML Documents.
|
You may have map the shared directory as a user, but you forget that the asp.net is running under the account of the pool, and there you do not have connect the y:\ with the shared directory.
The next think that you can do is to direct try to connect via the network shared name, eg: \\SharedCom\fulldir\file.xml
| 1 |
Connect the shared directory via the network shared name
|
Images give 404 after changing default domain
|
Never encountered this issue before. So I've just moved a site for a client to another server and for some reason all images give me a 404 when I change the default domain in the database (siteurl and home). CSS, JS and other files are linked correctly - it seems there's something affecting the uploads folder but I can't pinpoint what it is. Any ideas?
|
You will want to run a find-and-replace script across the database to update all URLs to reflect the new domain. Just because you change the WordPress settings doesn't mean the content stored in the database has been updated with the new domain! I've had good luck with the Velvet Blues Update URLs plugin but you can also do this type of find and replace update using phpMyAdmin or other similar database tools.
| 1 |
Find-and-replace script to update URLs to reflect new domain
|
add custom citation that differs in format than the rest
|
This has been bugging me for quite some time now but can't find a nice way to work it out.
I have a list of citations that follow the regular author. Year. Title. Journal. Volume: Pages layout. I have to cite a legal document (Water framework directive). How do I go about this, as the paper has no authors, journals, pages...
I would like it to appear in the text as
... V Sloveniji smo leta 2000 sprejeli
Vodno direktivo (2000/60/EC) (v
nadaljevanju: VD), ki v evropskem
prostoru enotno ureja politiko
upravljanja površinskih in podzemnih
celinskih voda, vključno s somornico
in morjem....
and in the references as
Ter Braak, C. J. F., Verdonschot, P. F. M. 1995. Canonical correspondence analysis and related multivariate methods in aquatic ecology. Aquatic Sciences 57(3): 255–289.
Vodna direktiva (2000/60/EC)
Wickham, H. 2009. ggplot2: elegant graphics for data analysis. Springer New York. ISBN 978-0-387-98140-6.
How should I specify my BibTeX source to achieve this?
EDIT
This is a more or less minimal working example. Style file can be found here, and the bib file here.
\documentclass{article}
\usepackage{natbib}
\begin{document}
As specified in \citet{vd} and \citep{Fraschetti2006} \dots
\bibliographystyle{custom_style}
\bibliography{test}
\end{document}
EDIT 2
A workaround that worked for me (for now). The four questionmarks in question (hehe) were the result of missing year in the bib file. I have modified the custom_style.bst from
FUNCTION {format.date}
{ year "year" bibinfo.check duplicate$ empty$
{
"empty year in " cite$ * "; set to ????" * warning$
pop$ "????"
}
'skip$
if$
extra.label *
}
to
FUNCTION {format.date}
{ year "year" bibinfo.check duplicate$ empty$
{
"empty year in " cite$ * "; set to " * warning$
pop$ ""
}
'skip$
if$
extra.label *
}
|
I suspect that even legal documents should be represented by a BibTeX entry with more than one field (and especially with a year field if one uses an author-year-style), but here goes.
I used the author instead of the title field because BibTeX otherwise would typeset the label V00 in the text.
The second pair of curly braces prevents BibTeX from breaking the "author" down in first name and last name.
\documentclass{article}
\usepackage{natbib}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@misc{V00,
author = {{\textit{Vodna direktiva (2000/60/EC)}}},
}
\end{filecontents}
\begin{document}
As specified in \citet{V00} \dots
\bibliographystyle{plainnat}
\bibliography{\jobname}
\end{document}
| 0.777778 |
BibTeX entry with more than one field if author-year-style
|
Lychrel calculator (Project Euler 55)
|
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers,
like 196, never produce a palindrome. A number that never forms a
palindrome through the reverse and add process is called a Lychrel
number. Due to the theoretical nature of these numbers, and for the
purpose of this problem, we shall assume that a number is Lychrel
until proven otherwise. In addition you are given that for every
number below ten-thousand, it will either (i) become a palindrome in
less than fifty iterations, or, (ii) no one, with all the computing
power that exists, has managed so far to map it to a palindrome. In
fact, 10677 is the first number to be shown to require over fifty
iterations before producing a palindrome: 4668731596684224866951378664
(53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves
Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
This is my solution:
from datetime import datetime
candidates = []
def reverse(number):
''' Returns the reverse order of an integer,
for example: reverse(123) returns the integer 321 '''
number = str(number)
return int(number[::-1])
def is_lychrel(number):
''' Returns True if 'number' is a lychrel candidate,
but works only with numbers from 1 to 10000 '''
iterated = number + reverse(number)
for i in range(25):
rev_iterated = reverse(iterated)
if iterated != rev_iterated:
iterated = iterated + rev_iterated
else:
return False
return True
if __name__ == '__main__':
start_time = datetime.now()
for number in range(10001):
if is_lychrel(number):
candidates.append(number)
time = datetime.now() - start_time # To get the time of the calculation
print('In {} were found {} lychrel candidates'.format(time, len(candidates)))
print(' '.join(map(str, candidates)), 'are candidates.')
suml = input('Press ENTER to close ')
On my PC (with Intel Atom 2GHz), I got it with .4 seconds. Could you offer suggestions on making it run faster?
|
1. Comments on your code
Python has a built-in module, timeit, for measuring the execution time of small code snippets. So there is no need for all that fussing about with datetime.
Project Euler problem 55 says:
you are given that for every number below ten thousand, it will either (i) become a palindrome in less than fifty iterations
but your code only tries 25 iterations. It happens to be the case that 25 iterations are enough in this case, but how did you figure that out? If you had a mathematical proof that showed that 25 iterations were enough, then that would be fair enough, but I suspect that in fact you re-ran the program with different values for the count of iterations until you found that smallest one that produces the right answer. This seems like cheating to me: if you are willing to do that, why not just replace the whole program with:
print(answer)
which would be even faster?
The problem statement asks:
How many Lychrel numbers are there below ten-thousand?
but you test range(10001) which is off by one. Luckily for you, 10,000 is not a Lychrel number, so this doesn't lead to an error.
You've made candidates into a global variable, and run some of your code at top level. This makes it hard to test your program from the interactive interpreter. You need something like this:
def problem55(n):
"""Return a list of Lychrel candidates below n."""
candidates = []
for number in range(n):
if is_lychrel(number):
candidates.append(number)
return candidates
and then you can test it like this:
>>> from timeit import timeit
>>> timeit(lambda:problem55(10000), number=100)
8.279778157011606
2. Speeding it up
The problem statement only asks how many Lychrel numbers there are, so there is no need to construct a list of them.
Function calls in Python are moderately expensive, so you can save some time by inlining them. This leads to an implementation like this:
def problem55_1(n, m):
"""Return the count of numbers below n that do not lead to a
palindrome after m iterations of reversal and addition.
"""
count = 0
for i in range(n):
r = int(str(i)[::-1])
for _ in range(m):
i += r
r = int(str(i)[::-1])
if i == r:
break
else:
count += 1
return count
which is about 16% faster than yours:
>>> timeit(lambda:problem55_1(10000, 50), number=100)
6.93482669594232
Janne suggested that you could speed things up by caching the numbers already found to be Lychrel and non-Lychrel, and you replied:
doing that is going to require more conditions and probably is going to be the same running time or even worse
which is a bit of a defeatist attitude. Certainly the code gets more complex when you add caching, but it's not a priori obvious whether this costs more than it saves, or saves more than it costs. The best way to find out is to knuckle down and try it:
def problem55_2(n, m):
"""Return the count of numbers below n that do not lead to a
palindrome after m iterations of reversal and addition.
"""
lychrel = set()
nonlychrel = set()
count = 0
for i in range(n):
j = i
if i in lychrel:
count += 1
continue
stack = [i]
r = int(str(i)[::-1])
for _ in range(m):
i += r
if i in lychrel:
count += 1
lychrel.update(stack)
break
if i in nonlychrel:
nonlychrel.update(stack)
break
stack.append(i)
r = int(str(i)[::-1])
if i == r:
nonlychrel.update(stack)
break
else:
count += 1
lychrel.update(stack)
return count
I find that this is about twice as fast as your code:
>>> timeit(lambda:problem55_2(10000, 50), number=100)
3.935654202941805
One final tweak from me. Now that we are caching, the order in which we check numbers for the Lychrel property matters. As you iterate the reverse-and-add process, the numbers get bigger. So if we start with the larger numbers and proceed downwards, then we are more likely to get cache hits. So I tried replacing the line:
for i in range(n):
with
for i in range(n - 1, -1, -1):
and got a further small speedup:
>>> timeit(lambda:problem55_3(10000, 50), number=100)
3.800810826011002
| 1 |
How many Lychrel numbers are there below tenthousand?
|
MS-Access VBA Date() works on one PC but not others
|
I am designing my first database from the ground up and I have learned a lot in the last few weeks. One thing that has been eating at me though is that on my login page I have a simple unbound text box with its control source as =Date().
This works perfectly well on the computer I use most days, but any other computer in the facility I am working out of displays #NAME? instead of the date.
I have tried changing to =Now() and it works fine on all computers. Apparently only =Date() has issues. If the fields control source is changed back to =Date() I am informed that The function you entered can't be used in this expression.
I have checked the MS-Access versions and tried on a machines with and without access.
I really need Date() to work because it is used elsewhere in more vital areas of my code and I may not be able to use Now() in its place. Any ideas as to why this may not work on any PC besides my own?
|
I suspect the issue is user's region and language settings for the date. I noticed this when I changed computers and my files wouldn't save anymore due to the slashes in the date. You should try the format() function so that your dates always have the same format and can be used across machines independent of the user's settings.
Sub Foo()
Debug.Print Date
Debug.Print format(Date, "yyyy-mm-dd")
End Sub
Output
7/23/2015
2015-07-23
| 0.888889 |
Debug.Print Dates
|
Tags to Post-ID mysql query. Tag Search
|
Im trying to implement a tag-based search. When i specify certain tags, tagged posts will be searched and the post-id will be displayed that matches the searchcriteria.
Currently it only works for a single tag.
$query = "SELECT DISTINCT $wpdb->posts.ID FROM $wpdb->terms
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id)
LEFT JOIN $wpdb->term_relationships ON ($wpdb->terms.term_id = $wpdb->term_relationships.term_taxonomy_id)
LEFT JOIN $wpdb->posts ON ($wpdb->term_relationships.object_id = $wpdb->posts.ID)
WHERE $wpdb->term_taxonomy.taxonomy = 'post_tag' " . $substring;
Substring looks like following:
$substring = "AND $wpdb->terms.slug IN ('tag1','tag2')"
And here is the problem. It does not look for single posts that match all criteria. Instead it 'collects' all posts with all tags searched.
For example:
// postid1 -> tag1
// postid2 -> tag2
// postid3 -> tag1, tag2
$substring = "AND $wpdb->terms.slug IN ('tag1')"
//Output: postid1, postid3 - - - CORRECT
$substring = "AND $wpdb->terms.slug IN ('tag1','tag2')"
//Output: postid1, postid2, postid3 - - -WRONG!
//Expected: postid3
So far i have no idea howto solve it in a single mysql query. Maybe im missing something.
Thanks for your help in advance.
|
These are normal IN mechanics - it matches anything in set, not all of set combined.
Type of match you want is called tag_slug__and in WP query arguments. You can see code that generates SQL for it in source of WP_Query->&get_posts() method.
Resulting SQL is like this:
SELECT p.ID
FROM wp_posts p
INNER JOIN wp_term_relationships tr ON (p.ID = tr.object_id)
INNER JOIN wp_term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
INNER JOIN wp_terms t ON (tt.term_id = t.term_id)
WHERE tt.taxonomy = 'post_tag'
AND t.slug IN ('is', 'filler')
GROUP BY p.ID HAVING count(p.ID) = 2
| 0.777778 |
SELECT p.ID FROM wp_posts
|
How to make a photo background fully white?
|
I have photos of a product and I would like to create a white background behind it. Like it is done in this example:
I have tried playing with levels and the brightness but that also messes up the product itself. How do i do this?
|
You don't do it in Photoshop. You start in the "studio".
This website explains a lot of jewelry photography.
When photographing pearls, by using only one light source positioned above, the pearls will appear rounder with more dimension.
Assuming you don't want to photograph pearls, take with you that they are using a single light on top, with a lightbox all around it. If you don't have a flash with a diffuser slightly larger than your subject, you could use some other lamp. If you don't have a lightbox, you could buy one (cheap), or you can use some white paper to reflect the light onto the subject.
Use a white acrylic sheet as your surface. (Or paper). Adjust your exposure so that the background is already almost overexposed.
| 1 |
When photographing pearls, use only one light on top, with a lightbox all around it.
|
How to 'select' menu items that also link to deeper items?
|
Currently I'm working on a navigation that doesn't take up too much screen real-estate. I came up with a pseudo off-canvas navigation with stacked menus.
A user can assign nodes to a product. This is the current state of the wireframe; user chose Add nodes. Now he want's to manually search for a specific node 1 (1. Browse Nodes in wireframe). The user now can select a node to add to product 2 or go 1 level deeper into the navigation 3. and 4.. If you click on a node-link the children off that node will slide-in and stack on top of the current menu. There is also a back option to parent (second wireframe).
I deliberately chose checkboxes, links and button as elements because that's their purpose; I wireframed there functionality not a design-solution. Normally I like selecting text/label also checks a checkbox, but now the label is a link too. A user could a) select that node to add to product, Or b) select node to navigate to children of that node.
I could argue if it makes sense that a node will act is a leaf and a branch. A don't have any real data about how customers assign nodes. I can't wait for this input. Currently functionality of the system is that a node could be a leaf and a branch. So asking real users is no option. Maybe in the future (months from now).
How to convert this into an intuitive navigation?
|
Something like this;
Hovering above nodes will reveal add-button. Clicking on the add-button will set node as 'checked'. Clicking on node-text or clicking on arrow will slide on 1 level deeper in the nav. EDIT: 'Done-button' functions to finishes the task 'add nodes' Or click outside the menu (eg in main-section) will hide menu. Good plan?
| 0.777778 |
Hovering above nodes will reveal add-button
|
Is there a way to read the columns in a shapefile / layer without converting it first to an MDB file?
|
My shapefile has a number of fields, like roadname, and street number. Is there a way to get at these without converting the shapefile first into a featureclass (mdb)? Sometimes the conversion is a time consuming operation.
I'm using ArcEngine 10 C# with VS2010
|
Are you opposed to using open source libraries? There are quite a few .NET options for dealing with Shapefiles. I've had very good results with the OGR (C# bindings) and SharpMap. A quick search on google yields many more options.
| 1 |
Are you opposed to using open source libraries
|
Footnote in booktabs package
|
I wish to add a footnote somewhere in a table. I am using booktabs package. I wrote the footnote using \footnote. It is showing symbol 1 inside a small box but it is not showing the footnote anywhere.
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath,amsthm,amsfonts,latexsym,amscd,amssymb,mathrsfs,hyperref,textcomp,booktabs}
We have already discussed about completeness.
\begin{table}[ht]
\begin{minipage}{\linewidth}
\def\arraystretch{1.4}\tabcolsep=2pt\small\centering
\begin{tabular}{@{} l l l l l @{}}\toprule
Order&Group $G$&Gap Id&Presentation&$\Gamma_d(G)$\footnote{We shall exclude the cases $d=1,|G|$, since $\Gamma_1(G)=K_1=\Gamma_{|G|}(G)$}\\ \midrule
1&$C_1$&1(1)&$\langle a;a^1\rangle$&$\Gamma_1(C_1)=K_1$ \\
2&$C_2$&2(1)&$\langle a;a^2\rangle$&$\Gamma_1(C_2)=\Gamma_2(C_2)=K_1$ \\
3&$C_3$&3(1)&$\langle a;a^3\rangle$&$\Gamma_1(C_3)=\Gamma_3(C_3)=K_1$ \\
4&$C_4$&4(1)&$\langle a;a^4\rangle$&$\Gamma_1(C_4)=\Gamma_2(C_4)=\Gamma_4(C_4)=K_1$\\
&$C_2\times C_2$&2(2)&$\langle a,b;a^2,b^2,aba^{-1}b^{-1}\rangle$&$\Gamma_1(G)=\Gamma_4(G)=K_1,\Gamma_2(G)=K_3$\\
5&$C_5$&5(1)&$\langle a;a^5\rangle$&$\Gamma_1(C_5)=\Gamma_5(C_5)=K_1$\\ \bottomrule
\end{tabular}
\end{minipage}
\caption{Abelian groups}
\end{table}
This table shows $\Gamma_d(G)$ for some abelian groups.
\end{document}
This is showing the line This table shows $\Gamma_d(G)$ for some abelian groups. before the table and table is showing on next page. Also i want the symbol * or \dagger at the place of a and I do not want the line before footnote.
|
Use a minipage for the tabular. However, your tabuloar is too wide and, of course, you shouldn't use too many lines. Without it it makes it more readable:
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath,amsthm,amsfonts,latexsym,amscd,amssymb,mathrsfs,hyperref,textcomp,booktabs}
\hypersetup{colorlinks}
\begin{document}
\begin{table}[ht]
\centering
\begin{minipage}{\linewidth}
\begin{tabular}{|p{0.9cm}|p{1.6cm}|p{1.6cm}|p{4cm}|p{4.5cm}|}
\hline
Order&Group $G$&Gap Id&Presentation&$\Gamma_d(G)$\footnote{We shall exclude the cases $d=1,|G|$, since $\Gamma_1(G)=K_1=\Gamma_{|G|}(G)$}\\ \hline
1&$C_1$&1(1)&$\langle a;a^1\rangle$&$\Gamma_1(C_1)=K_1$ \\ \hline
2&$C_2$&2(1)&$\langle a;a^2\rangle$&$\Gamma_1(C_2)=\Gamma_2(C_2)=K_1$ \\ \hline
3&$C_3$&3(1)&$\langle a;a^3\rangle$&$\Gamma_1(C_3)=\Gamma_3(C_3)=K_1$ \\ \hline
4&$C_4$&4(1)&$\langle a;a^4\rangle$&$\Gamma_1(C_4)=\Gamma_2(C_4)=\Gamma_4(C_4)=K_1$\\ \cline{2-5}
&$C_2\times C_2$&2(2)&$\langle a,b;a^2,b^2,aba^{-1}b^{-1}\rangle$&$\Gamma_1(G)=\Gamma_4(G)=K_1,\Gamma_2(G)=K_3$\\ \hline
5.&$C_5$&5(1)&$\langle a;a^5\rangle$&$\Gamma_1(C_5)=\Gamma_5(C_5)=K_1$\\ \hline
\end{tabular}
\end{minipage}
\caption{Abelian groups}
\end{table}
\begin{table}[ht]
\begin{minipage}{\linewidth}
\def\arraystretch{1.4}\tabcolsep=2pt\small\centering
\begin{tabular}{@{} l l l l l @{}}\toprule
Order&Group $G$&Gap Id&Presentation&$\Gamma_d(G)$\footnote{We shall exclude the cases $d=1,|G|$, since $\Gamma_1(G)=K_1=\Gamma_{|G|}(G)$}\\ \midrule
1&$C_1$&1(1)&$\langle a;a^1\rangle$&$\Gamma_1(C_1)=K_1$ \\
2&$C_2$&2(1)&$\langle a;a^2\rangle$&$\Gamma_1(C_2)=\Gamma_2(C_2)=K_1$ \\
3&$C_3$&3(1)&$\langle a;a^3\rangle$&$\Gamma_1(C_3)=\Gamma_3(C_3)=K_1$ \\
4&$C_4$&4(1)&$\langle a;a^4\rangle$&$\Gamma_1(C_4)=\Gamma_2(C_4)=\Gamma_4(C_4)=K_1$\\
&$C_2\times C_2$&2(2)&$\langle a,b;a^2,b^2,aba^{-1}b^{-1}\rangle$&$\Gamma_1(G)=\Gamma_4(G)=K_1,\Gamma_2(G)=K_3$\\
5.&$C_5$&5(1)&$\langle a;a^5\rangle$&$\Gamma_1(C_5)=\Gamma_5(C_5)=K_1$\\ \bottomrule
\end{tabular}
\end{minipage}
\caption{Abelian groups}
\end{table}
\end{document}
| 0.777778 |
Use a minipage for the tabular
|
Java access to protected member in subclass in different package, using object reference of parent type
|
I have the following code in two separate files.
package animal;
public class Frog
{
protected void ribbit()
{
System.out.println("In Frog class!");
}
}
package other;
import animal.*;
public class Tadpole extends Frog
{
protected void ribbit()
{
System.out.println("In Tadpole class!");
}
public static void main(String[] args)
{
Tadpole t = new Tadpole();
t.ribbit();
Frog f = new Tadpole();
f.ribbit(); // Does not compile
}
}
The first Tadpole object assigned to Tadpole type obviously compiles fine and the call to ribbit() will be to the Tadpole's ribbit() implementation. The second Tadpole object that is created and assigned to a Frog reference. However, the call to ribbit() results in a compiler error.
I know that if you create a subclass object in the subclass and assign to a superclass reference that is outside of the subclass's package and try to call a superclass method, this is not allowed. But in this case, shouldn't polymorphism make the object reference "f" call the Tadpole's ribbit() method since a Tadpole object was assigned to it? Why does this cause a compiler error and why is this is not allowed?
|
Just for simple understanding, method overriding is runtime feature . This is obtained in run time and compiler do not care about this during compilation. So your code has to be compiler compliance . So your compilation fails because the method is not accessible from other package during compilation ( despite the fact that it would be available during run time as it inherits the Frog class).
| 0.666667 |
method overriding is runtime feature
|
What is it called when a music has two concurrent tempos
|
I've recently watched a BBC documentary about the history of music and recall an episode where they talk about music that has two distinct tempos (and possibly time signatures) at the same time for different sets of instruments.
Still, I can't remember how this is called and who are the famous composers that composed that way (Stravinsky?).
|
This sort of thing has been explored pretty deeply by, among other people, Conlon Nancarrow. He used player pianos to perform pieces which would most likely have been too complex for anyone to perform organically. One way in which he complicated things was that he used what he called a tempo canon. As discussed here, one such piece was his Study for Player Piano 41a. It used multiple voices, each with its own tempo and the ratios were on a strict, but irrational ratio. If the ratio between tempos was rational, it would line up, or converge, so that two notes could fall at the same time. However, if the ratio was irrational, they would never converge and dance around each other until the piece ended.
This basic concept, although the effect can be jarring, is really not very different from polyrhythms and polymeters. It's just obfuscated by using complicated ratios. For example, if you have a bar and a main voice hit four evenly spaced beats, you have the standard quarter note pulse in 4/4. You can fit 3 notes evenly into that same bar in a second voice and the second voice will be playing half-note triplets. For every four notes in the main voice and every three notes in the second voice, the voices will play together. That's your bar. And that's a polyrhythm. That would be a 4:3 ratio. I'm not sure that's how it's typically notated, but the idea translates. You can imagine how this can be seen as two voices at different tempos. Say maybe one voice in 4/4 at 120 and another voice in 3/4 at 90. They would line up the same way.
Here's another example. If your main voice plays 8 eighth notes before repeating and your second voice plays 7 eighth notes before repeating, they will line up every 56 (7×8) eighth notes. In other words, after your main voice repeats seven times and your second voice repeats eight times. That's a polymeter. Now you can see how these concepts can get mixed up. As the ratios get more complicated (ie 128:73) or less rational (ie √2:φ), the tempos line up less and less and the individual tempos will get closer and/or less distinguishable. That is where you cross the line into tempo canon territory.
Note: I understand that 'irrational ratio' is a terrible oxymoron, but
I can't think of better terminology. Also, this is just the one conceptualization of
the multiple tempo idea. There is world music where this is done organically and many
people have already mentioned other composers who have worked with the idea. But hopefully this helps.
| 1 |
Conlon Nancarrow used multiple tempos to perform pieces which would have been too complex for anyone to perform organically .
|
How to find element count from child to parent with jquery?
|
I have a slight issue where i need to count nest level of elements.
Problem is that parent element can hold multiple child elements and child elements can have their own child elements.
Please see from where i want to start count (marked with text "I start here").
HTML:
<div class="main_set">
<div class="child_set">
<div class="child_set">
<div class="child_set">I start here!</div>
</div>
<div class="child_set"></div>
</div>
<div class="child_set">
<div class="child_set"></div>
</div>
</div>
I have tried couple things to get count 3.
For example my last attempt:
$(this).closest('.main_set').find('.child_set');
This one obviously returns 6 tho counting all child_sets.
How to count child_set elements from start place to main_set taking into account only nesting. So basically in my example how to get count 3?
|
use .children() instead of .find()
here clearly said
The .children() method differs from .find() in that .children() only
travels a single level down the DOM tree while .find() can traverse
down multiple levels to select descendant elements (grandchildren,
etc.) as well.
| 0.777778 |
Use .children() instead of .find()
|
how do i fixed divs from overlapping centered, static div on browser resize?
|
I am trying to build a two columned layout with a sidebar that always stays on the left side of the page with a main content area that is centered, and when the window is resized, the centered content will eventually bump up against the nav bar, but never move any further left than where it is when they touch (which would be left: 150px). Can someone help me out?
Here is the CSS:
@charset "UTF-8";
/* CSS Document */
body,td,th {
font-size: 16px;
font-family: Verdana, Geneva, sans-serif;
color: #000;
}
body {
background-color: #FFF;
margin-left: 0px;
margin-top: 0px;
margin-right: 15px;
margin-bottom: 0px;
}
#nav {
position: fixed;
top: 0px;
left: 0px;
width: 150px;
height: 10000px;
background-color: #D61D21;
text-align: right;
}
#nav a:link {
color: #FFF;
text-decoration: none;
}
#nav a:visited {
color: #FFF;
text-decoration: none;
}
#nav a:hover {
color: #FFF;
text-decoration: underline;
}
#main {
width: 810px;
height: 810px;
margin: 0px auto;
}
and here is the html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Nick Passaro Designs</title>
<link href="css/index.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="nav">
<a href="index.php"><img src="assets/marklogo.jpg" width="150" height="97" border="0" alt="Nick Passaro Designs"></a>
<p><a href="portfolio.php">PORTFOLIO</a> &nbsp;</p>
<p><a href="logos.php">LOGOS</a> &nbsp;</p>
<p><a href="print.php">PRINT</a> &nbsp;</p>
<p><a href="web.php">WEB DESIGN</a> &nbsp;</p>
<p><a href="photography.php">PHOTOGRAPHY</a> &nbsp;</p>
<p><a href="contact.php">CONTACT</a> &nbsp;</p>
</div>
<div id="main">
ENTER CONTENT HERE
</div>
</body>
</html>
Any help is greatly appreciated!
|
Do this:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Nick Passaro Designs</title>
<link href="index.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="nav">
<a href="index.php"><img src="assets/marklogo.jpg" width="150" height="97" border="0" alt="Nick Passaro Designs"></a>
<p><a href="portfolio.php">PORTFOLIO</a> &nbsp;</p>
<p><a href="logos.php">LOGOS</a> &nbsp;</p>
<p><a href="print.php">PRINT</a> &nbsp;</p>
<p><a href="web.php">WEB DESIGN</a> &nbsp;</p>
<p><a href="photography.php">PHOTOGRAPHY</a> &nbsp;</p>
<p><a href="contact.php">CONTACT</a> &nbsp;</p>
</div>
<div id="wrapper">
<div id="main">
ENTER CONTENT HERE
</div>
</div>
</body>
</html>
CSS:
#wrapper{
margin-left: 150px;
}
What you do is create a wrapper div around your main div and make that wrapper div have a left-margin of 150px so that it's side by side with the nav bar. Now all your resizes inside the main div should be limited to within the wrapper.
| 0.888889 |
Make a wrapper div have a left-margin of 150px .
|
Git: How can I merge changes made between two tags to another branch?
|
I'm trying to manage our Moodle instance on our own branch of the Moodle repo. I checked out tag "v1.9.11" of branch "MOODLE_19_STABLE", then copied that to a new branch "COE", where I've added in our custom theme, etc.
Now that tag "v1.9.12" exists, I want to merge the commits up to that tag into my "COE" branch (and not the commits that came after).
Can I do this with something like git cherry-pick?
|
$ git merge v1.9.12
will merge all the commits up to, and including, v1.9.12, and nothing after that.
| 0.888889 |
$ git merge v1.9.12 will merge all commits up to, and including, v1.8.12
|
Is pretending to want to trade before playing a monopoly card objectionable?
|
In Settlers of Catan, I sometimes try to ask people if they want to trade a certain resource, tricking them into revealing the approximate amount of that resource in everyone's hand. After this I play the monopoly card. This has on some occasions not been received very well.
Is this fair play?
|
Yes, it's lame :P.
But at my table you wouldn't be reprimanded, but expect future trade to get a little more difficult. This is an awesome way to get the rest to gang up on you.
| 1 |
Expect future trade to get a little harder
|
Behavior when validating an expired certificate chain
|
I have the following situation:
A server certificate (CServ) is signed by self-signed certificate (C0)
A client certificate (CCli) is signed by CServ
Client's trust-store contains C0, so the client application can trust CServ
Note: C0 is actually a simulation of a CA certificate for testing purposes.
Now, let's consider a situation when C0 either is expired or not yet valid. Since it's stored in client's trust-store, is it still trusted? In other words is chain [C0, CServ] still valid?
|
The trust store seems to contain certificates, but that's an illusion (or a tradition). Technically, a trust anchor, i.e. the basis for the trust in certificate validation, is a name coupled with a public key. It so happens that people found it convenient to store the name and public key as a file with the same format as a certificate; this required some trickeries, such as the "self-signature", which makes no sense but had to be included because the format for a certificate includes a non-optional field for a signature.
At that point, it really depends on the OS/browser internal conventions. Some implementations will look at the "validity dates" in the trust anchor "certificate" and will use them as, indeed, validity dates (i.e. beyond the end of validity date, they will cease to trust that trust anchor, even if it is still "there", in the dedicated store for trust anchors). Some other implementations will ignore these dates altogether. It is really up to each implementation to make these choices, since the standard is silent on the subject.
So you have to test.
| 1 |
Validity dates in a trust anchor "certificate"
|
What is temptation?
|
Temptation, in the common secular sense, seems to indicate an attraction to something.
Temptation
The act of tempting
The condition of being tempted.
Something attractive, tempting or seductive; an inducement or enticement.
Pressure applied to your thinking designed to create wrong emotions which will eventually lead to wrong actions.
Tempting
attractive, appealing, enticing
seductive, alluring, inviting
Tempt
(transitive) To provoke someone to do wrong, especially by promising a reward; to entice. She tempted me to eat the apple.
(transitive) To attract; to allure. Its glossy skin tempted me.
(transitive) To provoke something; to court. It would be tempting fate.
But, as with many secular concepts that overlap religious concepts, there are often explicit theological definitions which allow the terminology to fit into religious, dogmatic, and theological discussions with less ambiguity. In this case, is there any predominating Christian/theological definition?
In particular, how is temptation defined or explained in such a manner that allows Christ to have been tempted?
To clarify the problem, if Christ is to be attracted to some thing, there must be some part or aspect of Christ to which some thing appeals. More significantly, Christ, in order to be tempted, must desire that thing if we are to say He is attracted to it. And if Christ is to contain a part or aspect to which some evil may be a temptation, thus arousing a desire, there could be said to be a sinful nature or component in Christ -- a contradiction of His Godliness.
To illustrate the problem, one might select magnetism (or any natural force) as a natural analogy. For the effect of magnetism (sin) to attract (tempt) a material (person), the material must contain, at least to some extent, a magnetic (sinful) component.
Thus, if we say that Christ is tempted in this understanding, we say that He has a sinful component.
How do we Christians, Catholics, or any denomination that has a well-established concept, define or explain temptation in a non-trivial manner without requiring Christ to have a sinful nature?
|
The following is sort of an answer to your question: the desert fathers (from the beginnings of monasticism) thought a lot about the beginning of sin.
Sin has its origins in "logismoi," thoughts in our mind floating hither and thither, often from whence we know not. "Logismoi" is usually translated as "thoughts," though maybe in this usage it would be more suggestive to translate it as "distractions". Having logismoi is like walking the streets of Las Vegas, where promoters snap packets of prostitution flyers loudly across their hands and extend the flyers toward pedestrians. It is no sin to be assaulted by such advertising.
One may (at one's own risk) enter into dialogue with the logismoi to see what holds them together and to see how to help your brother (and yourself) tear them apart when need be.
Sin begins when one "couples" with logismoi, a condition described in depressing detail in our record of the ancestral sin:
... the woman saw that the tree was good for food, and that it was a delight to the eyes, and that the tree was to be desired to make one wise....
(Genesis 3:6)
One might say sin begins when one seriously considers a wrong choice as an option. Our Lord spoke of this in His sermon on the mount:
You have heard that it was said, "You shall not commit adultery." But I say to you that every one who looks at a woman lustfully has already committed adultery with her in his heart.
(Matthew 5:27-28)
I say this is sort of an answer because it doesn't address the use of the word "temptation" in English as such. But I hope it helps illuminate how sin begins.
In particular, Christ was, presumably, assaulted by logismoi as much as, and probably worse than, anyone else in human history. But He never coupled with them, so He never sinned. E.g. when tempted in the desert, Christ made it clear with His curt replies to Satan how little He thought of Satan's advances.
More terrifying to consider along these lines was His struggle in Gethsemane. Perhaps it's best for me not to speculate on what was going through His mind then.
I think @ryan hit on the desert fathers' distinction. The logismoi are the "presentation" of temptations, and the coupling is the "feeling" of temptation.
| 1 |
Sin begins when one "couples" with logismoi, a condition described in depressing detail .
|
How the hypergeometric distribution sums to 1?
|
The hypergeometric distribution is defined for $\max(0, n+K-N)\leq k\leq \min(K,n).$
But, when we use Vandermonde's identity to prove that probabilities sum to $1$, then we use the range of $0\leq k \leq n.$ I wonder how this is justified?
|
The reference mentions that this identity is from combinatorics: that is, it counts things.
What does it count? Consider $N$ objects. Once and for all, divide those $n$ things into a group of $K$ of them, which I will call "red," and the remainder, which I will call "blue." Each subset of $n$ such objects determines, and is determined by, its red objects and its blue objects. The number of such sets with $k$ red objects (and therefore $n-k$ blue objects) equals the number of ways to choose $k$ red objects from all $K$ ones (written $\color{red}{\binom{K}{k}}$) times the number of ways to choose the remaining $n-k$ blue objects from all the $N-K$ ones (written $\color{blue}{\binom{N-K}{n-k}}$).
Now if $k$ is not between $0$ and $K$, then there is no $k$-element subset of $K$ things, so $\binom{K}{k}=0$ in such cases. Similarly, $\binom{N-K}{n-k}=0$ if $n-k$ is not between $0$ and $N-K$. (This not only makes sense, it is actually how good software will evaluate these quantities. Ask R, for instance, to compute choose(5,6) or choose(5,-1): it will return the correct value of $0$ in both cases.)
Summing over all possible numbers $k$ shows that
$$\binom{N}{n} = \sum_k \color{red}{\binom{K}{k}}\color{blue}{\binom{N-K}{n-k}}$$
and as you read this you should say to yourself "any $n$ objects are comprised of some number $k$ of red objects and the remaining $n-k$ blue objects."
The sum needs to include all $k$ for which both the terms $\color{red}{\binom{K}{k}}$ and $\color{blue}{\binom{N-K}{n-k}}$ are nonzero, but it's fine to include any other values of $k$ because they will just introduce some extra zeros into the sum, which does not change it. We just need to make sure all relevant $k$ are included. It suffices to find an obvious lower bound for it ($0$ will do nicely and is more practicable than $-\infty$!) and an obvious upper bound ($N$ works because we cannot find more than $N$ objects altogether). A slightly better upper bound is $n$ (because $k$ counts the red objects in a set of $n$ things). Thus, writing these bounds explicitly and dividing both sides by $\binom{N}{n}$, we obtain
$$1 = \sum_{0\le k\le n}\frac{\color{red}{\binom{K}{k}}\color{blue}{\binom{N-K}{n-k}}}{\binom{N}{n}} .$$
Despite the notation, this formula does not implicitly assert that all values of $k$ in the range from $0$ to $n$ can occur in this distribution. About the only reason to fiddle with the inequalities and figure out what the smallest possible range of $k$ can be would be for writing programs that loop over these values: that might save a little time adding up some zeros.
| 0.666667 |
What does it count? Consider $N$ objects
|
iPhone dock connector problems, with and without accessories
|
I started to experience problems with my iPhone that seem to be related to the dock connector.
Upon plugging my iPhone into my (officially supported) car stereo, I started to get the message "This accessory is not supported by iPhone" on the screen. Didn't think much of it as I only use it for charging purposes, and that still worked so I ignored it. Then I bought a small ANT+ dongle, which is a little accessory you plug into the dock connector to allow your phone to receive data from various health/fitness devices like heart rate monitor, and cycle sensors etc. It produces the same error message every time I plug it in, and the apps that use the dongle will not recognise it.
The dongle does officially support my hardware and OS level. I've checked that it is not broken by plugging it into an iPhone 5, an iPad 3 and an iPod of some description, none of which showed the error. The supported apps find the device on the iPad, the iPhone 5 does not have the apps installed but offers to do so as soon as I plug it in, so I know the dongle is working correctly.
In addition to the above, when nothing is plugged into the dock connector, it still occassionally thinks that something is, resulting in a muted phone. When it's in this state I am not able to hear anything or change any volume settings (music playback or ringer volume) with the physical keys. Going into the Music app shows that it thinks it's outputting the music to the dock connector.
Why is this accessory not working on my iPhone, and how can I get it working? What causes my iPhone to think that it's docked when it isn't?
|
This commonly occurs when there is an issue with your dock connector. It is likely dirty, obstructed in some way, or possibly even broken with a bent pin or something. Very often this is not apparent, because with 30 pins to play with, chances are most of the time you only need the ones for charging and USB data transfer, leaving the rest unused such that you will not notice if they start working sub optimally.
There are 3 ways I would try to fix this, in order of most likely to fix:
Clear it out
Your first step is to check for any obvious blockage. If you have a can of compressed air, you can try to blow any debris out. If you don't, then using a fine non metallic scraper (a plastic toothpick is ideal, a wooden one may leave small fibers behind) carefully clean out what you can - even if it looks clean you will be surprised how much crap and fluff you can scrape out. Take care to blow any debris out of the phone, and not into it - i.e. hold it upright and get at it from underneath, don't sit it upside down and work from the top
Clean it up
If there is no obvious obstruction then the problem may be more subtle, a coating on one or more of the pins that is preventing a neat conductive contact, or is grounding a pin against another one for example - perhaps there has been some contact with a liquid in the past etc. You need to clean the pins to get rid of this. You will need a couple of things things - 1) some cleaning agent, 2) a lint free cloth/piece of sponge, or an old toothbrush.
For a cleaning agent, 99% isopropyl is perfect, but if you don't have that kicking around you could try a very small quantity of the neatest and purest alcoholic drink you have in the house - I've used Vodka which is by and large 50/50 alcohol and water. Don't use anything flavoured or anything that it likely to have anything other than alcohol and water in it! Especially sugars or salt!.
Using a very small amount of your cleaning agent, and keeping the phone upright so any drips fall out, and not into the phone, lightly brush or wipe the dock connector, taking care not to be rough enough to disturb the pins out of alignment. I've used a small piece of synthetic sponge and prodded it about with the same toothpick I used earlier.
Hit it
If this doesn't work, then the issue could still be a physical obstruction, although it may be beyond the dock connector and more internal. Short of taking the phone to bits, there is not a lot you can do, and whilst you cannot clean the inside, you can try to dislodge anything that's stuck by using a combination of lightly tapping the phone on all 4 sides whilst playing about with the vibrate functions for alarms etc.
Using the first 2 methods above I solved the "Accessory not supported problem", but still had the intermittent docking issue.
Assuming I could not fix that one, I went to turn on Vibrate alerts (which I had previously turned off) as a workaround, only to find that after playing with all the vibrate "tones" etc it magically fixed itself!
Note 1 It's possible that the issue is not with the connector on your phone, but on your device/cable - you can try all the above on the cable end too if doing it on your phone does not yield results.
Note 2 If your device is failing to charge, or will only charge from a certain cable or dock, then the same fix potentially applies.
| 0.888889 |
How to fix a dock connector problem?
|
Using bash "&" operator with ";" delineator?
|
I'm trying to write a command that's a one-line for loop containing a command that uses the & operator to put the command in the background:
for dir in $(ls); do command $dir &; done
Where & tells BASH to run command in the background. Yet BASH returns
bash: syntax error near unexpected token `;'
What's going on here? How can I use & in conjunction with ;? I tried enclosing things in quotes, like do "command $dir &" or do command $dir "&" but those have unexpected results.
|
You don't use the ; with '&', the '&' on its own is enough to finish the command. I believe there is currently no mention of this behaviour in the manual. Your loop would simply be:
for dir in $(ls); do command $dir & done
Additionally, you should consider using a glob instead of $(ls) which will fail if the filename contains whitespace. You can set nullglob to prevent dir being a * if there are no files:
shopt -s nullglob
for dir in *; do command $dir & done
| 0.888889 |
'&' on its own is enough to finish the command
|
Jsoup can't read xml return file
|
I'm facing some problems with Jsoup. I'm trying to retrieve an xml file from Open Movie Database using their API in my beta Android app.
Their API documentation says if the return type will be an xml just put an "r=" and the return file type.
I've tested with some requests. Below one of them:
Jsoup.connect(http://www.omdbapi.com/?i=tt1285016&r=xml).get();
Testing on a browser works fine. But on android no. Any exception is thrown. If I don't insert the return file type, it returns a JSON. In this case I receive the data.
To make sure if the problem is with xml file. I've teste with MusicBrainz API. By default it returns XML. For my surprise works fine.
What is the problem? The return type of open movie database of Jsoup?
|
Found the problem. The values were always there. I don't know why but the return type is an html file with xml tags included. Printing values on Logcat it returns html tags html, head, body and only after this the XML.
| 0.444444 |
Logcat returns html tags html, head, body and XML
|
How difficult is it to undertake a Humanities PhD. at Harvard (converting to the American system from Europe/UK?)
|
Before I begin, feel I should make it clear that I have no doubt that undertaking a PhD. anywhere, let alone at Harvard, will be a difficult and strenuous task!
To briefly explain, I have graduated with a good Bachelors of Arts from the UK, and am set to do my Research Masters in Holland. However, I have been in contact and have contacted the literature faculties in Harvard, who have been very encouraging but, to be honest, the system itself seems very different.
To clarify, I'll copy in some of what my (possible) supervisor has emailed me:
Our students enter the program, take two or three years of courses, and only then settle on a dissertation topic and choose a committee of three faculty -- one primary advisor and two other readers.
This sounds at once much more fluid and liberal a way of doing things, but, considering the ridiculous costs of studying in the USA, I'm not sure how leisurely that would be in reality! Should I assume that Doctoral programs in the USA are like a Masters leading into a PhD? Is there a scholarship available for both of these?
Has anyone reading this had any experience on the matter, and can relate more clearly how this process works, and whether exceptions are every possible?
|
The quoted description is pretty standard for how Humanities departments in the US work. Most students entering Humanities PhD programs in the States do not have MA degrees, although a significant proportion of those from the UK do. It would be unlikely that you could skip those first 2-3 years of coursework. Even if you could, it would put you at a serious disadvantage even if you knew in advance what topic you wanted to research. A 1-year UK MA degree, just does not prepare you to the same extent as 2-3 years of coursework.
As for funding, the top students are likely guaranteed funding for some number of years. The funding will likely require some teaching. The teaching maybe in the form as a TA, but is likely to be much more extensive and require you to design and run a large undergraduate lecture class. For those students, the funding will cover tuition and a stipend. Those without guaranteed funding can still get funding for teaching, but you cannot count on it. How tuition is handled depends on the university/department and where you are in the program.
In the Humanities, it is unlikely that any supervisors will have grants that pay for PhD students, but there are grants that you can apply directly for. Some of these cover students in the first few years, but most are for more senior students.
For US PhD programs in the Humanities, unlike in the Sciences, funding should play a huge role in your decision of where to go. In the Sciences, everyone essentially has funding that covers tuition and living expenses and very little teaching. In the Humanities, self funded students and students with with huge teaching requirements are common. There is a huge difference in productivity and happiness between those who have to take out loans, that they will likely never be able to pay back, or teach and those who do not.
| 1 |
a 1-year UK MA degree does not prepare you to the same extent as 2-3 years of coursework .
|
Get an item in a list of taxonomy
|
Hello Drupal Community,
I am creating a menu which has a link to an "editorial". I created a taxonomy named "edito" and created articles (content type) that are tagged with this taxonomy.
I need to recover the last article tagged with this taxonomy in the menu as a link (see image attached). Does anyone have an idea of how to achieve this ?
Thanks,
|
You should not try to hard-code the URL to the item in the menu item edit screen.
You should add a View to your Menu.
Views allows you create a view including a filter to show only recent content.
You can then add a filter for a specific Content Type, User or whatever. And you can limit the View to show only N items.
You can insert the View of new items into your menu with the help of 3rd party modules, an example is Menu Attach Block, see the project page for a list of similar helper modules.
| 0.666667 |
Add a View to your Menu
|
Linux Mail servers over Windows Mail servers
|
am new in systems administration and the org am in has been using exchange 2003 for lyk forever,i thot i would change the systems to a linux server basically to cut l
|
Well, dear mr. new - please consider that you dont even know what you are talking about.
has been using exchange 2003 for lyk forever
That would be "like" not "lyk", AND... Exchange 2003 is NOT A MAIL SERVER. What you try to do is like replacing a car with a spare engine. Exchange (2003 is outdated and seriously must be upgrades like yesterday) is a LOT more than a mere email system.
Unless your company does not use any of the othe features (like shared calendard, integration with phones in a push fasion) and has no interest in using some of the new featuers an upgrade would bring (voice control of calendar, integration with a SIP phone system as integrated mailbox with text to speech and speech to text) you basically are on the way to make a moronic bad decision. The type that may turn your system administration career with immediate termination for gross neglect and demosntrated incompetence.
So, sit down and think of what your company uses Exchange for. Then sit down and try tofind a product that can replace it in it's entierety. Then sit down and consider an ugparde (2010 is a LOT better than 2003). Then sit down and consider the assoiated costs for moving to linus in your company (which may include thigns like integrating backups, changing procesdures, adding more staff that has in depth linux knowledge etc.). Then make an educated decision. Right now you look like - sorry tobe blund - an ignorant linux zealot who does not even bother to check the software he wants to replace for the functionaltiy it offers.
MOST companies would really get angry with some junior wannabe system admin replacing their integrated staff coordination platform with a mere email system.
| 0.333333 |
Exchange 2003 is a LOT more than an email system
|
How to properly override a method with unknown number of arguments?
|
What I am doing is:
class Foo
alias_method :__bar__,:bar
def bar(*arg)
#do something
__bar__(*arg)
end
end
Is it the proper way to do it?
Or it is better to figure out how many required,optional,block arguments the original method has, and write exactly the same amount of arguments?
|
The use of a slurpy arg is the right approach, but you should also handle any block arguments:
class Foo
alias_method :__bar__,:bar
def bar(*arg, &block)
#do something
__bar__(*arg, &block)
end
end
| 1 |
Use of a slurpy arg to handle block arguments
|
Is it possible to compress and obfuscate Javascript code on a fly?
|
I came across this great online tool. It has options to compress and obfuscate JS. I am wondering if it is possible to do that on the site on the fly. I know it will slightly slow-down the client, but in my case it is acceptable. I am more concerned about proprietary code I use.
I use PHP and jQuery mainly.
|
You can use minify, which is based on Yahoo's YUI-Compressor.
It combines multiple CSS or Javascript
files, removes unnecessary whitespace
and comments, and serves them with
gzip encoding and optimal client-side
cache headers.
To get obfuscation, you can set nomunge => false
| 0.888889 |
minify is based on Yahoo's YUI-Compressor .
|
Can $(\log\log m)/(\log\log n)$ be rational?
|
If $m, n$ are two different positive integers, is it true that the ratio $\displaystyle \frac{\log\log m}{\log\log n}$ is necessarily irrational? By $\log$ I mean the logarithm in base $e$ (not base $10$).
I guess it is irrational, but I don't know why?
|
I'll assume you mean the natural logarithm. The condition that $\log \log m = q \log \log n$ where $q = \frac{a}{b}$ is rational is equivalent to the condition $(\log m)^b = (\log n)^a$. If $m \neq n$ then $a \neq b$ and this condition cannot be satisfied if $\log m$ is a rational multiple of $\log n$ because $\log n$ is transcendental by Lindemann-Weierstrass.
If $\log m$ is not a rational multiple of $\log n$, then this condition cannot be satisfied if one assumes Schanuel's conjecture, since then $\mathbb{Q}(n, m \log n, \log m)$ would have transcendence degree $1$. So this is likely to be true but out of reach of current technology (although I don't know enough about transcendence theory to say this with any authority).
| 1 |
The natural logarithm is equivalent to the condition $q = fracab$ .
|
What is the most secure way to do OCSP signing without creating validation loops?
|
I'd like to enable the most secure OCSP validation that Windows 2008 SP1 and newer support.
Based on the following information, am I required to implement id-pkix-ocsp-nocheck on my OCSP certificate?
If so, does that mean an OCSP response can be forged, allowing an revoked certificate to go unnoticed by the victim?
The signature on OCSP responses must follow the following rules to be
considered valid by a Windows Vista or Windows Server 2008 client:
For Windows Vista, either the OCSP signing certificate must be issued
by the same CA as the certificate being verified or the OCSP response
must be signed by the issuing CA.
For Windows Vista with Service Pack 1 and Windows Server 2008, the
OCSP signing certificate may chain up to any trusted root CA as long
as the certificate chain includes the OCSP Signing EKU extension.
CryptoAPI will not support independent OCSP signer during revocation
checking on this OCSP signing certificate chain to avoid circular
dependency. CryptoAPI will support CRL and delegated OCSP signer only.
We recommend that you enable the id-pkix-ocsp-nocheck
(1.3.6.1.5.5.7.48.1.5) extension in the OCSP signing certificate so
that no revocation checking is performed on the OCSP signing
certificate. This ensures that a CRL is not downloaded to validate the
OCSP signing certificate.
(source)
|
In all reality the entire certificate chain must be validated using OCSP or CRL. However, in practice the number of certificates revoked is quite small. To speed up the SSL/TLS handshake chrome has removed the use of OCSP and CRL by default (it can be re-enabled chrome's settings). Instead Chrome relies upon its own, system of blacklists.
| 0.833333 |
Chrome has removed the use of OCSP and CRL by default .
|
Does non-synthetic 10w30 motor oil contain sulphur?
|
I ask this question as I plan on using 10W30 motor oil in my Jeep's manual transmission and need no sulphur added to the oil so that it is "yellow metal safe". I'm not looking to start a discussion around whether or not motor oil may be used in manual transmission but rather, looking for information on whether motor oil (synthetic or mineral) contains sulphur as an additive. I assume synthetic does not.
|
Synthetic based oils do not typically contain sulphanates. Mobil, as an example recommend
Mobil 1 synthetic gear oil in lieu of a GL-5 lubricant that does contain sulphur and as
you correctly state is injurious to copper, brass, and the like.
| 1 |
Synthetic based oils do not typically contain sulphanates
|
Get REQUEST_URI and don't overwrite
|
I tried storing the REQUEST_URI in a session with the code below. I need to store the very first REQUEST_URI when a visitor lands on a page on our site and not have it overwritten when they begin browsing pages. This isn't working as I browse the site i'm seeing a new URI displayed by the echo.
session_start();
if ( !isset( $_SESSION['theuri'] ) ) {
if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
$_SESSION['theuri'] = $_SERVER['REQUEST_URI'];
}
}
echo $_SESSION['theuri'];
|
I found this article which said to add this code to my functions.php and now the code in my footer is working fine.
http://devondev.com/2012/02/03/using-the-php-session-in-wordpress/
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
| 0.666667 |
add_action to functions.php and now the code in my footer is working fine
|
Is this a bug? Angular removes object params when corresponding input is not valid
|
Please see this:
http://plnkr.co/edit/soubKCayeLAqgDOel8AL?p=preview
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<script data-require="[email protected]" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="testCtlr">
<pre>{{contacts | json}}</pre>
<div ng-repeat="contact in contacts">
<div ng-repeat="email in contact.emails">
<input type="email" name="email" ng-model="email.email">
<input type="text" name="text" ng-model="email.text">
</div>
</div>
</body>
</html>
var app = angular.module('testApp', []);
app.controller('testCtlr', ["$scope", function ($scope) {
$scope.contacts = [
{
id:'',
name:'',
emails:[
{
email: 'e1',
text: 'fghfgh'
},
{
email: 'e2',
text: 'hjkhjk'
}
],
}
];
}]);
you see if you change the text in the email text box it is removed from the obj unless it is a valid email...
|
It is not a bug, this is by design. The input type email uses regex to validate email address inputs. If the input is not valid it is removed from the model.
On another note - if you wrap your stuff in a form - you can determine the validation state of the inputs. Also, as you are using a repeat, you will need an index.
Here is an example of what I mean:
<form name="myForm">
<div ng-repeat="contact in contacts">
<div ng-repeat="email in contact.emails track by $index">
<div ng-show="myForm.email{{$index}}.$invalid">Invalid email.</div>
<input type="email" name="email{{$index}}" ng-model="email.email">
<input type="text" name="text" ng-model="email.text">
</div>
</div>
</form>
I have updated your Plunker here.
These are the validation states you can use:
//[formName].[inputFieldName].property
myForm.email1.$pristine;
// Boolean. True if the user has not yet modified the form.
myForm.email1.$dirty
// Boolean. True if the user has already modified the form.
myForm.email1.$valid
// Boolean.True if the the form passes the validation.
myForm.email1.$invalid
// Boolean. True if the the form doesn't pass the validation.
myForm.email1.$error
| 0.444444 |
Validation state of input type email
|
Can I use a shock pump to inflate a tube?
|
I know that shock pumps are meant for high pressure applications so that they can withstand high pressures needed by suspension shocks.
However, can I use a shock pump to inflate my tire in a pinch if I run out of CO2? How would it compare to a standard mini-pump in terms of volume?
|
Note: this calculation makes many assumptions, so it's only useful in an 'average use case', not some sort of exact measurement. If you find better information, please post it and I'll update the answer.
How many pumps you would need to fill up a tire depends on many variables. First, the volume of your inner tube, which can be approximated as a torus (doughnut-shape) atop the rim size of a given diameter. You can find yours approximated on this graph.
26" Mountain Bike, 2.1" tire width = 4.8L
29" Mountain Bike, 2.1" tire width = 5.2L
700C Road Bike, 35mm tire width = 2L
20" BMX Bike, 1.85" tire width = 3L
I'm finding pump specifications quite difficult to find (I need piston diameter and stroke length), but here's a comparison of some shock pumps on an empty shock cylinder of a 2007 Fox 36 RLC 160mm Fork.
Average Accu-Gage Pressure Reading after 100 strokes: 77.2 psi
My best guess at RC2 air chamber specifications: 1" (25.4mm) diameter, 160mm length (max travel). If someone can find accurate specs or the true volume, I'd appreciate it.
Fox RC2 Air Volume (estimated): Vcylinder = pi*r^2*h = 81 mL
So then, IF pumping air into different volumes is linearly proportional (it's not, but somewhere in the ball park), and you wanted to inflate the tires listed above to ~77.2psi, it'd take about this number of pumps with the 'average' shock pump:
Tire Volume Ratio of Tire to Air Shock Number of Pumps to ~77.2 psi
26" Mountain Bike, 2.1" tire width 4.8L 59:1 5,900
29" Mountain Bike, 2.1" tire width 5.2L 64:1 6,400
700C Road Bike, 35mm tire width 2L 25:1 2,500
20" BMX Bike, 1.85" tire width 3L 37:1 3,700
So, perhaps if it was a life or death situation, you have a lot of time on your hands, or you just can't afford that gym membership, you might want to pump a few thousand times to fill your tire. You probably don't.
By contrast, if you're just looking for this functionality in one device, you could just use a dual purpose model, such as this Specialized Pump, that can inflate both high pressure, low volume containers (like your shock) and low pressure, high volume containers (like your tire).
You twist the handle to select between uses, and save yourself a few thousand pumps.
| 1 |
How many pumps you would need to fill up a tire depends on many variables.
|
Get value of a form ID python/flask
|
how do you get the actual value of the input id after you send it in flask?
form:
<form action="" method="post">
<input id = "number_one" type="text" name="comment">
<input type="submit" value = "comment">
</form>
like what im trying to say is
when the form is sent. when you do this:
request.form.get("comment")
the value of the text field is passed. what I can't figure out is how to get the value of the id.
so when the form is sent we could then tell from which form the info was coming from was coming because each form has a unique id. In this case the id is number_one
so how do we go about getting the actual literal value of the id and not the text input?
|
You can't. The id value is not part of the form data set sent by the browser.
If you need to identify the field, you'll have to either add the id to the input element name, or if the id is generated by Javascript code, perhaps store the information in an extra hidden field.
Adding the id to the name could be done with a delimiter perhaps:
<input id = "number_one" type="text" name="comment.number_one">
which would require you to loop over all form keys:
for key is request.form:
if key.startswith('comment.'):
id_ = key.partition('.')[-1]
value = request.form[key]
| 0.888889 |
id value is not part of the form data set sent by the browser
|
Best Innodb Buffer Pool Size for 8GB RAM?
|
I found out that my MySQL server is configured with only 128MB for innodb_buffer_pool_size. That is not enough considering that I have a 8GB RAM server. It hosts MySQL server and an Apache/Catalina server. What should I change this seeting to?
|
I have four(4) old posts to demonstrate how to measure and size up the InnoDB Buffer Pool based on the amount of RAM on the DB Server and how much space is currently being taken up by data/index pages:
Apr 14, 2011 : What are the main differences between InnoDB and MyISAM?
Oct 22, 2012 : How much memory do I need for innodb buffer pool?
Oct 22, 1012 : How large should be mysql innodb_buffer_pool_size?
Apr 08, 2013 : MySQL performance impact of increasing innodb_buffer_pool_size
Please look over these posts, run the queries, and use good judgment. Why did I say to use good judgment ? If the ideal Buffer Pool Size is greater than 6GB (75% of your DB Server's RAM), the highest innodb_buffer_pool_size permissible would be 6G.
Give it a Try !!!
| 1 |
How to measure and size up InnoDB Buffer Pool?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.