summary
stringlengths 15
147
| text
stringlengths 1
19.3k
| answer
stringlengths 32
22.6k
| labels
float64 0.33
1
| answer_summary
stringlengths 5
164
|
---|---|---|---|---|
Custom theorem numbering | This one should be easy for the gurus…
Suppose I want to define a theorem environment which has a custom numbering scheme. That is, instead of being numbered according to some counter, it is numbered according to a passed parameter. So writing something like
\begin{customtheorem}{8}
Text.
\end{custom theorem}
would produce
Theorem 8. Text.
I realize I could define a new environment on my own, but then the header will be bold, or small caps, or whatever I defined it to be, and so may differ from the rest of the document if I switch documentclass. So I would like something that also matches the regular theorem headers.
Thanks in advance for any ideas.
| You can just temporarily reset your theorem counter:
\documentclass{article}
\usepackage{amsthm}
\newtheorem{Theorem}{Theorem}
\makeatletter
\newenvironment{customTheorem}[1]
{\count@\c@Theorem
\global\c@Theorem#1 %
\global\advance\c@Theorem\m@ne
\Theorem}
{\endTheorem
\global\c@Theorem\count@}
\makeatother
\begin{document}
\begin{Theorem}
Dummy text
\end{Theorem}
\begin{customTheorem}{99}
Dummy text
\end{customTheorem}
\begin{Theorem}
Dummy text
\end{Theorem}
\end{document}
| 0.666667 | Reset theorem counter temporarily |
simple algorithm to encrypt/decrypt a text file | I need to write a first program in one language that saves data in a text file, and write a second program in a second language to decrypt that file. The two languages in question don't include any crypto libraries, so I'm on my own.
Could someone recommend, point me to, or summarize a simple algorithm (pseudo code) that provides some level of basic encryption?
I don't have much experience in this area, but if you can summarize clearly in pseudo-code, I can implement it (don't assume prior knowledge).
It doesn't have to be bullet-proof, but just something that deters the user from understanding the text file. Something more secure than just a simple character-substitution (1 for 1), like perhaps a key that generates a random string used to XOR or similar complexity. I have no idea where to start.
UPDATE
How about pseudo-code for a one-time pad? Or XOR encryption with a key?
| My advice would be to use a stream cipher.
First of all, it is easy to implement, because you won't have to think about dividing into blocks, padding, etc..
Secondly, the idea of stream ciphers is very easy: you generate a pseudorandom sequence of bits out of the private key. Then you XOR this sequence with a plaintext. You will only have to code the generation, the rest is elementary.
Finally, there are very easy stream ciphers, e.g. RC4 http://en.wikipedia.org/wiki/RC4; another example is Salsa20 http://en.wikipedia.org/wiki/Salsa20
And when I say "simple" I mean not only the amount of lines of code, but also the ease of debugging/ flaws search.
| 0.888889 | How to use a stream cipher? |
optimal way to remove unwanted js and css files from page | I use drupal 6 and ubercart2. Loading of cart and checkout page takes a while so I am thinking about removing any js and css files which are not used on specific pages.
What would be the ideal way to do it? I know about js agregation but want to try the first approach.
Thank you very much.
| With reference to your question 'optimal way to remove unwanted js and css files from page', hope this approach works ::
1) Include your js & css files only under appropriate hook as per applicable
2) Use syntax like -
drupal_add_js (drupal_get_path ('module', 'module_name') . '/js/js_file_name.js'
);
drupal_add_css(drupal_get_path('module', 'module_name') . '/css/css_file_name.css');
3) You can make use of syntax like this to set some settings variable & check in your js file before invoking your event inside the behavior
In module file ::
drupal_add_js (array ('module_name' => array ('variable_name' => some_value)), 'setting' );
In js file ::
Drupal.behaviors.testName = {
attach: function (context, settings) {
if(typeof Drupal.settings.module_name != 'undefined'
&&
Drupal.settings.module_name.variable_name == some_value){
// Do SOMETHING
}
}
};
4) If your code already included js & css files at places which could be done a better way, then you need to make the code changes accordingly. For example,
If we could include the js & css files in hook_node_view (based on D7 standard, say), then we should not include it from hook_init.
Hope it helps
| 0.888889 | How to remove unwanted js and css files from page? |
deployment taking longer time using changesets | We currently use changesets to deploy to production for apex classes and configuration items. It is taking a long time for deployment because the validation on the production org takes a longer time to accomplish this. I know i can easily do a validation using ant to cut down the validation time but unfortunately the end user team does not allow this.Is there anything we can do to cut down the time taken to do the validate task for changesets in the production org?
Buyan
| Changeset deployment usually does not have SLA and what you have experienced is an expected behavior. Deployment time will always vary and how long one deployment takes to complete does not become a benchmark on how long it'll take to complete another
There are times when changeset deployment will hit a legitimate issue such as gack or a lock and when those occur, Salesforce support can definitely investigate and escalate to have the issue rectified. However in few cases the deployment doesn't hit any gack or lock.
If it took this long to complete may possibly be link to the the many post release patches Salesforce.com have been rolling out, as when a patch goes out active requests like changesets are temporary put on hold and resumed when ready, other possible causes of extended deployment time are size/types of component being deploy and how it affect/changes the org, heavy traffic on the instance or simply multiple deployment / validation holding up the total overall deployment process in the org.
However we need to remember there are no SLA with changeset, but if you want to deploy quicker and have more control over their deployment, then IDE / ANT is the way to go.
| 0.777778 | Changeset deployment usually does not have SLA and how long it takes to complete is not a benchmark on how long a deployment takes to |
Tcolorbox: force labelling to take on specific number | Using tcolorbox, how can I label a box and give the box whatever number I want?
\documentclass{memoir}
\usepackage[breakable]{tcolorbox}
\newtcolorbox[use counter=table,number within=chapter]{MijnOtherBox}[2][]{breakable,coltitle=blue!20!black,colback=black!1!white,colframe=black!10!white,title={Box~\thetcbcounter: #2},#1}
\begin{document}
\begin{MijnOtherBox}[label=Boxone]{Title for the box}
I want this box to be labelled with number 3.1 instead of \ref{Boxone}
\end{MijnOtherBox}
\end{document}
In fact my problem is that in my document there is an issue with the numbering of the boxes: in some chapters the numbering jump, e.g. Box 3.1, Box 3.2 and (!) Box 3.4, skipping 3.3...
| I'm not sure if the problem is skipping some values or setting them. This answer can help in the first case.
If you just want to skip one value, next code shows two possibilities:
\stepcounter outside the box or
step and label as tcolorbox option.
If you need to jump more than one value, use \addtocounter before the box.
Remember that the new value will be the base for following boxes.
\documentclass{memoir}
\usepackage[breakable]{tcolorbox}
\newtcolorbox[use counter=table,number within=chapter]{MijnOtherBox}[2][]
{breakable, coltitle=blue!20!black, colback=black!1!white,
colframe=black!10!white, title={Box~\thetcbcounter: #2}, #1}
\begin{document}
\begin{MijnOtherBox}[label=Boxone1]{Title for the box}
I want this box to be labelled with number 3.1 instead of \ref{Boxone1}
\end{MijnOtherBox}
\stepcounter{table}
\begin{MijnOtherBox}[label=Boxone2]{Title for the box}
I want this box to be labelled with number 3.1 instead of \ref{Boxone2}
\end{MijnOtherBox}
\begin{MijnOtherBox}[step and label={table}{Boxone3}]{Title for the box}
I want this box to be labelled with number 3.1 instead of \ref{Boxone3}
\end{MijnOtherBox}
\addtocounter{table}{3}
\begin{MijnOtherBox}[label=Boxone4]{Title for the box}
I want this box to be labelled with number 3.1 instead of \ref{Boxone4}
\end{MijnOtherBox}
\end{document}
| 1 | If you want to jump more than one value, use addtocounter before the box |
Apache won't allow multiple name-based virtual hosts | Here's the problem I'm facing: I've added multiple virtual hosts(name based) to apache yet still only one is loaded.
For example I have two domains with different contents.
Site1 Domain -> Site1 Content
Site2 Domain -> Site1 Content aswell..
I've included the httpd-vhosts file in the httpd config file, and I've edited it to match what it asks me to do on their documentation yet still only one folder of contents is served.
Here is my httpd-vhosts file, the httpd file I assume doesn't need posting but if required I shall:
NameVirtualHost *
<Directory "C:/www/">
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<VirtualHost *>
ServerName www.*****.com
DocumentRoot "C:\www*****"
</VirtualHost>
<VirtualHost *>
ServerName ****.co.cc
DocumentRoot "C:\www\****"
</VirtualHost>
ofcourse I removed the unnecessary comments and my domains names(private reasons). Oh yeah, and my server is hosted on Windows Server 2008 Standard
| First off, can you check the log files for errors when you start up Apache? It might be complaining, and it will give very useful information if it does..
Secondly, are you making similar changes to the SSL side of things? MOD_SSL is handled via a different config file, and if you're trying to access these sides of things on port 443, you're not going to get all the different sites working.
| 0.888889 | Can you check log files for errors when you start up Apache? |
How do I prevent unwanted routing errors in production | ActionController::RoutingError (No route matches [GET] "/google83362a7a0f381ff0.html"):
I see the above logs in production, how should I prevent it.
If user mistypes a URL, how should I re-direct to a common error page
| You can redirect the user to the desire page you want if no route matchs
Write down the following code at the bottom of your routes.rb file
In /config/routes.rb
#If no route matches
match ":url" => "application#redirect_user", :constraints => { :url => /.*/ }
Then redirect the user to the error page in the application_controller.rb file
*In /app/controllers/application_controller.rb*
def redirect_user
redirect_to '/404'
end
| 0.888889 | How to redirect the user to the desired page? |
Cannot shutdown Tomcat - transport Error | I am using Tomcat6.0.29. When I try to close Tomcat using shutdown.bat, it is not shutting down tomcat and also I don't see any update in log file for what happened. If I try to use "catalina stop" at the command prompt, I get the following error.
__Error: transport error 02: bind failed: address already in use
error: JDWP Transport dt_socket failed to initialize. Transport_Init<510>
JDWP exit error AGENT_ERROR_TRANSPORT_INT<197>: No transport initialized{../../..src/
sare/back/debugInit.c:690}
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT<197>__
Please let me know what should I do to fix this error. Thanks in advance
| Tomcat uses a different port for connections and for the command to shutdown.
By default the port is 8005. E.g. from server.xml
<Server port="8005" shutdown="SHUTDOWN">
The error you get indicates a conflict in ports.
Is it being used by another process? Are you doing remote debugging?
Change the ports to resolve conflict
| 1 | Is it being used by another process? |
What is the proper way to change the section title font in LaTeX? | Suppose I wanted to use a different font for a title then the body text in LaTeX (pdflatex). (For example, if I wanted to use a slightly fancier font for titles, or a sans-serif one.) How would I do that, change the font of a class of thing throughout the document, in a proper way. (Likewise, if I wanted to change the document title, captions, etc. Is there a general way of doing this?)
| I would say that really much depends on what you are trying to
achieve.
Do you want to make a class that others can use as well? You can
define your own commands for sectioning. Are there just minor
changes within one of your documents? Use package etoolbox and
patch your changes. Are there bigger changes to the sectioning
and titles? Package titlesec is commonly used with the standard
classes.
KOMA-classes have their own way of defining the font for various
instances of a document. The following example shows the
interface.
Disclaimer: This is just for demonstration, nobody should use
that many stuff in just one document.
\documentclass[plainheadsepline,headsepline=2pt]{scrreprt}
\usepackage{blindtext}
\usepackage{scrlayer-scrpage}
\usepackage{xcolor}
\RedeclareSectionCommand[font={\Huge\fontfamily{qhv}}]{chapter}
\RedeclareSectionCommand[font={\rmfamily\footnotesize\itshape}]{section}
\addtokomafont{captionlabel}{\usefont{T1}{qzc}{m}{it}}
\addtokomafont{caption}{\color{red!80!black}}
\addtokomafont{headsepline}{\color{red!80!black}}
\begin{document}
\chapter{lazy Leguan}
\section{walzing wombat}
\captionof{figure}{A figure caption}
\blindtext
\end{document}
| 1 | Do you want to make a class that others can use as well |
How is the energy/eigenvalue gap plot drawn for adiabatic quantum computation? | I was going through arXiv:quant-ph/0001106v1, the first paper by Farhi on adiabatic quantum computation.
Equation 2.24 says, $$\tilde{H}(s) = (1-s)H_B + sH_P$$ which means the adiabatic evolution starts from the ground state of $H_B$ and slowly evolves until it arrives at the ground state of $H_P$. In section 3.1, the one qubit example has the adiabatic Hamiltonian as $$\tilde{H}(s) = \begin{pmatrix}
s & \epsilon (1-s) \\
\epsilon (1-s) & 1-s
\end{pmatrix}$$
I don't see how the plot of Figure 1 is drawn. In figure 1, Farhi plotted eigenvalues of the Hamiltonian for s while the range for s was 0 to 1. The Hamiltonian is supposed to evolve according to the Schrodinger equation (eq 2.1), $$i \frac{d}{dt} |\Psi (t) \rangle = H(t) |\Psi (t) \rangle$$
Was this evolution solved to draw the plot? Or did Farhi derive the formula for eigenvalues in terms of s using just matrix math and plotted accordingly?
| The latter. The reason is because it doesn't make a lot of sense to do the eigendecomposition of an approximated Hamiltonian, which is what you're doing when solving for the dynamics (your operator probably won't be Hermitian so your energies won't even be real). Doing the evolution gives you the final state probabilities, but it's not very good for analyzing the energy gap precisely.
So you just plug in the right $s$ values and find the eigenvalues of that $H(s)$, and plotting that gives you the eigenspectrum in Fig. 1.
| 0.888889 | Doing the eigendecomposition of an approximated Hamiltonian |
\jobname in Gummi | The command \jobname usually print the file name without the path and extension, so inside a file called foo.tex will print just foo. With pdflatex foo.test or compiling from LaTeXila certainly I obtained this result. But from Gummi what I obtain is .foo.tex
Does anyone know why Gummi compiles differently and how I could get the usual \jobname behavior in Gummi?
Edit:
Based on helpful answers of @JosephWright and @Herbert
I wonder if it is possible to do the \jobname correction in Gummi only if the source have the .swp extensión or .tex persist in \jobname.
That is, I would like a solution like:
\makeatletter
\let\JobName\jobname
\ifthenelse{\equal{\detokenize{foo}}{\jobname}}
{}
{
\def\@JobName.#1.#2\@nil{#1}
\def\jobname{\expandafter\@JobName\JobName\@nil}
}
\makeatother
This conditional works to check if the jobname is foo or not, but I want a general solution, independent of the file name (not limited to the string foo).
| use in the preamble:
\makeatletter
\let\JobName\jobname
\def\@JobName.#1.#2\@nil{#1}
\def\jobname{\expandafter\@JobName\JobName\@nil}
\makeatother
then \jobname works as usual. The above is only useful for running a file with gummi.
| 0.666667 | makeatletter letJobNamejobname |
Is this formula in predicate logic a tautology? | $\left(\forall x \cdot p(X) \Rightarrow q(X)\right) \wedge p(Y) \Rightarrow q(Y)$
At first glance this seems like a tautlogy and that's what my notes say. But an interpretation where $p$ is always true and $q$ is always false seems to be a counterexample.
Can someone confirm this or show me where I've gone wrong?
Thanks.
| It is not a counterexample. In the case where $p$ is always true and $q$ is always false you have
$$(\forall X ,p(X) \Rightarrow q(X)) \qquad \mbox{ false}$$
$$(\forall X ,p(X) \Rightarrow q(X)) \wedge p(Y)\qquad \mbox{ false}$$
$$(\forall X ,p(X) \Rightarrow q(X)) \wedge p(Y) \Rightarrow q(Y)\qquad \mbox{ true}$$
since $\mbox{ false} \Rightarrow \mbox{ true}$ is true.
| 1 | $p$ always true and $q$ always false |
How is encapsulation used for safety? | I am learning OOP. I have studied much about encapsulation but the more I read the more I became confused.
I understand we hide (by making private) data and expose it to user of class (other developers) as properties or methods. I also understand by encapsulation we hide details.
In an article (http://www.csharp-station.com/Tutorial/CSharp/lesson19) I read:
Abstract from article
When designing an object, you must think about how others could use it. In a best-case scenario any program using the object would be well designed and the code would never change. However, the reality is that programs do change often and in a team environment many people touch the same code at one time or another. Therefore, it is beneficial to consider what could go wrong as well as the pristine image of how the object should be used.
In the case of the BankAccount object, examine the situation where code outside of your object could access a decimal Amount field or a string CustomerName field. At the point of time that the code is written, everything would work well. However, later in the development cycle, you realize that the BankAccount object should keep track of an int CustomerID rather than string CustomerName because you don't want to duplicate relationships between information (or some other valid reason to alter the definition of internal state). Such changes cause a rippling effect in your code because it was built to use the BankAccount class, as originally designed (with CustomerName being a string), and you must now change code that accesses that state throughout your entire application.
The object-oriented principle of Encapsulation helps avoid such problems, allowing you to hide internal state and abstract access to it though type members such as methods, properties, and indexers. Encapsulation helps you reduce coupling between objects and increases the maintainability of your code.
Question
How will encapsulation help when making changes in code and from its rippling effects.
For a data member, if I change its type from int to float, (even if I am exposing this using property) I will need to change variable type where I am using already using this code.
Kindly guide me how encapsulation will help with such changes.
Thanks for this help and guidance.
|
How will encapsulation help when making changes in code and from its rippling effects.
Let me give you a typical and simplistic example.
First, suppose you are not using encapsulation:
You have a set of data and use an array to store that data, and there is another part of your program that uses that array. Now, if at some point you decide that a linked list is a better choice for storing your data. If you replace array with linked list, what is going to happen? Your program will break, unless you make changes all over the place to replace the array-processing logic with linked-list-processing logic.
But, if you use OO/Encapsulation, then you probably partition your program into classes, one that store the data, and other, that uses the data. In the first class, you hide your implementation (encapsulation), and expose your services through methods like
size()
remove(int index)
add(int index, Object o)
get(int index)
...
In this second case, if you change the implementation of the storing class from array to linked list, or to any other thing, it will not affect your clients. No ripple effect.
| 0.666667 | How will encapsulation help when making changes in code and from rippling effects? |
Open Source Scripting Languages that work well with Microsoft SQL Server | I have been using PHP for a number of years now and have found it to be (relatively) well documented, easy to work with, to setup and to use.
One of its main advantages is its capablility of working, without many modifications, similarly on a Windows or *nix platforms.
It also has good support for connecting to Microsoft SQL Servers, in particular 2005 + 2008 through the mssql module + ntwdblib.dll or FreeTDS.
That being said, the more time I spend developing PHP, the more I feel the need to pick up another scripting language to broaden my skill set and to develop better web-based applications.
Because of this I've spent some time exploring alternative scripting languages in an effort to evaluate their suitability.
At present the biggest hurdle I have come accross is support provided by recent versions of the Open Source scripting languages, specifically: Python 3.2.2, Ruby 1.9.2, Node 0.5.7 for the Windows OS (WinXP in my case) and Microsoft SQL Server (2005 + 2008).
My existing working environ necessitates the requirement for connecting to a MSSQL database.
I'm looking for answers from developers who have experience working with either Python, Ruby or Node.js and using them to interacting with a MS SQL Server.
What would be your recommended Open Source scripting language which has good support for MS SQL Server.
Ideas welcome.
-P.
| Both Ruby and Python should be able to connect to MS SQL databases.
Python libraries:
PyTDS
pymssql
Ruby libraries:
TinyTDS - doesn't seem to be DBI compliant, but there is an ActiveRecord adapter.
| 0.888889 | Python libraries: PyTDS pymssql |
iCal Google Sync -- how to get rid of folders (delegates)? | I've got my calendars in Google, but when I sync them with iCal I get all these ugly folders. How can I clean this up?
| Short Answer: You cannot easily clean that up.
Long Answer: When you have delegate calendars, that typically means that you are given permission to view (maybe edit) someone else's calendar. This is why there is special interface to deal with delegation and they are grouped in their own section of the calendar list.
Behind the scenes, google treats each calendar you create as its own principal (almost like its own account), so iCal treats all the non default calendars as delegates. To confuse things further, you can actually can share google calendars so iCal could never tell the difference between an actual shared calendar and new calendar you added.
The only solution is to move all your events into the default calendar or move your calendars to a service which handles multiple calendars in a better way (Yahoo, Exchange, iCalServer)
| 1 | Delegate calendars are grouped in their own section of the calendar list |
Low beam headlights don't work, High beam headlights do | The vehicle is a 2003 Chevrolet Trailblazer. The low beams aren't working. High beams are. The fuse is perfectly fine (tested and swapped out). The bulbs are fine too.
A mechanic told me it could be the "body modulator". I've never heard of this before. Could this be the problem? If so, how hard is it to change out for a shade tree mechanic?
If not, what else could this be?
| I'd get a multimeter and check though the circuit - as Brian says the point at which the current is switched is a common failure point - either in the switch or the relay if one is fitted. I've never heard of a body modulator and can't see how one would be fitted in a headlamp circuit!
| 0.888889 | How do I get a multimeter and check though the circuit? |
android using async http connection to get image bitmap | I am trying to use async requests to fetch the images from urls, to prevent the url from hanging. This is the piece of code i am using for this
private void setImg(final ImageView im, String url){
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
public void onSuccess(String response){
try{
byte[] imageAsBytes = response.getBytes();
im.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
im.refreshDrawableState();
} catch(Throwable e){
e.printStackTrace();
}
}
});
}
This is always showing this warning in logcat
12-29 01:55:33.043: D/skia(14414): --- SkImageDecoder::Factory returned null
I cannot find a proper reason for this. Any help?
| Now that a binary response handler has been added to AsyncHttp you can simply use androids BitmapFactory.decodeByeArray function:
AsyncHttpClient client = new AsyncHttpClient();
client.get(image_url, null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(byte[] fileData) {
Bitmap image = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
//Do whatever you want with the image variable
}
});
| 0.888889 | BitmapFactory.decodeByeArray |
What technique/sensor can I use to recognized tagged objects thrown onto a surface? | I am trying to implement a concept for somebody else.
Basically, I want to create a smart surface. I want to create a surface I can throw one or more tagged objects on that should all be recognized.
I am unsure how to this and what sensors I should use. I have been thinking about using one of the NFC ICs from NXP. However, designing a circuit board and buying this IC is too expensive for our idea. I'm also unsure of whether the surface area will cause problems, because it'll be quite large (think of a small coffee table).
I've also been thinking about other ways to recognize objects, but I have not come up with anything yet. I am probably not using the correct term.
Does anyone know of a type or sensor or technique to implement this?
Note: I am a computer engineer, not an electrical engineer. I know the basics, but really not much more than that, so I prefer a solution that is available as a simple IC or a complete circuit board with the really complicated things done for me by the experts :)
| A better solution might be to use printed tags and image recognition. There are open source solutions for this - for instance, trackmate. All you will need is a printer, a camera, and a transparent (or possibly frosted) surface.
| 1 | Print tags and image recognition can be a better solution . |
Configuring a tftp server for multiple clients | I am using a tftp server to hold the boot image for a dev board and the dev board is hard-coded to look at a particular IP address for the server. This all works fine. What I want to do now is be able to set up a second dev board to look at the same IP address for the server, but get a different boot image. I would like to do this by having the tftp server use a different root directory based on the IP address of the client connecting to it. Is there a way to do this?
I realize there may be some way to do this with iptables, but I have to turn the firewall on the server machine off entirely for other reasons, so that may not be terribly practical.
For reference, I'm using Fedora 15 for the server, but that can be changed if need be.
| DHCPD or not?
You don't say but I'm assuming that you have some PXE configuration file that this DEV board is setup to look for. Typically you'd tell the DHCP clients what PXE image to use like so via a DCHP server:
subnet 192.168.0.0 netmask 255.255.255.0 {
range 192.168.0.10 192.168.0.49;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.0.255;
option routers 192.168.0.1;
filename "pxelinux.0";
next-server 192.168.0.100;
}
The TFTP server would be the next-server 192.168.0.100, and the file to load would be filename "pxelinux.0". But since you don't have this setup your DEV board is looking for a the "next-server" at a specific IP address, I'm going to assume that it's looking for a specific PXE file too.
Using PXELINUX
This solution would assume you have control over pointing the DEV board at a particular "filename", in this case I'm suggesting you use PXELINUX, the file would be pxelinux.0.
PXELINUX allows you to have custom images based on a system's MAC address is the more typical way to do it, since system generally don't have an actual IP address assigned to them in a static way, whereas the MAC addresses are static.
Setup
On the TFTP server's root directory you'd then create something like this:
/mybootdir/pxelinux.cfg/01-88-99-aa-bb-cc-dd
/mybootdir/pxelinux.cfg/01-88-99-00-11-22-33
/mybootdir/pxelinux.cfg/default
Each MAC address above is a file with the appropriate boot stanza in it for each system. Here's mine from my Cobbler setup:
$ ls -l /tftpboot/pxelinux.cfg/
total 88
-rw-r--r-- 1 root root 292 Jul 9 2012 01-54-52-00-05-5a-ab
-rw-r--r-- 1 root root 288 Jul 9 2012 01-54-52-00-17-a6-cd
Along with a sample file:
$ more /tftpboot/pxelinux.cfg/01-54-52-00-05-5a-ab
default linux
prompt 0
timeout 1
label linux
kernel /images/Centos56-x86_64/vmlinuz
ipappend 2
append initrd=/images/Centos56-x86_64/initrd.img ksdevice=bootif lang= console=ttyS0,115200 text serial kssendmac ks=http://192.168.1.101/cblr/svc
/op/ks/system/server123
The above can be paired down to suit your needs, but should be enough of an example to get you started, there additional examples up on the PXELINUX website as well!
| 0.888889 | Using PXELINUX This solution would assume you have control over pointing the DEV board at a specific IP address |
How does an embryo know where to grow limbs etc | For example you have a cell or already a bunch of cells. Those cell(s) divide and after several week you have a grown organism, for example a human with limbs, several different organs etc.
However, how do cells know where up, down, left, right etc. is?
I know left and right can be defined clearly in physics. However how do cells define those directions and what are mechanisms for them to grow into a certain direction?
Is there a paper or a longer article dealing with that question/problem?
I don't think my knowledge on Biology goes far beyond high school level maybe 1. term at a university. If I have to, I would read and learn everything I need to know to understand the matter.
| Embryonic cells "know" where they are relative to each other by chemical signals, same as in adults. These molecules are known as morphogens (specific examples include the sonic hedgehog and β-catenin). The amount of morphogen in a region of cells determines which gene gets turned on and thus what it develops into. And the amount varies by how far they are from the source of the morphogen. Though AFAIK, scientists don't fully understand their mechanisms yet (like how they are dispersed, how the different concentrations are kept rigidly, etc.).
As for arms, etc., the earliest cells are unspecialized (stem cells). They "define" which becomes what early on by how they are arranged. Remember that their "up, down, left, and right" is relative to them, not to their surroundings. The first multicellular hollow ball of stem cells, the blastula, separates into distinct germ layers during gastrulation - the ectoderm, mesoderm, endoderm. Each of these layers develop into something different upon further division. What develops after that is basically a worm, composed of a series of repeating "segments" (somites) with a distinct head and tail area. Somites are initially undifferentiated. The job of determining which segment becomes what falls on Hox genes. So that for example, one segment becomes the head, another becomes the arm and pectoral girdle, another becomes a rib+vertebra, etc. Hox genes are arranged in clusters within the DNA relative to which gets expressed first. The first hox gene is for the head for example, while the last is for the tip of the tail (the tipmost segment of the coccyx in humans). Though these clusters themselves are often repeated into a kind of redundant failsafes. This page from the University of Utah explains it pretty well. It helps if you view embryogenesis as more or less echoes of evolution in fast forward.
| 0.777778 | Embryonic cells "know" where they are relative by chemical signals, same as in adults . |
Can the Mage Wars Warlock be played without any Demon cards? | As the subject states, I was wondering if the Mage Wars Core Set comes with enough Fire type cards to allow the Warlock Mage to build a spellbook with absolutely no Demon cards. Without seeing the cards, I will assume that most, if not all of the other Dark magic cards are OK, but I would ultimately prefer a pure Fire Magic spellbook.
So as to preemptively answer the almost inevitable 'Why?', I will simply say that, as an orthodox Christian, my conscience doesn't allow me to play a game with such cards. I would prefer not to debate/explain this further, as I believe such a discussion is well beyond the scope of this site.
| In the starting Core Set I would have to say that it would be a very tough if not an impossible feat to be able to play the Warlock without the Demon cards, as there is only one Flame type creature, but it just happens to also be a Demon. So you would have to spend quite a bit of your deck points on the doubled points from creatures not being a dark or fire type.
This may be doable, as you may be able to counter balance with some of the powerful Flame attack spells that can really do some damage, especially when combined with an equipment called Elemental Wand, to allow you to bind and recast the attack spells each turn.
| 1 | How to play the Warlock without the Demon cards? |
Simulating an automotive load dump with a bank of charged capacitors? | I've been working on a data logging device that will eventually go into my personal vehicle. I've scoured the interwebs and built what, in theory, should be a fairly stout power supply capable to handle fast transients and undervoltage and the fabled load dump. My problem is, though... I want to actually test the power supply.
In previous questions that I've asked related to the design of the power supply portion, I've been told that the "right way" to simulate a load dump is with a proper, preofessional testing device. I'm curious, though... what's stopping me from rigging up something that is "close enough"?
My idea is simply this: get a low-voltage DC power source, such as an old PC power supply. Get a DC-DC converter to step that 12V up to something in the 80V range. Assemble a bank of capacitors to get me in the neighborhood of a theoretical 12V load dump.. which from what I can tell is in the hundreds of joules range. Once charged, simply connect it to the battery input of the device - which wouldn't be connected to an actual power source lest I want to potentially screw that power source up - and see if explodes, and if not, see if it works normally afterwards.
Does this sound like the dumbest idea you've ever heard? Is it a somewhat decent idea that simply needs a lot of planning and number checking to in order to work roughly as intended?
| A load dump is what happens to an automobile electrical system when a large load (such as the headlights) switches off. The problem is that the charging system (primarily the alternator) has significant inductance, and any attempt to rapidly reduce the current draw results in an "inductive kick" that creates a large voltage spike on the 12V bus. This kick is the same phenomenon used to create the spark in the ignition system, just a different manifestation of it. The point is, any equipment that's attached to the 12V bus needs to be able to withstand these occasional 100-200V voltage spikes without damage.
Since load dump is primarily an inductive phenomenon, it would probably be easier to simulate it that way, too. You don't really need to simulate the full energy of an actual automotive load dump; you just need to create the same voltage waveform across the supply terminals of your device.
Put a largish inductor (L1, on the order of 1H, perhaps the primary of a large power transformer) in series with your device (i.e., connect the device to the power supply through the inductor). This represents the inductance of the automobile charging system.
Put a few µF of capacitance (C1) across (in parallel with) your device; this represents the distributed capacitance of the automobile wiring, and helps to limit the risetime of the load dump event. Make sure this capacitor is rated for a few hundred volts.
Put a 120Ω resistor (R1) in parallel with your device, too. This represents other static loads within the automobile, and will set an upper limit on the peak voltage that the load dump creates. (This resistor will be drawing 100 mA and dissipating 1.2W.)
Now, connect a low-value, high-power resistor (R2) across your device, in series with a switch (SW1). This represents the load that is going to get "dumped". The value of the resistor should be such that the DC current doesn't exceed the power supply's capability, and you can adjust the value of the resistor to change the current with respect to the value of the inductor to dump a specific amount of energy (0.5×I2×L). For example, if your inductor is 1H and your resistor is 12Ω (@ 12W), you'll be drawing 1A, and the stored energy will be 0.5 Joules.
Close the switch to "charge up" the inductor, then open it — there's your simulated load dump event. With these resistor values, the peak voltage will be on the order of 100-120V. You can use different combinations of resistor values to simulate different kinds of events. The ratio of R1 to R2 approximately determines the peak voltage of the spike (relative to the power supply voltage). Scale both resistors downward to simulate higher-current (higher-energy) events. Make the capacitor smaller to get faster risetimes; 1H and 1µF resonate at 160Hz, which gives you a fairly leisurely 1.5ms risetime (1/4 cycle). For example, changing C1 to 0.01µF would give you a risetime of about 150µs.
| 0.777778 | a load dump is what happens to an automobile electrical system when a large load switches off |
Why do I have house flies in my carport? | I bought my home in early September 2012. I noticed that flies were flocking around a light in my open air carport whether it was on or off. I tried a few products like fly tape, spray and a fly trap. Still no results. This continued through fall until temps dropped. This Spring I thought I would take preventive measures and cleaned my entire carport with Lysol including my garbage cans which are new. But still flies are flocking around this light. Its strange, they don't land on it that much as if there were some food source. They just fly around it all day until the sun goes down and even then there are a few stragglers. I would say at peak during the day there are about 150 to 200 flies. Why are they attracted to this area and What do I do to get rid of them?
| Is it possible that these are not your regular house flies but instead something called a cluster fly?
I've seen these flies make a nuisance of themselves in the ceiling of one house of a friend. He had to get it fumigated. After that, no problems.
Is your carport right next to your house? is the light attached to the carport or to the house? Could there be a little nest in there somewhere?
| 1 | Is it possible that these are not your regular house flies but instead a cluster fly? |
A verb for transforming something into currency | I need a verb that expresses the concept of transforming a raw material into currency, as in this sentence "The bitcoin manufacturing process currenciates digital information."
New coinages are fine if they make sense and are less clumsy than the one I used above, but an existing term would be preferred. I've considered the word mint but that seems to relate more to the final product than the raw material -- in other words, you mint coins (the finished product), you don't mint gold (the raw material).
| Monetize to coin into money; also : to establish as legal tender
| 1 | Monetize to coin into money; also to establish as legal tender |
Relationship between user story, feature, and epic? | As someone whose still new to agile, I'm not sure I completely understand the relationship or difference between a user story, feature, and epic.
According to this question, a feature is a collection of stories. One of the answers suggest that a feature is actually an epic.
So are features and epics considered the same thing, which is basically a collection of related user stories?
Our project manager insists that there's a hierarchical structure:
Epic -> Features -> User stories
... basically all user stories must fall within this structure. Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.
To me, that sounds awkward. Can someone please clarify how user stories, features, and epics are related? Or is there an article that clearly outlines the differences?
| I caution you against applying too rigid a hierarchy to these terms. We tried to do that in my previous job. Twice. Both attempts were different and both times we found we had unnecessarily limited ourselves. The only constant was the definition of a User Story. From a planning perspective, a story is the basic building block of a project. The larger terms (epic, feature, etc.) are effectively just tags. Tags are an easy way to allow a story to exist as part of multiple Epics and multiple Features at the same time. It's not worth the mental effort to be more strict than that.
Tags work for Stack Exchange and they can work for you too.
| 0.888889 | Tags are an easy way to allow a story to exist as part of multiple Epics and multiple Features |
How do I stop Windows from moving desktop Icons? | I have two monitors connected to my computer. (same graphics card. One HDMI, the other DVI).
Whenever I do one of the following things, my icons move around on my desktop:
Play a Game
Turn off one monitor
When I stop playing the game or turn one of the monitors back on, Windows 7 does not properly restore the icon locations.
Is there is a way I can prevent Windows from moving my desktop icons around?
| No. When the screen resolution changes, Explorer will automatically move icons that would otherwise be off-screen.
(Imagine the complaints if it didn't do that. "I changed my monitor and now half my files are gone!")
| 0.888889 | When screen resolution changes, Explorer will automatically move icons that would otherwise be off-screen |
How to store length of time in a model with Rails? | I can think of two solutions:
1) Store hours, minutes, seconds, etc. in separate columns in the database
Downside: a lot of columns
2) Convert and store the number of seconds
We still want to be able to show seperate fields for hour, minute, second, etc. in the form. We could write virtual attribute for each of these and write a before_save callback that converts the timespan to seconds (still messy tho).
Am I missing some other obvious solution? How do you people do this?
| I vote for a single column to keep track of durations. That keeps the duration normalized, whereas you'll need to do almost as much work or more to normalize multi-column durations.
Rails (activesupport) also gives you wonderful methods to work with time. For example, if your duration is in seconds, you can easily add the duration in seconds to a point in time and get an end time:
end_time = Time.now + duration_in_secs
It is a bit more work using virtual attributes to separate it out, but in my experience, it's not that more work. perhaps there is a plugin or gem that simplifies it.
| 0.888889 | Rails (activesupport) allows you to keep track of multi-column durations |
Meteor renderList intercept? client side | I have chat messages displayed like this:
{{#each msg}}
{{> chatMsg}}
{{/each}}
When users enter the chat I add a document to the collection with user joins the chat. When a user rapidly reenters and leaves the chat I don't want to duplicate user joins the chat over and over again. I want to display something like user joins the chat x3.
Is there a way to do this on the client side by hooking into renderList? I know I can change the doc on the server side but it seems unnecessarily intensive.
| One option is to make a method call that just updates the latest user joined message.
function formatJoinMessage(username,count) {...}
if (Meteor.isServer) Meteor.startup(function () {Chats._ensureIndex({modified:-1}); ...});
Meteor.methods({
join:function() {
var joinMessage = Chats.find({type:MESSAGE_TYPE_JOINED,userId:this.userId}).sort({modified:-1}).fetch()[0];
if (joinMessage)
Chats.update({_id:joinMessage._id},{$inc:{joins:1},$set:{text:formatJoinMessage(this.userId,joinMessage.joins+1),modified:new Date()});
else
Chats.insert({user:this.userId,joins:1,modified:new Date(),text:formatJoinMessage(this.userId,1)});
}
)};
Don't want to change the server doc? That's okay, but conceptually a chat join isn't a chat message. So you should definitely have a meta field for stuff like this in your chat documents.
But supposing you don't want to do that. I'd do something like this:
var userIdToName = function(userId) {...}; // some kind of userId to name helper
Template.chatroom.msg = function() {
var messages = Chat.findOne(Session.get("currentChat")).messages; // msg in your code?
return _.reduce(messages,function (newMessages, currentMessage) {
var lastMsg = newMessages[newMessages.length-1];
if (currentMessage.type == MESSAGE_TYPES_JOIN) {
if (lastMsg && lastMsg.type == MESSAGE_TYPES_JOIN && currentMessage.user == lastMsg.user) {
currentMessage.timesJoined = lastMsg.timesJoined+1;
newMessages.shift();
} else {
currentMessage.timesJoined = 1;
}
currentMessage.chatMsg = userIdToName(lastMsg.user) + " joins the chat &mult;" + currentMessage.timesJoined.toString();
}
return newMessages.concat(currentMessage);
},[]);
}
This is a bit of a doozy. Suffice it to say, it "reduces" all the join messages it finds in the chat's current messages down to one message. You dynamically add the property timesJoined; it does not appear in the document. But you should have a type field that lets you know the difference between a join message and a regular message is.
If you don't even have that metadata at minimum, then your chat application isn't going to work very well. Don't hesitate to change your model!
| 0.888889 | How to make a method call that just updates the latest user joined message? |
Reading Metadata from Instruction | I want to extract all metadata information attached to a instruction. I tried to extract this information using getAllMetadata.
Can someone explain me why the following code doesn't print the name for the metadata nodes?
Note: I is an instruction
.
.
.
I->getAllMetadata(MDForInst);
for(SmallVector<std::pair<unsigned, MDNode*>, 4>::iterator II = MDForInst.begin(),
EE = MDForInst.end(); II !=EE; ++II){
outs()<<"name: "<< II->second->getName() << "\n";
}
.
.
.
| Despite inheriting the getName method from Value (and a few similar methods), MDNodes don't actually have names.
If you have something like:
<instruction>, !mymetadata !5
and you want the string "!mymetadata", you need to use the "kind" value - that unsigned value in each pair - to get the custom metadata name from the module. The code would like something like (roughly, didn't check it myself):
SmallVector<StringRef, 8> Names;
M.getMDKindNames(Names);
for(SmallVector<std::pair<unsigned, MDNode*>, 4>::iterator
II = MDForInst.begin(), EE = MDForInst.end(); II !=EE; ++II) {
outs() << "name: " << Names[II->first] << "\n";
}
| 0.888889 | MDNodes don't actually have names . |
Linux : how to redirect stdout & stderr to logger? | I have a program I need to run at startup, it has output on stdout and stderr that I want to redirect to the system log using the logger command. What I have in my startup script is thie:
/home/dirname/application_name -v|logger 2>&1 &
This is redirecting the stdout to syslog just fine but stderr is coming to the console, so I need some help on refining the command.
| You need to combine the output of STDERR and STDOUT prior to piping it to logger. Try this instead:
/home/dirname/application_name -v 2>&1 | logger &
Example
$ echo "hi" 2>&1 | logger &
[1] 26818
[1]+ Done echo "hi" 2>&1 | logger
$ sudo tail /var/log/messages
Apr 12 17:53:57 greeneggs saml: hi
You can use the abbreviated notation here as well, if used cautiously in a actual Bash shell (not to be confused with Dash):
$ echo "hi" |& logger &
NOTE: This is equivalent to <cmd1> 2>&1 | <cmd2>. Again only use the above when making use of an actual Bash shell interactively, would be a good way to approach it.
excerpt from ABSG
# |& was added to Bash 4 as an abbreviation for 2>&1 |.
References
Advanced Bash Scripting Guide - Chapter 20. I/O Redirection
| 1 | Use the abbreviated notation in a Bash shell |
What are the programming languages for GPU | I read an article stating that GPU are the future of supercomputing. I would like to know what are the programming languages used for programming on GPU's
| OpenCL is the open and cross platform solution and runs on both GPUs and CPUs.
Another is CUDA which is built by NVIDIA for their GPUs.
HLSL,Cg are few others
| 1 | OpenCL is open and cross platform solution and runs on GPUs and CPUs |
Opening a file on unix using c++ | I am trying to open a file in c++ and the server the progam in running on is based on tux.
string filename = "../dir/input.txt"; works but
string filename = "~jal/dir1/dir/input.txt"; fails
Is there any way to open a file in c++ when the filename provided is in the second format?
| The ~jal expansion is performed by the shell (bash/csh/whatever), not by the system itself, so your program is trying to look into the folder named ~jal/, not /home/jal/.
I'm not a C coder, but getpwent() may be what you need.
| 0.888889 | jal expansion is performed by shell (bash/csh/whatever), not by the system itself |
Can i transfer money via Indian bank atm to citibank account? | I have a Bank Account with Indian Bank.
Is it possible for me to transfer money from my Indian bank account via atm to Citibank Account?
If Yes what the steps to do this.
| In India, transferring to other banks is available mostly on Internet banking. Some banks are offering Transferring option within the bank in ATMs. You need to visit the bank branch to register and activate this Transfer option for intra-bank accounts.
| 1 | In India, transferring to other banks is available mostly on Internet banking |
Biscuit, dowel or simple braces for making unit top with inset lid and slim sides? | I've had 5 pieces of iroko machined for creating a top to my DIY TV lift, complete with a lid for the TV to pop up through:
The dimensions are based on the pre-existing cabinet, and the lid size needed for the TV to rise up. I was originally taking my cue from this YouTube video wherein he joins his (very long) pieces with biscuits; however now I have my pieces I'm concerned that:
The two sides are too slim to really hold the whole thing together with any strength (as I imagine I could only use one biscuit on each side);
The boards may be relatively slim (20mm) and as such need small biscuits or dowels, compounding point 1.
Bearing in mind that a) I'm a total novice, and b) I don't own a biscuit-cutter, I was wondering whether a far easier solution might be to use one or two 'braces' (apologies if this is not the correct term) running on the underside of the lid, on either side, joining the front and back pieces and spanning the shorter side pieces. These would be hidden inside the unit once the lid is in place, so it shouldn't affect the look.
Although the top isn't structural, it should still be solid and sound, and most likely need to at least bear the weight of a graceless cat who will hurl his body at any piece of furniture like a sack of potatoes.
TL;DR Illustrations
Biscuits:
Braces:
| Honestly for solid wood boards (hardwood in your case) just applying wood glue and clamping would provide more than sufficient strength to hold the weight of a cat. Simple glue joints are used to make table tops without additional fasteners. The strength of the glue joint is generally stronger than the wood itself and since your boards have already been machined they provide great gluing surfaces. Just don't clamp so hard you squeeze out all the glue.
20mm (a little more than 3/4") is plenty thick to use most fastening systems including biscuits or dowels. Biscuits you need a special bicuit cutting tool which can be expensive. Dowels benefit from a jig to get them to line up properly. My personal choice is to use pocket screw holes for applications like this.
A Kreg Mini jig will suffice for your needs as long as you have a power drill and only costs about $13 and you don't need expensive bar clamps as you would with glue alone but a face clamp would benefit to keep everything flush. You can also just use standard quick clamps though. I use mine frequently but there are more advanced models that make positioning easier. I have comparisons of the different Kreg Jig models on my site.
The way I would do it is to drill the pocket screw holes on the undersides of the boards using 3 screws on each side, 1 of which is screwed onto the long board. 2 screws per side would be adequate but I like to have some on the alternate board for glueups like this.
| 1 | Using wood glue and clamping to make table tops without additional fasteners |
Power loss from an inductive load | A problem reads "A single phase 50 Hz generator supplies an inductive load of 5000 kW at a power factor of 0.707 lagging ... "
How can there be real power loss from an inductor?
| With a 5 GigaWatt generation of power, caused by heavy industry with motor driven inductive loads it raises the reactive current which doesn't get counted as "real" power consumption but is a cost to the provider, as it reduces the capacity limited by current in distribution losses. Motors have inductance but do work (consume real power) and have losses and dissipate heat from many causes, such as winding resistance.
To resolve this, switchable capacitor banks are manually or automatically adjusted near the sub-stations to raise the power factor and reduce the peak current back to the source. They select +VARS of phase leading current from banks to offset some of the -VARS from the loads to reduce distribution losses and improve capacity for real power to be sold.
So even though as consumers we are measured by real power, with all our fridge and air condition motors running, power providers need to raise the power factor when additional capacity is required or to reduce the distribution losses which can be as much as 10% in cable resistive loss. But in large hydro power stations this is still the most efficient power source.
the above answer was intended to offer a bigger picture of what power factor means to a 5GW power station. We obviously are not dealing with just inductors here but in general "inductive loads". Inductive Power factor is different from power Factor caused the growing issues of SMPS effects of current pulses before peak voltage. Olin has already clearly stated the theory & fundamentals already. So maybe this should just be a side comment to put it in perspective on a large scale power network. I was not trying to compete with a better answer, just add practical value.
| 0.666667 | 5 GigaWatt generation of power, caused by heavy industry with inductive loads |
Facebook API: is it possible to get a user's public profile data by email address? |
Possible Duplicate:
Find Facebook user (url to profile page) by known email address
I have a list of email addresses from people that use my app. Is it possible to query for their facebook public data by email address?
Thanks Richard.
| Any application can fetch users(application authorized users) facebookID in user basic information via graph api or fql.
for exa.
https://graph.facebook.com/me?access_token=[facebook returned access token]
it will return these information in JSON
{
"id": "100001114785800",
"name": "Stella Jackson",
"first_name": "Stella",
"last_name": "Jackson",
"link": "http://www.facebook.com/profile.php?id=100001114785800",
"birthday": "04/16/1987",
"gender": "female",
"interested_in": [
"female"
],
"timezone": 5.5,
"locale": "en_US",
"updated_time": "2010-10-08T13:26:10+0000"
}
Once you get user ID you can fetch user picture via graph api
https://graph.facebook.com/[user facebook id]?fields=id,name,picture
https://graph.facebook.com/100001114785800?fields=id,name,picture
OR
https://graph.facebook.com/100001114785800/picture?type=small
type can be small, normal, large, square
Best luck Richard
| 1 | How to fetch users facebookID in graph api? |
Serial connection between Raspberry Pi and Roomba | I have a Raspberry Pi with this FTDI cable and a Roomba 560. The Roomba has an SCI port to allow for control of the roomba via serial. I installed the PySerial library on the pi and send valid commands to Roomba, but the roomba doesn't respond. I have the TXD of the cable attached to the TXD of the roomba, the RXD on the cable wired to the RXD on the roomba, and a ground on the cable wired to the ground on the roomba (everything in it's respective port). I do not have power going from the cable to the roomba or vice-versa.
What I can't figure out is why the commands aren't working. There's no error message upon running the python code. This is the information sheet for the Roomba's SCI port.
Code:
import serial
ser = serial.Serial('/dev/ttyUSB0')
# this is the defualt Roomba baud rate
ser.baudrate = 57600
# Start SCI - puts into safe mode
ser.write(chr(128))
# Enable full mode
ser.write(chr(131))
# Spot clean
ser.write(chr(134))
print 'Done'
| Sounds like you have the Pi and Roomba both talking on the same wire, and both listening on the other wire.
Connect the Pi's TX line to the Roomba's RX line, and vice versa.
First rule for troubleshooting serial communications: Swap connections on pins 2 and 3!
| 1 | Connect Pi's TX line to Roomba's RX line |
How to Investigate Wi-Fi Intrusion and where to look for evidence? | I'm trying to figure out how to configure a network so that I can tell what an intruder did (in the past) while on the network after they are detected.
eg. If someone with a wi-fi enabled laptop parked outside my home and connected to my home network because he was able to crack my weak encryption. and if he were to do some fraudulent activity from my network, how can I configure my network and where would I have to look on the network to see what he was up to?
What devices would be able to log valuable information and how would I make sense of this information?
| Since I now know your question is theoretical, I can answer it better about how you can setup your network so you would be able to tell. The exact way of setting it up will vary from device to device, but there are a lot of options available. The key is that you need a device capable of logging that is in a location on the network that everything the person does will go through it.
For an average home network, this could be either the Wireless Access Point, the Router or if applicable, the gateway or firewall. The wireless access point will get the information right as they get on to the network and will ensure that all activity coming in on the wireless network is logged, but if they were to use their wireless connection to compromise a wired system and then use the wired system, you would have an incomplete log.
Most likely the Router also serves as the gateway and firewall (the device that gives the rest of the network access to the Internet and ensures the Internet doesn't have unintended access to the private network). Logging at the gateway and/or firewall ensures that all outbound traffic is logged, but won't tell you anything about what the intruder did internally on your network.
In most home networks, since there is only one router and it also generally serves as wireless access point, gateway and firewall, it will end up being privy to all connections flowing across the network. It may not have access to all the contents of the packets it routes (if encryption is used) but it at least (by necessity) has access to the routing information (ie, where it is coming from and where it is going). This is likely the best place in a home network to log.
Most consumer routers do not have this kind of logging by default, however third party firmwares such as DD-WRT often add logging capability to the routers that can either write to an internal store (limited space) or a network share. Exactly what information can be stored and how it is formatted varies from device to device, but in general information like the IP and MAC Address of the client as well as the requested destination IP, Port and protocol (such as TCP or UDP) as well as a timestamp can give you a lot of what you need to get at least a general idea of what was going on.
If space is no object, it may even be possible to log the content of every packet sent across the network, but that will be a huge amount of space and it may not be safe to exclude "known" MAC addresses from the logging to try and reduce the amount since MAC spoofing is fairly easy on a wireless network. (IE, the intruder can make themselves look like a valid machine) Of course, if you are going to this kind of length, you could also do a per machine certificate and/or not use a weak key at which point the problem would likely be avoided in the first place.
| 1 | How to set up a wireless access point in a home network |
SQL how to count the number of credit cards that had at least 1,5,10,20 etc transactions | I have a data set of credit card transactions.
create table trans (
card_id int,
amount int
);
insert into trans values (1, 1);
insert into trans values (2, 1);
insert into trans values (3, 1);
insert into trans values (4, 1);
insert into trans values (5, 1);
insert into trans values (5, 1);
insert into trans values (6, 1);
insert into trans values (6, 1);
insert into trans values (7, 1);
insert into trans values (7, 1);
insert into trans values (8, 1);
insert into trans values (8, 1);
insert into trans values (8, 1);
insert into trans values (9, 1);
insert into trans values (9, 1);
insert into trans values (9, 1);
insert into trans values (10, 1);
insert into trans values (10, 1);
insert into trans values (10, 1);
insert into trans values (10, 1);
I desire to know:
1. how many cards were used to make at least 1 transaction
2. how many cards were used to make at least 5 transactions
3. how many cards were used to make at least 10 transactions
4. how many cards were used to make at least 20 transactions
etc...
SQL:
select count, sum(count2) from
(
select count, count(*) count2 from
(
select card_id, count(*) count
from trans
group by card_id
) d
group by count
) d2
where count> {is at least __} /*this is the part causing an error*/
group by count
order by count
You have an error in your SQL syntax...
http://sqlfiddle.com/#!9/705b5/5
| Because the groups overlap, I think conditional aggregation is a better approach:
select sum(cnt >= 1) as trans_1,
sum(cnt >= 5) as trans_5,
sum(cnt >= 10) as trans_10,
sum(cnt >= 20) as trans_20
from (select card_id, count(*) as cnt
from trans
group by card_id
) d;
| 1 | Conditional aggregation: select sum(cnt >= 1) as trans_1, sum (cn |
Where to find ferry flights and empty leg flights? | Based on this question Avoiding crew fatigue on empty leg flights I learned that there are "empty leg" flights or "ferry flights".
These seem a good option but I would like to know more about them.
Where are these announced? How can one travel this way?
| Corporate/Business Aircraft
For corporate aircraft, this is a common occurrence and there have indeed been attempts to utilise these legs. A quick search on Google for empty legs turns up plenty of results. I came across two companies called flyvictor and returnjet that offered a bunch of flights from all spots in Europe.
Another similar possibility is getting a ticket for an extra seat on corporate jets that are not 'ferry flights' but simply have extra capacity. This article ("How to fly on a private jet for under $200 per person") might interest you.
Note:
They are 'opportunist' in nature. There is no guarantee a flight will turn up for your desired route, and/or there will be a return flight.
The company will always try and sell a flight like a normal charter if possible.
Commercial Aircraft
For commercial airlines, ferry flights are avoided as far as possible. They are (in principle) nothing but money down the drain. You will encounter ferry flights:
When you need to move the aircraft for maintence.
British Airways run a facility in Cardiff for maintaining among others their huge fleet of Boeing 747s.
Austrian Airlines run a facility in Bratislava, requiring a 20-minute hop for aircraft due for maintence from Vienna.
When stuff messes up, most notably breakdowns. For instance, an mechanical breakdown at a remote airport followed by ferrying the aircraft back once repaired.
The issue is that:
These flights are often at strange and/or irregular times.
Occasionally crewed by only cockpit crew and no flight attendants.
As such, there is little incentive for airlines to let passengers along even (if it may legally possible). The cost, time, paperwork and extra staff would most probably not pay off for the low number of passengers that could be expected.
| 1 | How to fly on a private jet for under $200? |
MacBook Pro Retina and fonts rendering | I am using MPB retina. I have more than two years of a constant osx experience but what I can't stand is an OSX font rendering. That's simply uncomfortable for my eyes. Big amount of my work I do using external monitor (Nec 24') and fonts look even more blurry (terrible) on it.
Is there any official or unofficial way to change font rendering in OSX?
Any kind of custom kexts or patching would be appreciated. I can't find myself anything wrt this.
| You can use a lighter text rendering style by running
defaults write -g AppleFontSmoothing -int 1
and quitting and reopening applications to apply the changes.
| 0.888889 | Using defaults write -g AppleFontSmoothing -int 1 |
Layman's guide to getting started with Forex (foreign exchange trading)? | How should I get started with Forex (foreign exchange trading)? How should I prepare myself for it? Please give your answer thinking of me as a layman.
| There are various indexes on the stock market that track the currencies. Though it is different than Forex (probably less leverage), you may be able to get the effects you're looking for. I don't have a lot of knowledge in this area, but looked some into FXE, to trade the Euro debt crisis. Here's an article on Forex, putting FXE down (obviously a biased view, but perhaps will give you a starting point for comparison, should you want to trade something specific, like the current euro/dollar situation).
| 1 | Forex putting FXE down |
Does Improved Familiar feat apply to Urban Companions? | Cityscape Web Enhancement lists an alternate class feature for Druids and Rangers, called Urban Companion:
The character gains the companionship of a smaller but far more intelligent creature than she otherwise would have. This is identical to the sorcerer's ability to summon a familiar (PH 52), including all benefits granted and gained by the familiar, except as noted below. Her functional level for determining the abilities of the companion is equal to her druid level or one-half her ranger level.
Does a character with Urban Companion qualify for the Improved Familiar feat?
| It is unlikely there is any firm documentation on this; web enhancements weren't the most well supported thing WotC did, and it came fairly late in the life cycle of 3.5.
That said, the line 'this is identical to the sorcerer's ability to summon a familiar' strongly suggests that it should. This is in many ways just like a class ability granting prerequisite feats like various cleric domains do, so you should meet the 'ability to summon a familiar' prerequisite of Improved Familiar, even if you don't call it a familiar.
However, you still have to meet all the other requirements, including alignment and class-level. And Rangers would still suffer from the equivalent-class-level reduction they normal suffer with animal companions (I don't have the source material in front of me, but I seem to recall ranger levels only counted as half a druid level for determining the companions available. The same would apply to Improved Familiars.)
| 0.888889 | Improved Familiar: 'similar to sorcerer's ability to summon familiar' |
How was this photo taken | My question is how was this picture taken.
And I've got a few assumptions I made regarding the photo, please correct me when I am wrong.
Low aperture value, like 1.4-2.0
Quite high shutter speed, my guess is that it was 400-500
Auto iso speed
That's how I would have taken a picture like this. The other thing is that it has some vignetting - I guess, it's a postprocessing.
What else? It looks to me that some other postprocessing had to be done.
And what kind of lens you think it was?
My guess is that it was some zoom-lens, but that's all I can tell.
| This is mostly guess-work:
To me this looks like a medium length zoom:
(Assuming its on a Full Frame body) of 150mm - 200mm.
Shutter speed would be 1/200th+
ISO 800 (I NEVER use Auto ISO)
Aperture may not be that large, as the lens is long-ish, could be 3.5f ish
The vignette looks fake
| 1 | This looks like a medium length zoom . |
Is possible to remote mount an image, that can boot and install itself? | I have a remote server, which runs Linux. I would like to install remotely the OS image, in case that it gets corrupted (this has already happened twice while I am experimenting with the OS).
So far, the only way that I have, is to physically go to the machine location and use a USB disk to mount the OS and the BIOS see it, so it can boot from it.
Is there any way to basically connect to the machine via ssh, attach this image and have it act like it would be on a virtual drive on Windows (like daemon tools for example), so it would persist to a reboot and allow me to install remotely the OS?
I was looking at solutions on Google, but I found something mentioning PXE boot....which sounds complicated, since you need a server and such, and it is not as simple as mounting an image and being done with it.
Beyond that, I found nothing useful, so I am quite short on options....does anyone know how to accomplish this?
| Here's a hypothetical situation which I consider might be plausible:
The targeted machine is EFI.
grub is either never installed on the target or has been utterly wiped from the system.
it can only ever interfere and offers nothing of value otherwise.
So what we might do in the above case is configure a boot option for a small installation/rescue image we keep on our /esp or EFI system partition.
If anything were ever to go wrong with our current installation, then, for so long as we can at least access the EFI system partition by some means, then we can interface our firmware and set the machine to boot to our recovery image on next reboot. In that case all we would have to do is change a text file or two, cross our fingers and run reboot now.
Here is a basic set of commands for a minimally configured Arch Linux (because it's what I use) system which could still do as I describe.
First, we'll make a work directory and download some files.
I use aria2c here. I recommend it, but use whatever works.
I unzip rEFInd with 7za but the same
tool preference is yours in all cases here.
If you're not reading this within a few hours/days of my posting it, then there is a very good chance that the links used below are not current.
mkdir /tmp/work && cd /tmp/work || exit
aria2c 'magnet:?xt=urn:btih:331c7fac2e13c251d77521d2dc61976b6fc4a033&dn=archlinux-2015.06.01-dual.iso&tr=udp://tracker.archlinux.org:6969&tr=http://tracker.archlinux.org:6969/announce' \
'http://iweb.dl.sourceforge.net/project/refind/0.8.7/refind-cd-0.8.7.zip'
7za x ref*.zip; rm ref*zip
Next I'll make an image disk.
I use a file here with loop devices, but you may want to use an actual disk if you want to boot to this from firmware.
In the case of an actual device the fallocate and losetup stuff can be ignored and the actual device names will far more likely
correspond to /dev/sda[12] than /dev/loop0p[12]
fallocate -l4G img
Now I'll partition that disk with the gdisk utility and assign it to a loop device.
This is a scripted shortcut for the options you'd want to feed the program interactively. It will create a GUID partition table and a partition of type EFI-system that spans the first available 750Mib of the target disk and another linux default partition spanning the rest of the disk.
These partitions will be /dev/sda1 and /dev/sda2 respectively if you're using a real disk, which will be /dev/sda rather than ./img. It is usually desirable to add more than one partition for a linux root, which is assumed to be the purpose of /dev/sda2.
printf script or no, the gdisk program is easy to use - and so you might do better to go at it interactively instead. The target disk should not be mounted when it is run, and you'll probably need root rights to write the changes.
As a general rule you can do pretty much whatever you want in that program without any effect until you write - so be sure when you do.
I'll be putting my $TGT in a shell variable. Except for its definition here, which you may want to tailor as necessary, where I use it so can you.
printf %s\\n o y n 1 '' +750M ef00 \
n 2 '' '' '' '' w y |
gdisk ./img >/dev/null
TGT=$(sudo losetup --show -Pf img)p
We'll need a filesystem on the esp, too. It must be FAT.
I give mine the fs label VESP. You should call yours whatever you want.
We'll use the label later in /etc/fstab and another config file - so definitely make it something.
In my opinion you should always label all disks.
If you install an OS to ${TGT}2 now you will of course need a filesystem for it as well.
sudo mkfs.vfat -nVESP "$TGT"1
And we'll make some mount directories and start extracting the relevant files.
set ref ref*iso \
arch arch*iso \
efi arch/EFI/archiso/efiboot.img
while [ "$#" -gt 0 ]
do mkdir "$1" || exit
sudo mount "$2" "$1"
shift 2
done; mkdir esp
Install rEFInd...
rEFInd is a boot manager - which mostly just offers and populates boot menus.
rEFInd will put its config files on the esp and these can be edited at any time and anyway you like.
sudo ref/install.sh --usedefault "$TGT"1 &&
sudo umount ref && rm -rf ref*
Now we'll mount our esp and get the needed files off of the Arch install disk to get our own live bootable rescue disk.
Most live disks implement a sort of ugly hack to make the flat, unpartitioned iso filesystem look like an acceptable boot device to a UEFI system while still maintaining backwards compatibility w/ BIOS systems.
Arch Linux is no exception.
This ugly hack is that efiboot.img currently mounted on ./efi. It's where we'll find our kernel and initramfs image file. The other ones on the disk (in ./arch/arch/boot) will not work for EFI systems.
sudo sh -ec <<CONF '
mount "$1" esp
cp -ar efi/EFI/archiso esp/EFI
cp -ar arch/arch/*x86* esp/EFI/archiso
mkdir esp/EFI/archiso/cow
xargs > esp/EFI/archiso/refind_linux.conf
umount efi arch
rm -rf efi arch*' -- "$TGT"1
\"arch_iso\" \"archisobasedir=EFI/archiso \
archisolabel=VESP \
copytoram \
cow_label=VESP \
cow_directory=/EFI/archiso/cow\
cow_persistence=P \
cow_spacesize=384M \
initrd=EFI/archiso/archiso.img\"
CONF
You have essentially just installed - from the ground up - a pre-boot rescue environment with a persistent copy-on-write save file (so you might, for example systemctl enable sshd_socket now and the setting would persist in the live system's next boot). The Arch Linux live install media now resides on your system's boot partition and can be called from the boot menu at any time. Of course, you also installed the boot menu manager.
A couple of things about the above should stand out to you:
I use *x86* because I have a 64-bit machine and that glob gets what I need. For a 32-bit installation (but why?) use *686* instead.
What I need, by the way, is a total of only 7 files and approximately 300M.
The live-system's rootfs is the squashed image in esp/EFI/archiso/x86_64/airootfs.sfs.
I specify the disk by label. There are no hints or other such nonsense - the disk is named and so it is easily found. You'll need to substitute in whatever you chose for an esp label instead of VESP.
The copytoram kernel parameter instructs the Arch Linux live init system to copy its rootfs image into a tmpfs before loopmounting it - which frees you actually to access the esp when working in that environment. Most live install systems offer similarly arranged constructs.
Where EFI shines is in its ability to handle a filesystem. On modern computers there is absolutely no need to pack some raw binary and wedge it in between your disk partitions. It astounds me that people still do, when, instead, they could manage and configure their boot environment with simple text files arranged in a regular, everyday directory tree. Above I put the kernel and initramfs in their own named folder in a central tree structure. The EFI - which will take its cues from rEFInd in this case for convenience - will invoke that at boot by pathname because it mounts the esp.
Now all that is left to do is to ensure you understand how to select the system which will actually boot when you need to. Understand - you can boot this right now. You can do it in a virtual machine w/ qemu (you'll need OVMF -pflash firmware) or you can reboot your computer and rEFInd will detect the kernel and pass its pathname to the firmware which will load and execute the Arch Linux live system. When you install a more permanent system on the disk - or several (which you can do right now if you so choose by rebooting to the live disk and performing the installation) - you'll want to keep its kernel and initramfs in the same structure. This is very easily arranged.
If, for example, you were to install a system on a root partition named, for lack of an imagination, root, you'd want to set it up something like this:
mount --bind its particular boot folder over the root /boot path in /etc/fstab.
You'll need two lines in /etc/fstab and to create a mount point in /esp to handle this.
sudo sh -c <<\FSTAB '
[ -d /esp ] || mkdir /esp
findmnt /esp || mount -L ESP /esp
mkdir -p /esp/EFI/root
cp /boot/kernel binary \
/boot/initramfs.img \
/esp/EFI/root
mount -B /esp/EFI/root /boot
cat >> /etc/fstab
echo "$1">/boot/refind_linux.conf
' -- '"new_menu_item" "root=LABEL=root"'
LABEL=ESP /esp vfat defaults 0 2
/esp/EFI/root /boot none bind,defaults 0 0
FSTAB
You only ever have to do anything like that once per installation - and that is assuming you didn't set it up that way in the first place - which is easier because the kernel and initramfs will already be where they belong. Once you've got those lines in /etc/fstab and a minimal config file in /boot/refind_linux.conf you're set for good. You can support as many installations as you like on the same system with the same /esp device and centralize all bootable binaries in the same tree just like that. Different
systems will do things a little differently - Windows takes a little more cajoling to get it to conform, for example - but they will all work.
Ok, the last thing you need to know, as I said before, is how choose the next booting installation from the filesystem. This is configured in the file /esp/EFI/BOOT/refind.conf.
You should read this file - it's probably 99% comment and will tell you all about what you might do with it.
Of course, you don't really have to do anything - by default rEFInd will boot the most recently updated kernel in its scan tree.
But I usually wind up setting the following options:
<<\DEF sudo tee \
/esp/EFI/BOOT/refind.conf.def
### refind.conf.def
### when renamed to refind.conf this file
### will cause refind to select by default
### the menu item called "new_menu_item"
### in its /boot/refind_linux.conf
default_selection new_menu_item
### this file will also set the menu timeout
### to only 5 seconds at every boot
timeout 5
### END
DEF
And the rescue file...
<<\RES sudo tee \
/esp/EFI/BOOT/refind.conf.res
### refind.conf.res
### this one will default to selecting
### the entry named "arch_iso" with a
### 10 second timeout
default_selection arch_iso
timeout 10
### END
RES
And so now you can just move them around.
For example, to make the rescue environment definitely boot after you do reboot now...
sudo cp /esp/EFI/BOOT/refind.conf.res \
/esp/EFI/BOOT/refind.conf
And substitute .def for the .res used above, of course, to go back to default root.
| 0.888889 | How to set up a boot option for an UEFI system? |
Running ArcPy script from ArcObjects? | the standard method requires to run ArcPy script in command line, i've struggled with it to run but without a result, i can import arcpy, set the workspace to the geodatabase path and describe the env variable using arcpy.Describe(arcpy.env.workspace).name it gives me the geodatabase name, but when i try to get featureclasses using arcpy.ListFeatureClasses() i get [], i have made sure that all the environement variables in PATH and PYTHONPATH are ok .
i would like to know if there's an alternative way to run ArcPy script, like it could be run in ArcMap console, is there a way to send scripts to ArcMap console using ArcObjects, what's the difference between ArcMap console and standard command line console?
so any way to run an ArcPy script using ArcObjects 10 or Arcgis Engine 10 will be very welcome.
| I think you need to execute arcpy.ListFeatureClasses to get a list of featureclasses in your geodatabase.
| 0.777778 | arcpy.ListFeatureClasses to get list of featureclasses |
Why are papers without code but with results accepted? | I just started reading some papers (Computer Science, specifically Computer Vision) and thought "now let's look at the source code" and was quite astonished that most of the papers don't have any source code implementing the described methods to look at, while claiming some performance or being better than other papers.
How do these papers get accepted in journals / conferences? Do people have to submit their source code privately to the reviewers at least, so that they can reproduce the experiment if possible.
Do most journals / conferences just "trust" that people who submit the paper really implemented the theory and got those exact results?
I always had this idea that any experiment should be reproducible by others else it's not scientific justified. Been wondering about this the last few days.
| You seem to think that we should request code, because without code, any crazy result, be it fraud or honest mistake, can be slipped into the journal. But this is not so. Including code is a nice-to-have feature, not a must-have feature. The other answers silently assume this and explain the (good and not-so-good) reasons which lead to the current situation of uncommonly included code. I think I can complement them by explaining why it is not a must-have feature.
For theoretical results, you don't need any empirical tools like code to reproduce them, as others mentioned (e.g. proving that an algorithm has a better big O behavior than another). Of course, there are also empirical results, which cannot be replicated that way.
But your reviewers will have an expectation of what your idea will result in. If the current best performance for wugging zums is 3 zums/s, and you add a minor tweak and report 300 zums/s, your reviewers are supposed to notice that your claim is unusual, and do something (possibly demand to resubmit with the code). This is not foolproof, but with multiple reviewers per paper, it is effective, because the magnitude of most empirical results is predictable once the reviewer sees the idea and understands how it works.
For this class of paper, both honest and dishonest mistakes have a good chance of being caught, with bad results for honest scientists (reputation loss, especially if caught after publication) and worse results for dishonest scientists (end of career if proven!). Moreover, the graver the mistake (as measured in the size of error), the higher the chance of being caught. It is less likely that you will get caught if your algorithm manages 4 zums/s and you report 5 zums/second, than if you report 300 zums/s. So, scientists are disincentivized from submitting incorrect papers, leaving less incorrect ones in the submitted pool, and the reviewers catch lots of the remainder.
There are cases where it is totally unknown why an observation is the way it is, and in these cases, it is very important to describe the exact test setup perfectly. But I have never seen this kind of paper in computer science, it is associated with natural sciences. So no code there. Even if you got such results in computer science (e.g. you observed that users are capable of reading a 12000 word EULA in less than 30 seconds, which contradicts common reading speed observations, and you have no explanation for it), it is unlikely that including the code you used to obtain the result will be pertinent to replication.
To put it together, among a large mass of computer science papers, the theoretical ones and the natural-phenomenon-observation ones don't need code inclusion for replication, and the remaining ones will contain only a low percentage of incorrect-but-uncaught papers. Aggregated, this leads to an acceptably low level of incorrect papers being submitted. Requesting the code to go with them will increase quality for one class of paper, but it will be an increase of an already high quality level. It is not that not having this feature makes the current quality too low.
| 1 | Including code is a nice-to-have feature, not a must-have . |
Scaling FFT output by number of points in FFT | When computing the N-point FFT of some signal, the result is always divided by N. I can understand why this is the case for a summation over the N points, but often the result of the FFT operation is a vector of length N rather than a summation. Why then is the length-N vector that is the output of the FFT scaled by the number of points (N) used to compute the FFT? Thanks.
| The difference is that the digital Fourier transform (and FFT as well) gives a vector of size N (or M in some cases) that contains sums of N samples.
So, basically, each point of the FFT transform is the result of a sum over a certain time interval of the time-based samples. That's why you divide by N.
You can consider it this way: you take an interval of N samples of your signal; then, you basically sum all the samples N times, but each time multiplying them for a different function, that allows to extract the information for a specific frequency (or frequency range, to be more accurate).
At the end, in summary, instead of having N samples, each one associated to a time interval, you have N samples (as before) but each of them related to the whole interval and describing the component of the signal for a specific frequency range.
Just for completeness, there are four cases of Fourier transform:
Continuous Fourier transform, for continuous signals in time, over a finite interval, that gives a continuous frequency response;
Fourier series, taking a continuous and periodic signal and giving the discrete series of harmonics, so with discrete frequencial components;
Time discrete Fourier transform, the reciprocal of (2), in which from a discrete-in-time signal gives a periodic function in the frequency domain;
Digital Fourier Transform, that takes a discrete and periodic signal to give a discrete and periodic spectrum.
So transforming a periodic signal gives a discrete spectrum and vice versa.
| 1 | Digital Fourier transform gives a vector of size N (or M in some cases) that contains sums of N samples . |
Where is Query String (URL) Filter? | Based on the answers to a previous question I want to use the Query String (URL) Filter, but I don't see it on my site. Is there something I have to enable?
| Filter web parts require enabling SharePoint Enterprise site collection feature. That means this belongs to only enterprise SharePoint versions.
| 0.888889 | SharePoint Enterprise site collection feature |
Question about thermodynamic conjugate quantities | I've come across the Onsager reciprocal principle. It's almost clear, except for thermodynamic conjugate quantities - what's that, physical meaning (except the formal definitions: $X_i = -\frac{1}{k}\frac{\partial S}{\partial x_i}$, which isn't clear) and why:
\begin{equation}
\langle X_i\cdot x_k\rangle = \delta_{ik}
\end{equation}
The Wikipedia is lack for references in this article.
| Thermodynamic conjugate variables are pairs of variables $x_i$, $X_i$ where the product $X_i\cdot dx_i$ has the dimension of energy and actually appears as a term in the infinitesimal variation of energy, free energy, or work such as $dE$.
In the pair, one quantity is intensive and the other is extensive.
The best example is pressure and volume because $p\,dV$ is a term in $dE$. Analogously, temperature and entropy because of $T\,dS$, chemical potential and particle number because of $\mu \,dN$, and many electric, magnetic, gravitational, and surface tension examples exist.
If you have
$$ dE = \dots + p\,dV, $$
it's easy to see that $p$ is the partial derivative of $E$ with respect to $V$. This role of $p,V$ may be reverted if you consider $H=E+pV$ instead of $E$ i.e. substitute $E = H-pV$. Then you will get
$$dH = \dots - V\,dp.$$
This "Lagrange duality" may be applied to any pair.
| 0.444444 | Thermodynamic conjugate variables are pairs of variables $x_i$, $X_I$ . |
Ethical Disclosure of Professional Knowledge in PhD Dissertation | I have just completed my PhD. Although my examiners did not raise any concerns, I have been grappling with an ethical issue for the entire duration of my candidature.
The issue concerns professional knowledge of the field on which my research is based. This is an issue of concern because I am employed in the field and have access to information that is generally not publicly available (but is available to me as an employee) or only found in hard-to-get industry publications (e.g. newsletters). These publications are hard-to-get because of their specialised nature and limited circulation.
Disclosing this information creates a potential conflict of interest for me (because of reasons associated with commercial-in-confidence, breach of trust etc.). It gets even worse because I am often actively involved in generating this information as part of various negotiations I am required to have with third parties (in my capacity as an employee). As an example, I draft policy speeches for my CEO so this has the effect of quoting my own work in my dissertation (but attributed to my CEO in the citation and bibliography!)
To resolve this matter, I have declared (categorically) this conflict of interest (several times in my dissertation) (although I don't identify myself as the ghost writer). I have also put whatever information I thought could be ethically disclosed in the relevant context (e.g. cited the publicly available newsletter, where possible). This was to ensure future researchers could benefit from this 'inside' knowledge. I have stated this as one of the contributions to knowledge that my dissertation is making.
I must add that the professional knowledge does not contradict or undermine my research, so I am certainly not withholding the information for this reason. On the contrary, this information enhances the main arguments of my study (so omitting it presents a significant dilemma for me).
i would love to hear how else could this matter be resolved.
| And, as a small point, if one's work is confidential for the reason that it is so extremely useful/important/wonderful (!?!), while one cannot claim this directly, it is usually possible to communicate facts about the situation in a way that will be understood by potential employers. One's letter writers would hopefully/presumably comment on the situation, and possibly gossip will lead the way, besides, if it's really something good.
At least as a starting point, honesty + keeping promises is a good baseline. :)
| 0.888889 | if one's work is confidential for reason that it is so useful/important/wonderful, it is usually possible to communicate |
Should I get a reusable/washable air filter for my Kia Soul? | I've got a 2010 Kia Soul, and I was wondering if I should get a reusable/washable air filter, such as the K&N 33-2960.
The reasons I would think to get such an air filter would be:
Save on the cost of replacement filters
Less waste for the environment
Better for the engine
A bit more power
How much of a benefit am I likely to see in each of the above categories from using a washable air filter? Are there other benefits?
Thanks!
| I ordered a K&N Air filter for my 2010 Kia Soul and yes, a little more power but a lot less mileage per gallon. The reason being these filters are made for older vehicles with a carburator and not with fuel injection. I am in the process of returning my air filter to K&N because of this. They were very reasonable about this and indicated they will refund the full amount on my credit card but I must pay for the shipping. I will let you know the outcome once I send the item back to them.
| 1 | K&N Air Filter for my 2010 Kia Soul |
Why does WPF toggle button pulse once unchecked | Within a Desktop app I have a toggle button:
<ToggleButton x:Name="CFStglBtn" Checked="cfsCBox_Checked"
Unchecked="cfsCBox_Unchecked"
IsChecked="True" HorizontalAlignment="Left" Margin="5,0,0,0">
<StackPanel Orientation="Horizontal">
<Image Source="assets\telephone.png" Margin="3,0,0,0" />
<TextBlock Text="CFS" FontSize="10" Margin="5,5,5,0"
Foreground="DarkSlateGray"/>
</StackPanel>
</ToggleButton>
For the Checked event I am setting a value and then executing a method FilterView();
//ommitting code
Unchecked state is just the opposite. resets a variable and executed the method again
The question I have is I noticed when I uncheck the toggle button the button continues to pulse or flash ( going from blue to chrome) as if it still has focus. The button will stay like this until another button is clicked.
Is there a way to remove this focus so that when the button is unchecked the button goes back to a unchecked state without the flashing / pulsing color.
As you can see from above this is a standard toggle button no styles or custom
I tested this on just a regular button and I found the same occured when clicked the button will continue to pulse / flash until another button is clicked.
How do you work around this or prevent this effect from happening.
Thank you
| Set the Button Focusable="False".
| 1 | Set the Button Focusable="False" |
What to call "Cancel" when "Cancel" is already the default action? | When attempting to cancel a service or setting, "cancel" is the default action. What should the normal "cancel" button be called?
Redbox uses a playful "just kidding", which may not be appropriate in all circumstances.
| Rewording
I would try my very, very best to avoid using the term 'cancel' for terminating the subscription. Cancel is generally considered to be a safe action. Here, you are using it in a more destructive sense, thus causing the confusion you noticed.
If you manage to avoid the term 'cancel' for the actual activity, you can resume to use it for the cancel action on the dialog. In the mockup below, I used "Unsubscribe", but you can also consider other ways to express this like "terminate", "end", "remove" or "stop" subscription.
download bmml source – Wireframes created with Balsamiq Mockups
Not confirming at all
Alternatively, you could consider getting rid of the confirmation message completely. Instead, you could display something like this:
download bmml source
You could then also send the users a message by email saying essentially the same thing, and also allowing them to change their mind for a limited time.
| 0.888889 | 'cancel' for terminating a subscription |
Output workflows associated to all lists in a web application | Still very new to Powershell. I've adapted a script I found here to display information I want to see about workflows for a particular list. That looks like this:
$siteURL="https://mydomain/sites/ericrules/"
$listName="Calendar"
$site=Get-SPSite $siteURL
$web=$site.RootWeb
$list=$web.Lists[$listName]
$wfManager=$site.WorkflowManager
$associationColl=$list.WorkflowAssociations
foreach($association in $associationColl)
{
write-host $association.ParentSite, "List:" $association.ParentList, "Name:" $association.Name, "Description:" $association.Description, "Manual:" $association.AllowManual,"On Create:" $association.AutoStartCreate, "On Change:" $association.AutoStartChange,"Created:" $association.Created, "Modified:" $association.Modified
}
$web.Dispose()
$site.Dispose()
How would I adapt and generalize this to start at a singular web application and iterate through all the site collections, sites and subsites, looking at every list and outputting that data? If it was a nicely formatted text file with the quoted values as headers, that'd be ideal. A CSV would work too.
I'm still having difficulty figuring out all the for each looping going on.
| This is for all lists in a farm
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Microsoft.SharePoint.Administration.SPFarm]::Local.Services |? {
$_.TypeName -eq "Windows SharePoint Services Web Application"
} |% {
$_.WebApplications |% {
$webapplication = $_
Write-Host "web app"
$webapplication.Sites |% {
$site = $_
Write-Host $site.Url
$site.AllWebs |% {
$web = $_
Write-Host $web.Url
$web.Lists |% {
$list = $_
Write-Host $list.Title
#do some stuff
}
}
}
}
}
If you just need a particular webapplication use this:
$site = new-object Microsoft.SharePoint.SPSite "https://mydomain/sites/ericrules/")
$webapplication = $site.WebApplication
Filter/Dispose as needed
Then pipe the result into Export-CSV
| 0.888889 | Windows SharePoint Services Web Application |
how to display a message box for a user in Java | I want to display a message box to show some message in Java, and the box should have three buttons that the user can press such that the program can get value when user presses the button.
| If you use Java Swing then take a look at
JOptionPane
| 1 | JOptionPane - Java Swing |
Graphicsrow title | I made the following graphic with Mathematica 9.0:
Does anybody know how to put a title on the top of the whole graph? (not in each single plot).
Basically I used
GraphicsRow[ListLinePlot[]ListLinePlot[]]
Thanks.
| p = Plot[Sin[x], {x, 0, 2 Pi}, ImageSize -> 200];
Framed[
Column[
{
Style["Sinus", Darker@Blue, Bold, 16],
GraphicsRow[{p, p}]
},
Alignment -> Center],
FrameMargins -> 10]
| 0.777778 | Framed[ Column[ Style["Sinus", Darker@Blue, Bold, 16]] |
Confused with HoldForm in Postfix notation | Why does the following code produce different result? In my mental model, they should be the same.
Table[With[{x = i^k}, HoldForm[x]], {k, 1, 5}]
With[{x = i^k}, HoldForm[x]] // Table[#, {k, 1, 5}] &
Output:
{i,i^2,i^3,i^4,i^5}
{i^k,i^k,i^k,i^k,i^k}
| To be more specific, the difference is not because of the postfix application but because of the pure function (the part with # and &) application:
Table[With[{x = i^k}, HoldForm[x]], {k, 1, 5}] (* no pure function *)
(* ==> {i, i^2, i^3, i^4, i^5} *)
With[{x = i^k}, HoldForm[x]] // (Table[#, {k, 1, 5}] &) (* postfix pure function *)
(* ==> {i^k, i^k, i^k, i^k, i^k} *)
(Table[#, {k, 1, 5}] &) @ With[{x = i^k}, HoldForm[x]] (* prefix pure function *)
(* ==> {i^k, i^k, i^k, i^k, i^k} *)
Accordingly, if you simplify your example, and put some Prints in it:
Block[{k = 1}, Print[2]; With[{x = k}, Print[1]; HoldForm@x]]
During evaluation of In[17]:= 2
During evaluation of In[17]:= 1
(* ==> 1 *)
Block[{k = 1}, Print[2]; #] &@With[{x = k}, Print[1]; HoldForm@x]
During evaluation of In[17]:= 1
During evaluation of In[17]:= 2
(* ==> k *)
As you can see, in the last case, the With is evaluated first, not Block, resulting in thus a replacement x -> k, so Block cannot replace x in the second step as there is no x anymore in the expression.
An even more simple example that shows the reversed evaluation sequence for pure function application compared to normal, nested expression evaluation:
(Print[2]; Print[1];)
2
1
(Print[2]; #;) & @ Print[1]; (* or: Print[1]; // (Print[2]; #;) & *)
1
2
| 1 | Reversed evaluation sequence for pure function application |
How can I speed up the rate at which putty dries? | We're (slowly) renovating the sash windows in our house and the current window is causing problems. What should have been a quick job (especially at this time of year!) has turned into a marathon because the putty won't dry.
We had to replace a couple of panes of glass (one was cracked and we broke another when using a heat gun to remove the paint) so we knew it would take a little while. On a previous window the putty took over three weeks to dry enough to paint partly because (as we thought) there was too much oil. So this time we rolled the putty on newspaper first to try to remove the excess oil. It seemed to work, but after two weeks the putty is still soft to the touch.
We've tried standing the windows next to a radiator but all that seemed to do was make it softer (which was obviously going to happen in hindsight).
So given that we don't want to reputty the windows what can we do to speed up the drying process.
We've had to seal off the room and cover the window as best we can in the meantime.
I've found this advice on DoItYourself.com which doesn't really help as it says use other materials!
The answers to this post on DIY-Forums are confusing at best and possibly contradictory as one recommends exposing the putty to moisture(!) to speed the drying process.
| Heat will make the putty softer, which is why you can heat it up to remove it. Putty pretty much stays soft for years. Initially, it doesn't really dry out so much as oxidize which forms a skin on it.
If you absolutely must paint it right away, you'll probably has to use one of the latex based glazing compounds. If you want to use a traditional one, paint it as soon as it forms enough of a skin that the paint will stick to it. Also, I think you probably should be using oil based paints, but check the instructions on the putty.
If you let use know specifically which putty you are using, that might help get better answers.
| 1 | Heat will make the putty softer, which is why you can heat up to remove it |
JQuery .replaceWith() html element to div class | I want to replace
<div class="blog">Blog</h1>
with
<h1>Blog</h1>
which is inside a class name "sidebar"
I used this code but didn't work:
$(window).load(function() {
$( ".sidebar h1" ).replaceWith( "<div class="blog">Blog</h1>" );
}
What is wrong on my code?
| Firstly, your opening a div tag and closing an h1 tag.
Secondly, your quotes are mismatched within the .replaceWith bit.
I would do this instead:
<h1 id="replaceme">Blog</h1>
<script>
$(window).load(function() {
$("#replaceme").replaceWith('<div class="blog">Blog</div>');
| 0.777778 | div tag and h1 tag |
Setting up Exim to forward mail | I'm trying to setup Exim on a fresh CentOS install so that it will receive mail for a collection of given addresses, and forward the mail respectively to another address. For example, receiving mail from [email protected] would be forwarded to [email protected].
I figure this should be fairly straight forward... I had this working before with Sendmail, using the virtusertable - is there something similar I can do with Exim?
I'd also like to be able to send mail, but only for mail being sent from the local machine (i.e., from applications running on the server) - I don't need/want a publicly available SMTP server.
Are there any other settings I should bear in mind to make sure the mail server is secure? (i.e., prevent relaying) I'm assuming that it will be secure out of the box.
Thanks.
| A variation on what Joe Freeman said, without using dsearch (which gave me unknown lookup type "dsearch" error):
In the beginning of exim.conf:
#Replace:
domainlist local_domains = lsearch;/etc/virtual/domains
#With:
domainlist local_domains = lsearch;/etc/virtual/domains : lsearch;/etc/virtual/forwarding_domains
In the section "begin routers" add:
sender_redirect:
driver = redirect
domains = lsearch;/etc/virtual/forwarding_domains
data = ${lookup{$local_part}lsearch{/etc/virtual/forwarding/$domain}}
In lsearch;/etc/virtual/forwarding_domains add your domains one per line:
example.com
And create /etc/virtual/forwarding/example.com containg:
me: [email protected]
| 0.888889 | Lookup type "dsearch" error |
How can I improve this DB query? it takes too much time | The query is this:
$today = $date->getTimestamp();
SELECT t.*, u.screen_name, u.profile_image_url
FROM table AS t
LEFT JOIN users AS u
ON t.user_id=u.id_str
WHERE UNIX_TIMESTAMP(t.created_at) > {$today}
ORDER BY id DESC
LIMIT 12;
| Even though you didn't post table definitions in your question so I can't tell for sure what is missed, the following indexes will be beneficial :
Index on table (user_id, created_at)
Index on users(id_str) or even users(id_str,screen_name,profile_image_url)
I guess you already have an index on table(id)
UPDATE
Change WHERE :
from WHERE UNIX_TIMESTAMP(t.created_at) > {$today} to WHERE t.created_at > FROM_UNIXTIME({$today}), this way optimizer will use index that includes create_at column more efficiently.
| 0.666667 | Index on table (user_id, created_at) |
Why don't wifi managers remember mac addresses for hotspots to defeat the jasager attack? | So I just learned about the jasager attack, via the wifi pineapple and it struck me immediately that it wouldn't work at all if network managers (privately) associated MAC addresses with hotspots and asked for explicit permission if you were going to connect to a new physical device.
Obviously this would be mildly irritating in public hotspots where devices change and hundreds of diverse locations share network names, but it would make home and work networks much harder to penetrate.
I haven't found any wifi managers that do this, or at least I haven't found information that any do.
My question:
Am I missing something obvious? Would remembering MACs not actually increase security?
If it would, are there any network managers that do this? (I'm on Linux, but if there are tools for other OS's I think it's worth having them in the answers)
| MAC address spoofing is trivial for an attacker to carry out, any form of mac address filtering will not help secure any network. However, MAC address filtering can cause real problems for legitimate users. What if you buy a new router and give it the same SSID?
The best defense against this sort of attack is WPA. It isn't prefect, WPA-PSK is pretty easy to break, but its better than anything else consumers have.
| 0.777778 | MAC address spoofing can cause real problems for legitimate users |
Implement scroll bar for content in samsung smart tv apps | I have a simple Smart TV app (javascript app) that shows a list of items. And I want pagination for list of items. My solution is create scroll bar for apps. But how to implement scroll bar in samsung smart tv apps. Please help me!
| Samsung Browser does not support displaying scrollbars, you need to implement it yourself. Also 2010-2011 TV Browser don't support horizontal scrolling.
| 0.833333 | Samsung Browser does not support displaying scrollbars, you need it yourself |
How can I keep a macbook running when the display is closed? | I bought a macbook pro retina 13" few days ago. I have never had a mac before and I don't know where can I set the computer to keep running when I close the display.
The laptop came with os x 10.8.4.
Any help?
| I posted an answer over to the similar question:
Is there any way to set a MacBook Pro to not sleep when you close the lid?
that applies to this question as well. Since I found this question in a search, others will too, so go there for the discussion.
| 1 | Is there any way to set a MacBook Pro to not sleep when you close the lid? |
How to extract name/data from database and use it as my folder name which is created dynamically in asp.net c# using server.MapPath()? | I have used AjaxFileUpload to upload multiple image files. Now i want to store the uploaded images inside rootfolder>subfolder.
The rootfolder is in the name of the user.
The rootfolder is created dynamically by taking the session of the user who has logged in
Like this:
string username = Session["username"].ToString();
I am able to create this folder and save images in it. but i want to save it in subfolder.
the subfolder is also created dynamically but this time i have to take the value(id) from the database and name the folder by that id name. (this is so that i can refer to the database)
I know how to create a new folder using Server.MapPath();
Here is the code for it in brief
using System.IO
if (Directory.Exists(Server.MapPath(uploadPath))) return;
else Directory.CreateDirectory(Server.MapPath(uploadPath));
where uploadPath is the folder's name i want to create dynamiclly.
but how do I include the subfolder too in my Server.MapPath() so as to make my path as rootfolder/subfolder ?
Small example to make the question understandable.
I am a seller. I have posted 4 ads online.
Now when i am posting my 5th ad i want to include many images.
these images should be saved in the folder
Seller/5/imagename.jpg.
(where Seller is the username(main folder), 5 is the advertID in the database and the name of the subfolder)
How do i do this? Please help.
I am using asp.net c#
| User Path.Combine to add your root and the user id:
var userPath = Path.Combine(uploadPath,userID)
This is the safest way to create what you need. The Directory.CreateDirectory method will create all the subfolders as needed:
var userPath = Path.Combine(uploadPath,userID)
if (Directory.Exists(Server.MapPath(userPath))) return;
else Directory.CreateDirectory(Server.MapPath(userPath));
| 0.833333 | User Path.Combine to add root and user id |
OCR software for handwritten notes | I am looking for a way to recognize handwriting of scanned notes (in PDF format).
It doesn't have to be perfect, and it doesn't have to free, but before paying I would like to try it (even with just a single page).
It doesn't necessarily have to be a native Mac OS X application. I would be OK with an online application, or a Unix application to install or compile. In other words, anything that works somewhat decently would be OK.
I am also not necessarily looking for a perfect result. Even transforming my notes into a searchable PDF with just some of the text recognized would be better than nothing.
| I realize that you are looking for a Mac OS application, but for the benefit of readers drawn to this topic by the search for handwriting recognition, I'd like to mention MyScript Memo and Notes Plus on iOS. They share a handwriting recognition engine that seems to work very well in my hands. MyScript memo has a free version that anyone with an iOS device can try.
(I also see that you are looking to recognize handwritten notes scanned from paper, which these apps will not do. They recognize handwritten notes written directly on the iOS device.)
| 0.777778 | MyScript Memo and Notes Plus on iOS |
How to install social engineering toolkit? | When I searched for the social engineering toolkit I got the error "no such path or file".
I used this orders for installing it but without success.
be sure to install subversion before installing the selected tools.
(i did it)
svn co http://svn.secmaniac.com/social_engineering_toolkit set/
and the link is not working anymore.
| I wouldn't use whatever guide you are using, they moved their stuff to git several months ago:
sudo apt-get install git
git clone https://github.com/trustedsec/social-engineer-toolkit/ set/
Resources:
https://www.trustedsec.com/downloads/social-engineer-toolkit/
| 1 | sudo apt-get install git clone |
Extending Internal Link and External Link to allow selection of Images | I need to extend selection of external and Internal Link and provide a image selection.
Please see the snapshot in the below :
Here the above snapshot allows you to add properties for External Link.In the same popup can we add a field Called Image(as shown in screenshot) which will allow user to select images from the media library??
Thanks,
Suhas
| If you are talking about a whole field and not just an external link inside of a rich text field, you should create a custom field based on the documentation to do so in SDN:
http://sdn.sitecore.net/Articles/API/Creating%20a%20Composite%20Custom%20Field.aspx
You can inherit most functionality from the current link field.
| 0.777778 | Create a custom field based on the documentation to do so in SDN |
Postfix or exim: Automated/Programmatic and forwarded email setup | I'm looking to replace our current use of an external smtp provider with an in-house installation. It should handle the following situations:
Certain addresses should be forwarded to gmail addresses; we'd like to continue to use gmail as our primary email interface.
Other addresses should be available as pop/imap mailboxes.
Other addresses will be handled programmatically: they'll kick off various tasks, get logged, etc. These addresses should either kick off a process to the handle the email addresses, or should store in an easily processable format.
It should also be fairly easily configurable with domain keys, spf, and anything else it takes to allow email deliverability.
I've used sendmail in the distant past. It seems postfix and exim are the recommended options these days. My main question is: what's the best choice and setup for the forwarding of the addresses to gmail, and for the programmatic access? Is procmail still the way to go or are there better options these days?
We're using linux/ubuntu servers.
| Both exim and postfix are more than capable of doing what you need, best advice is to pick the one that's easiest for you to use and/or most familiar with.
As for dealing with forwards to gmail and into scripts best way to do this is with a global aliases file (usually kept in /etc/aliases or /etc/mail/aliases).
| 0.666667 | Exim and postfix are more than capable of doing what you need, best advice is to pick the one that's easiest to use and |
Superscript citations without brackets with the `revtex4-1` document class | Is it possible to achieve citations that are superscript and don't have brackets using the revtex4-1 document class?
An example of how they should look:
Afirmation3,4
| Sketch of a biblatex solution:
\usepackage[autocite=footnote,style=verbose-trad1]{biblatex}
\let\cite\autocite
Now when you write Something something\cite{key} the citation will be placed in a footnote at the bottom of the page
| 0.888889 | letciteautocite |
MVC3 Actionlink with submit | I am new MVC user and I am trying to make shopping cart as following MVC Music Store tutorial
I am trying to pass the radiobutton value which is different price types through actionlink.
Is it possible to pass the value with productId?
When I click the link, it will call 'AddToCart' method.
Could you help me? thanks.
Product model
namespace MvcApplication2.Models
{
public class Product
{
[Key] public int productId { get; set; }
public int categoryId { get; set; }
[Required(ErrorMessage = "Product model name is required")]
public String model { get; set; }
[DisplayFormat(DataFormatString = "{0:0.#}")]
public decimal displaySize { get; set; }
public String processor { get; set; }
public int ramSize { get; set; }
public int capacity { get; set; }
public String colour { get; set; }
public String description { get; set; }
public decimal price { get; set; }
public decimal threeDayPrice { get; set; }
public decimal aWeekPrice { get; set; }
public decimal twoWeekPrice { get; set; }
public decimal aMonthPrice { get; set; }
public decimal threeMonthPrice { get; set; }
public decimal sixMonthPrice { get; set; }
//public decimal sixMonthPrice { get { return price * 0.25M; } }
public int stock { get; set; }
public virtual Category Category { get; set; }
}
}
details.cshtml
@model MvcApplication2.Models.Product
<td>
Rental Period: <br />
@using (Html.BeginForm())
{
<div class="display-label">
@Html.RadioButtonFor(model => model.price, Model.threeDayPrice)
3 day: £@Model.threeDayPrice
</div>
<div class="display-label">
@Html.RadioButtonFor(model => model.price, Model.aWeekPrice)
1 week: £@Model.aWeekPrice
</div>
<div class="display-label">
@Html.RadioButtonFor(model => model.price, @Model.twoWeekPrice)
2 week: £@Model.twoWeekPrice
</div>
<div class="display-label">
@Html.RadioButtonFor(model => model.price, @Model.twoWeekPrice)
1 month: £@Model.twoWeekPrice
</div>
<div class="display-label">
@Html.RadioButtonFor(model => model.price, @Model.threeMonthPrice)
3 month: £@Model.threeMonthPrice
</div>
<div class="display-label">
@Html.RadioButtonFor(model => model.price, @Model.sixMonthPrice)
6 month: £@Model.sixMonthPrice
</div>
}
</td>
</tr>
</table>
<p class="button" style="margin-left:200px; width:90px;">
//Is it possible to submit the selected radiobutton value through this?
@Html.ActionLink("Add to cart", "AddToCart", "ShoppingCart", new { id = Model.productId }, "")
</p>
---Added controller---
ShoppingCartController.cs
public ActionResult AddToCart(int id)
{
// Retrieve the product from the database
var addedProduct = db.Product
.Single(product => product.productId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
| Because you say you are new right off the bat I'm going to tell you that the way you are going about this is not the best way to achieve what you are trying to achieve.
Putting a submit button at the bottom of the form will get the data to post and bind to Product if you change the top of the form to
@using (Html.BeginForm("AddToCart", "WHATEVERYOURCONTROLLERISCALLED"))
but I think you are missing a few key points here.
There are some conventions that you seem to be ignoring
ShoppingCart.cs should be named ShoppingCartController.cs and appear in the controllers folder of your project
Instead of naming each price on the model you can use a list of prices options and display them on the form as a series of radio buttons while putting the mutually exclusive choice. for example.
The Model
public class Product{
// remove all the different price properties.
// other properties go here...And while you are at it Use Pascal case for property names Eg. displaySize would be DisplaySize but I guess that is up to you.
[Required]
public string PriceChoice { get; set; }
}
The Controller
public class ShoppingCartController : Controller
{
public ActionResult Details(int productId)
{
// get the product from the database
var model = Database.GetProductById(productId);
// set a default if you want
model.PriceChoice = "a";
return View(model);
}
[HttpPost]
public ActionResult AddToCart(Product model)
{
// do whatever you need to do
return RedirectToAction("Details", new { id = model.Id });
}
}
The View
@using (Html.BeginForm())
{
<div>A: @Html.RadioButtonFor(x => x.PriceChoice , "a")</div>
<div>B: @Html.RadioButtonFor(x => x.PriceChoice , "b")</div>
@Html.ValidationMessageFor(x => x.PriceChoice )
<input type="submit" value="OK" />
}
Now that's all very abridged and basic so I hope you get the gist of it.
Also you'll find some value in reading this Post Redirect Get So while it doesn't strictly apply to what you are doing it will explain the structure of the code you are reading in the examples where you see RedirectToAction.
Now if you want to do this really cleverly you will have to learn some javascript and issue an Ajax command.
Hope this helps
| 0.777778 | RedirectToAction is not the best way to achieve what you are doing |
Mail "Can't continue" for a AppleScript function | I'm trying to write an AppleScript for use with Mail (on Snow Leopard) to save image attachments of messages to a folder. The main part of the AppleScript is:
property ImageExtensionList : {"jpg", "jpeg"}
property PicturesFolder : path to pictures folder as text
property SaveFolderName : "Fetched"
property SaveFolder : PicturesFolder & SaveFolderName
tell application "Mail"
set theMessages to the selection
repeat with theMessage in theMessages
repeat with theAttachment in every mail attachment of theMessage
set attachmentFileName to theAttachment's name
if isImageFileName(attachmentFileName) then
set attachmentPathName to SaveFolder & attachmentFileName
save theAttachment in getNonexistantFile(attachmentPathName)
end if
end repeat
end repeat
end tell
on isImageFileName(theFileName)
set dot to offset of "." in theFileName
if dot > 0 then
set theExtension to text (dot + 1) thru -1 of theFileName
return theExtension is in ImageExtensionList
end if
return false
end isImageFileName
When run, I get the error:
error "Mail got an error: Can’t continue isImageFileName." number -1708
where error -1708 is:
Event wasnt handled by an Apple event handler.
However, if I copy/paste the isImageFileName() into another script like:
property ImageExtensionList : {"jpg", "jpeg"}
on isImageFileName(theFileName)
set dot to offset of "." in theFileName
if dot > 0 then
set theExtension to text (dot + 1) thru -1 of theFileName
return theExtension is in ImageExtensionList
end if
return false
end isImageFileName
if isImageFileName("foo.jpg") then
return true
else
return false
end if
it works fine. Why does Mail complain about this?
| Try "my isImageFileName". It's not Mail, just a quirk of AppleScript.
| 0.666667 | Try "my isImageFileName" |
How do I prevent unwanted routing errors in production | ActionController::RoutingError (No route matches [GET] "/google83362a7a0f381ff0.html"):
I see the above logs in production, how should I prevent it.
If user mistypes a URL, how should I re-direct to a common error page
| Rails does this automatically when application running in production mode.When uploading application to live server, Rails takes care of handling those exceptions and rendering the correct error pages with the correct header status.You can directly find the files inside public folder.
Whenever you set up your Rails application on a live server, you give the site root as the /public folder in your application. Then, whenever a request is made to that server address, Web server first looks in that public folder and tries to serve a static asset (this is a configurable option in config/environment.rb). If it can't find the requested page, then the request is forwarded through the Ruby stack.
When in production mode, if Rails encounters an error that isn't handled, it throws the error to the stack, which then tells Web server to render an appropriate error.
Here are some common errors that you'll see in development mode and what they render in production mode:
ActiveRecord::RecordNotFound => 404 (page not found)
nil.method => 500 (server error) unless you turn off whiny nils
ActionController::RoutingError => 404 (page not found)
| 1 | When uploading application to live server, Rails takes care of handling error pages with correct header status. |
If you attempt to predict a Roulette wheel $n$ times, what's the probability you'll get $5$ in a row at some point? | I'm talking about a Roulette wheel with $38$ equally probable outcomes. Someone mentioned that he guessed the correct number five times in a row, and said that this was surprising because the probability of this happening was $$\left(\frac{1}{38}\right)^5$$
This is true if you only play the game $5$ times. However, if you play it more than $5$ times there's a higher (should be much higher?) probability that you'll get $5$ in a row at some point.
I was thinking about how surprised this person should be at their streak of $m$ correct guesses given that they play $n$ games, each with probability $p$ of success. It makes intuitive sense that their surprise should be proportional to $1/q$ (or maybe $\log(1/q)$ since $1$ in a billion doesn't surprise you $10$ times more than $1$ in $100$ million), where $q$ is the probability that they get at least one streak of $m$ correct guesses at some point in their $n$ games.
So, with the Roulette example I was thinking about, $p=1/38$ and $m=5$.
I tried to find an explicit formula for $q$ in terms of $n$, and encountered some difficulty, because of the non-independence of "getting a streak in the first five tries" and "getting a streak in tries $2$ through $6$" (if the first is a failure, it's much more likely that the second will be too).
In summary, two questions:
How do I find the probability that you get $5$ correct guesses in a row at some point if you play $n$ games of Roulette?
More generally, what is the probability that you get $m$ successes at some point in a series of $n$ events, each with probability $p$ of success?
The variables satisfy $\,\,\,m,n \in \mathbb{N}$, $\,\,\,m\leq n$, $\,\,\,p \in \mathbb{R}$, $\,\,\,0 \leq p \leq 1$.
If we write the answer to the second question as a function $q(m,n,p)$, then we can say that $q$ should be increasing with $n$, decreasing with $m$, and increasing with $p$. It should equal $p^n$ when $m=n$ and should equal $1$ when $p=1$ and $0$ when $p=0$.
I feel as though this should be a basic probability problem, but I'm having trouble solving it. Maybe some kind of recursive approach would work? Given $q(n,m,p)$, I think I could write $q(n+1,m,p)$ using the probability that the last $m-1$ results are all successes ...
| Feller, "An Introduction to Probability Theory and Its Applications", Third Edition, gives a useful approximation on p. 325, equation 7.11.
Suppose we toss a possibly biased coin $n$ times, where the probability of a head is $p$ and $q = 1-p$. Let $q_n$ be the probability there is no run of $r$ successive heads. Then
$$q_n \sim \frac{1-px}{(r+1-rx)q} \cdot \frac{1}{x^{n+1}} $$
where $x$ is the smallest positive root of $1 - x + q p^r x^{r+1} = 0$.
For your problem, we have $r = 5$, $p = 1/38$, and $q = 37/38$, from which we calculate $x \approx 1 + 1.228854 \times 10^{-8}$.
It works out that $q_n = 1/2$ for $n \approx 5.64 \times 10^7$, i.e. it takes about 56 million trials to have a 50% chance of guessing correctly 5 times in a row.
| 1 | Feller, "An Introduction to Probability Theory and Its Applications" |
Take quick notes without interrupting current activity | When I’m in the middle of something and get an idea, I want to note it down without interrupting what I’m doing.
Desired workflow: adding a note
I press a key (or a key combo).
(should work everywhere: while browsing, while writing, while watching a video, etc.)
A note window opens.
(just a single text field, no title/category/etc.)
(it must be empty)
(doesn’t have to be a GUI)
I enter my note.
I press, e.g. Enter to save the note.
(the window must close automatically)
Browsing notes
Just a simple list/table of all saved notes.
Especially not just text files which I’d have to open separately to read their content.
Should display the date/time when a note was saved.
Should offer a quick way to delete notes.
No need for editing notes.
Formal requirements
A solution must be FLOSS and run natively on GNU/Linux.
| It sounds to me like Tomboy would definitely do the job. Excerpt from the website:
Tomboy is a desktop note-taking application for Linux, Unix, Windows, and Mac OS X. Simple and easy to use, but with potential to help you organize the ideas and information you deal with every day.
Notable Features
Highlighting text
Inline spelll checking
Auto-linking web & email addresses
Undo/redo
Font styling & sizing
Bulleted lists
Note synchronization across several computers
Emacs-style binding can be used, and it has several plugins. As for the list without need of opening the notes, all notes can be exported to an HTML page. This whole thing may however be too fancy for your needs.
| 0.777778 | Tomboy note-taking application for Linux, Unix, Windows, and Mac OS X |
How do I change the MySQL database directory? | I am using CentOS with cPanel. On my server, all MySQL databases save at /var/lib/mysql. Now /var is 100% full and MySQL has stopped working. How can I move the databases to a new directory like /home/mysql especially considering that this server is managed with cPanel?
| Stopping the Default Install/Instance
service mysqld stop
Clear Current Config
rm /etc/my.cnf
Uninstal the Default Install/Instance
yum remove mysql mysql-server -y
Clear Current Datadir
test -d /var/lib/mysql/ && rm -rf /var/lib/mysql/
Clear the 'New' Datadir
test -d /mysql/mysql/ && rm -rf /mysql/mysql/
Install it again
yum install mysql mysql-server -y
Check the service status
service mysqld status
Start it - just to create a first/default structure
service mysqld start
Check the service status
service mysqld status
Interrupt the current MySQL server installation
service mysqld stop
Ensure that you don´t have anymore instance/service running
ps axu | grep mysql
Move the mysql data directory to '/mysql' partition and create the symbolic link
test -d /var/lib/mysql/ && mv /var/lib/mysql/ /mysql/ && ln -s /mysql/mysql /var/lib/
Check symbolic link and the real path
ls -lrth /var/lib/ | grep mysql
Set permission on new Datadir
chown -R mysql:mysql /mysql/mysql
Start it
service mysqld start
Try to connect (keep in mind that the default install of MySQL doesn´t set a 'pwd' for 'root' user and then you should connect with 'blank password'
mysql -u root -p --host 127.0.0.1
Once connected to MySQL, create a new db just to test if it´s working and where MySQL will create folder/file structure
create database DBTesteNew;
exit
Check if the new db is on the 'new datadir'
ls /mysql/mysql
Make sure the mysqld is set to start on boot time
chkconfig mysqld on
restart
reboot
| 1 | Stopping the Default Install/Instance service mysqld stop Clear Current Config |
Repair wood floor damage | I just moved into a new house. I have never had wooden floors until now. Today, we moved a box and saw a strange waxy looking white gunk on the floor after moving a box. Unknowingly, I scraped it off with my fingernails. Now, I am pretty sure I scraped off the top layer of my wood floors finish.
I read about wood floor finishes. Some say I should try to match the floor's finish, but I don't know what it is. Others have said polyurathane can just be brushed on.
The wood and stain appear to be fine, but this waxy stuff on top I destroyed. Its about a 36sq in area that I destroyed.
Damaged Floor
Good Floor
What can I do to fix this? Do I need a professional?
| This is an educated guess only because I can't really see or feel what you are describing. This may be old floor wax that has had something damp left sitting on it. Often in older homes folks would use old fashion floor waxes that will discolor or turn white with age, water, friction or heat. You may first try using a little mineral spirits or a mild cleaning agent with a polishing compound, such as Bar Keepers Friend with a soft cloth on a small spot to see if it will remove the white residue. If in fact this floor has been treated with a wax product, the entire floor would have to be stripped of wax, perhaps buff sanded and restained, then protected with a few coats of Urethane. Don't attempt to apply urethane until you have determined what is causing the white waxy residue. Putting any coating such as urethane over a waxed floor will bubble, peel, and create a mess to clean up. another test you could do would be to gently scrape a very small section of the white stain with a putty knife. If the material comes off easily it may be wax. it may be old varnish, but that would not feel waxy, but not out of the question. Let us know what you find, and we can go from there. Good Luck
| 1 | Old fashion floor waxes that discolor or turn white with age, water, friction or heat |
Could Apple and Microsoft allow the GPLv3 on their locked-down devices? | It seems that both Apple and Microsoft prohibit GPLv3-licensed software in the app stores for their locked-down devices (i.e. iOS, Windows Phone and the Metro part of Windows). I have heard various explanations for this. However: Would they even be able to allow this license in their app stores if they wanted to, or does the GPL's anti-tivoization clause already prohibit this?
| Apple effectively ban any GPL because they only allow redistribution through the store and by registered developers. So if you distribute the GPL to your users they cannot abide by it.
Apple could simply allow any GPL app to be redistributed by any user through a free section of the site - but chose not to. Ironically OSX is based on a free BSD Unix kernel.
Microsoft have an historical objection to "the cancer of open source" and their licence explicitly bans any open source licenced app that requires redistribution of source (ie GPL). This is their right, it's a business decision - just like banning sales in a particular country. As their position in the market becomes less dominant they might change their mind
| 1 | Apple bans any GPL because they only allow redistribution through the store . |
How to allow only one product in a cart? | We have a requirement, wherein a customer will be allowed to add only one product to the cart at a time. However he/she can add any quantity of that product.
How can I prevent a product from adding to cart if there is already a product present in the cart?
Can some one help on this?
| I know this topic is something old, but i had a similar problem. I want only one item in cart and if customer adds a new one, i want to replace the old one with the new one. So i override the addAction (described here like this:
public function addAction(){
$items = $this->_getCart()->getItems();
foreach ($items as $item)
{
$itemId = $item->getItemId();
$this->_getCart()->removeItem($itemId);
}
parent::addAction();
}
| 1 | if customer adds a new item, i want to replace the old one with the new one |
Integrate a division of polynomials | Hi I have the following integral:
$$\int \frac{2x}{x^2+6x+3}\, dx$$
I made some changes like:
$$\int \dfrac{2x+6-6}{x^2+6x+3}\, dx$$
then I have:
$$\int \dfrac{2x+6}{x^2+6x+3}\, dx -\int\dfrac{6}{x^2+6x+3}\, dx$$
and thus: $$\ln(x^2+6x+3)-\int\dfrac{6}{x^2+6x+3}\, dx$$
Ok, I have decomposed $$\frac{2x}{x^2+6x+3} $$ in: $$ \frac{3+\sqrt6}{\sqrt6(x+\sqrt 6+3)} + \frac{3-\sqrt6}{\sqrt6 (-x+\sqrt6-3)}$$
How can I integrate this expressions?
| A start: Note that $x^2+6x+3=0$ has the roots $\alpha=-3+\sqrt{6}$ and $\beta=-3-\sqrt{6}$. Thus $x^2+6x+3=(x-\alpha)(x-\beta)$.
Express $\frac{6}{(x-\alpha)(x-\beta)}$ as $\frac{A}{x-\alpha}+\frac{B}{(x-\beta)}$ (partial fractions).
| 0.888889 | $x2+6x+3=0$ has roots $alpha=-3+sqrt6 |
good 3d model with bones? | Can anyone direct me to a site where I can download a free 3D model with a skeleton so I can practice using them in the XNA environment untill I'll make my own models?
If the model is human-ish (2 legs , 2 hands and stands up) that would be great!
| Our studio has entry test for animators and it is human 3D model with bones. It is rigged maya scene. You are allowed to use it for non comercial purposes.
download model
whole page (in czech language)
| 0.888889 | Studio has entry test for animators |
Why do some programmers categorize C, Python, C++ differently? - regarding level | I am taking an introductory course on python and the instructor says that python is a high level language and C and C++ are low level languages. It's just damn confusing. I thought that C, C++, Python, Java, etc were all high level languages. I was reading questions at stackoverflow on C, C++, etc and they all seem to refer to those languages as high level. it seems to me that some programmers use those terms interchangably. Please clarify this for me.
| The line between the "low-level" and the "high-level" languages shifts from time to time.
For example:
Back in the days of UNIX, C was a high level language.
Today C doesn't have the structures like the mapping types(dictionaries), iterators etc. which today's high-level languages like Python have. So the line has shifted, and C has now fallen into the low-level group.
Low-Level Languages:
These languages are "close" to what the machine can execute (the lowest level being : Assembly Code!).
When working with these languages, the programmer has to think about the lowest level stuff like memory management.. You are close in that sense to the hardware, that you have to directly work with it.
High-level Languages:
These languages take you away from the hardware, as they manage things like memory themselves. When you work with these languages, memory is a factor(obviously), but you don't work with the hardware directly. Instead the language manages that, keeping you away (maybe higher) from the lower, hardware interface.
| 1 | Low-Level Languages: These languages take you away from hardware . |
WPF RichTextBox Image Link issue | I am loading a .rtf file into a WPF Rich TextBox and my images that have links are getting this underline property added. I do not want the underline and cant seem to get rid of it.
public MainWindow()
{
InitializeComponent();
Assembly assembly = Assembly.GetExecutingAssembly();
Stream s = assembly.GetManifestResourceStream("WPFRichTextIssue.Sigs.MSC.rtf");
using (s)
{
TextRange TR = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);
TR.Load(s, DataFormats.Rtf);
}
}
I have tired to find the underlined images with
if (TR.GetPropertyValue(Inline.TextDecorationsProperty) == TextDecorations.Underline)
{
}
else
{
// Do something
}
But the Image is not Inline.Text so it does not find it... Any help would be great.
I also thought maybe i could overwrite the Rich Textbox default functionality that causes the underline of links but all i can seem to find to make that change is to the Inline Text nothing for the images and the images are not affected.
The only other option i can think is if there was a way to change the .rtf file to make sure it did not have any underline attributes but unless I am missing something that does not seem to help either.
Entire VS 2012 project issue sample... Download Project
thanks
| Looking in your XAML, just after the RTB opening tag that looks something like this:
<RichTextBox x:Name="RTB_Reply" HorizontalAlignment="Left" Height="157" Margin="302,338,0,0" VerticalAlignment="Top" Width="488" IsReadOnly="True">
Paste this:
<RichTextBox.Resources>
<Style TargetType="{x:Type Hyperlink}">
<Setter Property="TextDecorations" Value="{x:Null}"/>
</Style>
</RichTextBox.Resources>
done deal. =D
| 0.777778 | IsReadOnly "True" |
why ions and electrons are at different temperatures in plasma? | In plasma, collision rate among ions or electrons is much larger than the collision rate between ions and electrons. why is that so?
| Consider a plasma that just's been formed and then left alone. Being far from equilibrium, the plasma will evolve towards an equilibrium state. At this stage, it's not very useful to characterize the plasma with a temperature because the velocity distribution would bear little resemblance to a Boltzmann distribution, or really any kind of distribution function with meaningful moments.
Let's assume that the plasma is being driven towards equilibrium by collision events. The particles will lose energy during each inelastic collision event, with some being more inelastic than others. The degree of inelasticity will depend significantly on the mass ratio: ion-ion collisions and electron-electron collisions will be inelastic compared to ion-electron collisions.
Since the $i-i$ and $e-e$ collisions are relatively inelastic, it often occurs that the ions and electrons quickly develop their own "temperatures". The ion velocity distribution rapidly approaches a Boltzmann distribution with temperature, and the electrons also rapidly approach a Boltzmann distribution with some different temperature. If you were to superpose the two, you'd get a funny-looking distribution with a tall top and wide tails, i.e. not global equilibrium.
The "centeredness" or "tailedness" (basically kurtosis) of the total distribution tells you how far from equilibrium the plasma is. The further the system is from equilibrium, the faster it will try to equilibrate via collisions. So if the temperatures are very different, the $i-e$ collision frequency will be high. If the temperatures are not too different, the $i-e$ will be lower, but still higher than the $e-e$ and $i-i$ systems that have already approximately equilibrated with themselves.
Note: In laboratory experiments, it's common to produce plasmas whose ions and electrons do not settle to a Boltzmann distribution. In that case, the kurtosis argument flies out the window. Another major complication arises if the electrons and ions have different flow speeds, where so-called "two-stream" or "bump-on-tail" instabilities become important in the equilibration physics.
| 0.777778 | ion-ion collisions and electron-electron collisions are inelastic compared to Boltzmann |
How best can I discover what is up with my electrical bill? | This might be subjective, I don't know. However, it's a serious problem for me. My electrical bill is outrageous. It's three times as large as my next-door neighbor, and four or five times the size of my neighbor's across the street. It's worse in the summer (I live in central TX), but I've had the air conditioner inspected, and while the house is right at the maximum capacity for our unit, the unit should still be able to take care of the load. That also doesn't explain why our winter bills are larger than the comparables.
What I would like to do is check the amount of current drawn by each running appliance and calculate where all my money is going. I just don't know how to go about doing this.
| Brultech has a solution that will show you how much each circuit uses. You might need an electrician to install it. It works like the ammeter but tracks usage over time.
| 1 | How much each circuit uses |
What kind of dose can you expect from a radioactive lens? | I read that lens makers used to use radioactive glass to increase the refractive index property of their lenses.
How radioactive are they?
Here are some example dosages; where would looking through the viewfinder for an hour fit?
http://xkcd.com/radiation/
| The article in rfusca's answer includes some references: The Aero-Ektars, by NASA scientist Michael Briggs; Radioactive Materials in Camera Lenses, from the Health Physics Society (an organization focused on radiation safety); and Thoriated Camera Lens (ca. 1970s), from Oak Ridge Associated Universities's professional training on radiation safety.
From the ORAU PTP article:
Measurements have indicated that the exposure rate at a depth of 10 cm
in the body of an individual carrying a camera containing 0.36 uCi of
thorium would be approximately 0.01 mrem/hr. Based on this value,
NUREG-1717 calculated that a serious photographer might receive an
annual exposure of 2 mrem. This assumed that the photographer carried
the camera 30 days per year and for 6 hours per day. They also
estimated an exposure of 0.7 mrem per year for an average
photographer. If the camera lens contained the maximum permitted
concentration of thorium (30%), NUREG-1717 estimated that the
aforementioned annual doses could triple.
This puts the "6hrs/day for a month" usage at about the same as getting a chest X-ray — or, one little green square on the xkcd chart. Or to put it another way, using the lens six hours a day for a year would be the same as taking three round-trip flights from one US coast to the other in that year. Not completely trivial, but not something people normally stress about. And that'd be really heavy usage.
The articles indicate that exposure to the eye might be a greater concern than overall dosage, particularly if you happen to have thorium in an eyepiece (unlikely for general photo equipment). So you might decide to spend a little less time holding the camera right to your eye than you might otherwise.
Assuming (based on the reading) that looking through the viewfinder is very roughly an order of magnitude greater exposure than the general usage, looking through the viewfinder for an hour is about 1µSv — equivalent to getting an arm x-ray.
| 1 | The Aero-Ektars, by Michael Briggs, and Thoriated Camera Lens (ca. 1970s) |
What exactly is computation? | I know what computation is in some vague sense (it is the thing computers do), but I would like a more rigorous definition.
Dictionary.com's definitions of computation, computing, calculate, and compute are circular, so it doesn't help.
Wikipedia defines computation to be "any type of calculation that follows a well-defined model."
It defines calculation as "the deliberate process that transforms one or more inputs into one or more results, with variable change." But it seems this definition includes many actions as computations even though they aren't typically thought of as computation.
For example, wouldn't this entail that, say, a bomb exploding is a computation, with the input being the fuse being lighted and the output being the explosion?
So, what exactly is computation?
| This is the question that Turing set out to solve in his famous 1936 paper, On computable numbers, with an application to the Entscheidungsproblem, a paper in which he comes up with (what came to be known as) the Turing machine model. See in particular Section 9.
Turing's work is in the context of computable numbers. There are other notions of computation appropriate for computing other kinds of structures, and their study forms part of computation theory (also known as recursion theory).
The main difference between the common notion of computation and your example (an exploding bomb) is the thing being computed. What is being computed by your exploding bomb? Another difference is the computational means, but one can envision a mechanical contraption which uses bombs to compute something more legitimate.
Another point is whether the classical notions of computation apply to what we perceive today as computation – namely, two-way interaction between the computer and the user. This is a common criticism levelled against the classical notional of computability, though interaction can be modelled using the tools of computation theory (it's just not what you learn in class).
| 1 | What is being computed by an exploding bomb? |
Digital circuits | A can't find examples about what I want to do with the circuitTikZ package. I want to put a letter and a black port at the left of this circuit and I want the nand4 to act like an inverter.
\begin{circuitikz} \draw
(0,2) node[nand port] (nand4) {}
(2,3) node[nand port] (nand3) {}
(4,2) node[nand port] (nand2) {}
(0,0) node[nand port] (nand1) {}
(nand1.out) |- (nand2.in 2)
(nand4.out) |- (nand3.in 2)
(nand3.out) |- (nand2.in 1)
;\end{circuitikz}
| One possibility:
\documentclass{article}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}
\draw
(0,2) node[nand port] (nand4) {}
(2,3) node[nand port] (nand3) {}
(4,2) node[nand port] (nand2) {}
(0,0) node[nand port] (nand1) {}
(nand1.out) |- (nand2.in 2)
(nand4.out) |- (nand3.in 2)
(nand3.out) |- (nand2.in 1)
;
\draw
([xshift=-1cm]nand1.in 1)
coordinate (aux) node[left] {$c$} to[short,*-]
(nand1.in 1);
\draw
([xshift=-1cm]nand1.in 2)
node[left] {$d$} to[short,*-]
(nand1.in 2);
\draw
(aux|-nand3.in 1)
node[left] {$a$} to[short,*-]
(nand3.in 1);
\draw
(nand4.in 1) -- coordinate (middle) (nand4.in 2);
\draw
(aux|-middle)
node[left] {$b$} to[short,*-]
(middle);
\end{circuitikz}
\end{document}
| 0.777778 | usepackagecircuitikz draw (0,2) node[nand port] (nand2) |
intersection between two multipolygons yielding anomalous GeometryCollection object full of LineString's & Polygon's (trying to get intersect area) | Normally when I call the #intersection method on a multipolygon to find the intersection shape on another multipolygon I get a multipolygon returned back to me. Either that or something else I can then call the #area function on.
Well, 150 spatial joins into a list of zoning shapefiles (ie this is a rare case) I'm scanning through my code throws an error because it can't call the #area method on a CAPIGeometryCollection. I am having problems linking qgis with my postgresql db and don't know how to create a kml for a "GeometryCollection" object
Here's what the WKT string output for the intersection shape looks like:
"GEOMETRYCOLLECTION (LINESTRING (1480424.245856002 596629.5658560097, 1480362.875856012 596566.8158560097), LINESTRING (1480362.875856012 596566.8158560097, 1480293.995856002 596496.4358560145), LINESTRING (1480293.995856002 596496.4358560145, 1480235.625856012 596435.0658560097), LINESTRING (1480235.625856012 596435.0658560097, 1480186.495856002 596385.8158560097), LINESTRING (1480186.495856002 596385.8158560097, 1480146.125856012 596345.3758560121), LINESTRING (1480146.125856012 596345.3758560121, 1480141.125856012 596341.3158560097), LINESTRING (1480141.125856012 596341.3158560097, 1480090.995856002 596301.3158560097), LINESTRING (1480090.995856002 596301.3158560097, 1480044.875856012 596263.8758560121), LINESTRING (1480044.875856012 596263.8758560121, 1480005.745856002 596231.995856002), POLYGON ((1480512.6034600246 596678.2322904326, 1480512.598981008 596678.1839810014, 1480511.7765895594 596677.7314431852, 1480512.6034600246 596678.2322904326)), POLYGON ((1480005.745856002 596231.995856002, 1479874.7139810026 596136.0839810073, 1479816.8752310127 596088.7502310127, 1479758.3752310127 596040.8127310127, 1479707.547731012 595999.19689875, 1479758.375856012 596040.8158560097, 1479816.875856012 596088.8158560097, 1479875.375856012 596136.6258560121, 1480005.745856002 596231.995856002)))"
I could skip this error with a rescue block or a next identifier and move on per case but that's not very professional. Documentation on this issue is extremely slim so I figured I'd contribute with a stackexchange question
Plus (just checked), I can't load GEOMETRYCOLLECTION wkts into qgis (currently passing in the polygons & line string arghhs each by hand)
(note: someone with >300 points or whatever mark this question with these new question tags: 'geometry-collection' & 'multi-polygon', they're pretty basic to gis I think, esp the multipolygons, thanks)
EDIT:
I could pluck out the polygon(s) from these collections, but I'm wondering what these linestrings mean (i.e. maybe they're the exterior rings of polygons that are part of the intersect shape)
| Solution for now: ignore the LineStrings, these are probably produced by an "st_touches" type spatial join where only the perimeters of the multipolygons are touching
RGeo allows you to break out the pieces of a Geometry Collection so I wrote some code to catch the intersect shape if its a GeometryCollection type, sending it to a different area to pluck out the polygons, sum up their size, mark that as the intersect size, and move on
x = shape.intersection(p.proj_shape_2264)
if x.geometry_type.to_s == "GeometryCollection"
area = 0
(0..(x.count - 1)).to_a.each do |k|
collection_shape = x.geometry_n(k)
next if collection_shape.geometry_type.to_s == "LineString"
area += collection_shape.area
end
z.intersect_size = area
else
| 1 | GeometryCollection type spatial join where only the perimeters of multipolygons are touching RGeo |
Improper shutdown, now 3 flashes on boot | I had to do a hard power off on my Pi, as it had crashed. Now, when I turn it on, I get 3 flashes of the OK LED, which means either loader.bin or start.elf is not found. I have plugged the SD card into my Windows PC to browse the boot partition and neither of those files is present. Is there any way to repair the boot partition and allow the Pi to boot without losing any data on the card? I have important data that hasn't been backed up yet on the card.
| I'm afraid you're going to have to fix the installation manually.
You can download the relevant bin and elf files from the Raspberry Pi GitHub repository.
Then mount the boot partition of the SD card and copy the files onto it.
If this doesn't work then something more serious has gone wrong and you're going to have to re-flash the entire image.
However, you should be able to save your data if you can mount the SD card as you can simply copy off the files you want. They will be in the directory /home/[username].
I hope this helps, let me know if you have any more trouble.
| 1 | Install the boot partition of the SD card |
Increasing voltage source frequency | I am trying to simulate a simple circuit using a simulation program like SPICE. In the beginning of the circuit I have a pulse train voltage source, later it is connected to a normal LPF. The voltage source frequency is set as 1 kHz, my question is how to increase this frequency?
The only options that I have is to change the time of the cycle and the voltage. If I set 1 ms and 5V, the frequency will be 1 kHz.
If I change the time to 0.5 ms, the result will be 5V for 0.5 ms and the rest is 0. (The second cycle will not start after 0.5 ms, so the frequency is same 1 kHz). Strange!
How do I increase the frequency of the voltage source?
| You can change the frequency by making changes in either time or frequency. As you mentioned that you have changed time to 0.5ms, please make sure whether you have changed time period of one complete cycle (on time + off time). If your time period of one complete cycle is 0.5ms, your frequency should be 2khz, because frequency is number of cycles per second.
| 0.777778 | Change the frequency by making changes in time or frequency |
Is it usual for finished PhD students to send out physical copies of their thesis to unknown persons? | Some time ago, a recently-graduated PhD has sent me a physical (book) copy of his dissertation. The graduate works in a somewhat-related field, but is personally entirely unknown to me (I have some loose connections to the advisor, though). I was reasonably confused by this - I personally have never heard of a custom of sending physical theses to anybody besides maybe parents. I was 100% convinced that I received the dissertation in error (also because the mailing was addressed to my name, but using a wrong department name).
Last week I by chance got hold of the graduate and told him that he sent me his thesis by accident, and asked whether he wants to have it back. He seemed confused and a little bit annoyed that I wanted to give his thesis back - it turns out he actually sent me the book on purpose, assuming that I would be interested in his work. He told me that he thought it is customary to send a finished PhD thesis to people that he thought might profit from its results.
So, is this a thing, at least in some fields? If so, why not just send the core papers or a link to a digital version of the thesis? Mailing out printed copies seems extremely expensive, and also (at least for me) very unlikely to result in anything else than me having another book gathering dust in my office shelf. I am honestly very unlikely to read an entire thesis, especially if I only have it in a dead-tree book version.
| In some countries you print a large number of copies (as stated by Pieter Naaijkens), in some only a single digit number which should then be distributed to a specific set of recipients. Regardless it is not unusual that a person might distribute copies to people that might have some interest in it. It is, however, not a must and the recipients is up to the author. When you send a thesis I think it is wise to write an accompanying letter explaining why the thesis is sent to the specific person. To send them without such a personal note may come across as a little odd and can of course be misunderstood.
I did my PhD in the US and made a larger number of cheap copies (do not remember how many) to distribute among friends. I sent a few to others whose research I had built on. This was outside of the, at least then, mandatory five bound copies. In Sweden, where I now reside, printing of about 250 is mandatory and the student can print additional copies at their own cost. We recommend students to think about sending their thesis to people they can imagine would be interested in it. Since the life time of a thesis is usually quite short, most will soon be properly published, it is a good way to advertise your PhD and your work right after you have completed the work.
| 1 | In some countries you print a large number of copies (as stated by Pieter Naaijkens) |
Dealing with digital circuits and their associated switching speed? | When designing a digital one-minute counting circuit I came across a difficult problem.
Basically, I designed the circuit to drive the (normally HIGH) clock of the 10s slot low if the 1s slot's current state was 9 (actually, just if the first and last bits are HIGH -> 1001)
The devices I am using are positive edge, so when the 1s slot returns to zero the condition is no longer satisfied - therefore the clock returns to a HIGH state and increments the 10s slot.
The problem is that I was getting double clock problems(7->8 transition and the designed clock mechanism).
It turns out that there was just enough delay in the switching between 7 -> 8 (0111 -> 1000) that the first/last bit HIGH condition is satisfied:
i.e., some combination occurs in the transition period to register a logical HIGH at the output
1001 1011 1101 1111
The temporary solution to the problem I came up with was to actually keep the clock for the 10s slot LOW until the condition where the 1s slot equals 0 (0000) is satisfied(So, essentially clock WHEN we get to the state as opposed to before). However, this solution requires too many gates (a 4-input NOR minimum). My previous design was actually fed from another part in the design that is already present, so it didn't require any additional circuitry.
Any ideas on a more efficient solution?
The IC's used in this design are the 74LS47 (7Segment decoder) and the 74LS163 (4-bit binary counter). The pull-down resistor inclusion is a mechanism to set the counters to 00 and hold while the switch is closed.
| The way I see it, you're causing problems for yourself by using multiple clock domains, and worse, deriving a clock from data. The problem with data is that it has to settle. That's why we have separate clocks. A combinatorial circuit which evaluates some variables and then drives a clock invites trouble.
Secondly, if you're going to kludge it, at least do it right. You cannot detect a 9 by noting that the first and last of four bits bit are 1. If you want a signal which fires when there is a 9, you must evaluate all four bits earnestly and trigger that signal only when they are 1001.
There is no reason not to design this in such a way that a single clock is distributed to all the chips. Then it's a matter of running the clock slowly enough that all inputs and outputs settle before each edge arrives.
Read the data sheet. The TI one clearly says "The carry look-ahead circuitry provides for n-bit synchronous applications without additional gating. Instrumental in accomplishing this function are two count-enable inputs and a ripple carry output. Both count enable inputs P and T must be high to count [...]".
It sounds like these chips are intended to be hooked up together easily. You can prevent the upper digit from counting up on the next clock edge by de-asserting its count enable inputs. Whenever the lower digit is nine, your circuitry can enable the upper digit chip to count, and also set up the lower digit to perform a synchronous reset.
When the next clock edge arrives (to all chips), the upper digit counts up, and the other flips to zero.
| 1 | Deriving a clock from data is causing problems for yourself |
Why do people rewrite some libraries to many programming languages? | There are some libraries, which are available in their versions written in many different programming languages, like for example Lucene, which is written in Java (as they say, 100% pure Java), but has also its versions in C++, C, Perl, Ruby, Lisp and some other languages. And I'm talking about implementations in these languages, not just FFI interfaces.
Why do people do that? I can see one obvious reason: deployment and distribution (and probably development as well) easier when a project has fewer dependencies. But is there anything else? In what situations is it worth it?
| Sometimes you're developing for a platform where the tool the software was written in (Java in Lucene's case) isn't an option. If you want the features without having to reengineer the code from scratch, you port the code.
| 0.333333 | Creating a platform where the software was written in Java isn't an option |
Bordermatrix without brackets | I am hanging on this one since yesterday and was not able to find an example nor anything in the documentation --- maybe I am blind?
What i want is a matrix with border annotations BUT without the brackets (neither round nor squared nor curled, each of which have been discussed here). I also want to make the bordertext (A-E) bold and italic on the X and the Y axis...
I have some code to construct the matrix as I have it right now:
\documentclass{article}
\def\VR{\kern-\arraycolsep\strut\vrule &\kern-\arraycolsep}
\def\vr{\kern-\arraycolsep & \kern-\arraycolsep}
\begin{document}
\LARGE
$\bordermatrix{
& A & B & C & D & E \cr
A & 0 & 0 & 1 & 0 & 1 \cr
B & 0 & 0 & 1 & 0 & 0 \cr
C & 0 & 1 & 1 & 0 & 1 \cr
D & 1 & 0 & 1 & 0 & 0 \cr
E & 1 & 1 & 1 & 0 & 0 }$
\end{document}
| Don't use \bordermatrix, that's all!
\documentclass{article}
\begin{document}
\begin{tabular}{c @{\hspace{2\tabcolsep}} *{5}{c}}
&
\itshape A &
\itshape B &
\itshape C &
\itshape D &
\itshape E
\\[1ex]
\bfseries A & 0 & 0 & 1 & 0 & 1 \\
\bfseries B & 0 & 0 & 1 & 0 & 0 \\
\bfseries C & 0 & 1 & 1 & 0 & 1 \\
\bfseries D & 1 & 0 & 1 & 0 & 0 \\
\bfseries E & 1 & 1 & 1 & 0 & 0
\end{tabular}
\end{document}
If you want the column and row headers to be bold italic, just tell TeX to.
\documentclass{article}
\newcommand{\bolditalic}{\bfseries\itshape}
\begin{document}
\begin{tabular}{c @{\hspace{2\tabcolsep}} *{5}{c}}
&
\bolditalic A &
\bolditalic B &
\bolditalic C &
\bolditalic D &
\bolditalic E
\\[1ex]
\bolditalic A & 0 & 0 & 1 & 0 & 1 \\
\bolditalic B & 0 & 0 & 1 & 0 & 0 \\
\bolditalic C & 0 & 1 & 1 & 0 & 1 \\
\bolditalic D & 1 & 0 & 1 & 0 & 0 \\
\bolditalic E & 1 & 1 & 1 & 0 & 0
\end{tabular}
\end{document}
| 0.888889 | documentclassarticle begintabularc |
Convert "Mon Aug 01 09:08:25 CDT 2011" to a usable date/time using Excel | I have a giant spreadsheet with computer names and the date stamp that they last reported into our PGP server that I need to convert to a usable date/time, so I can sort the column by the time the computer last reported. The format of the field now is as follows:
Mon Aug 01 09:08:25 CDT 2011
All of them have a 3-character day followed by a 3-character month followed by a 2 character date, and so on, so someone with some Excel skill should be able to parse it out.
Edit -- The closest I have come to getting it is using this formula:
RIGHT(L2,4),VLOOKUP(MID(L2,5,3),MonthLookup!A:B,2,FALSE),MID(L2,9,2)
Where L2 is the field I am trying to convert and MonthLookup is a sheet with two columns, the first column being the 3 character month ("Jan", "Feb", etc.) and the second column being the numerical month (1, 2, etc.)
This gives me a usable date, but I need to keep the time as well.
| Here's the simplest way, though there are others:
=DATEVALUE(MID(A1,9,2) & MID(A1,5,3) & RIGHT(A1,4)) +
TIME(MID(A1,12,2),MID(A1,15,2),MID(A1,18,2))
| 1 | =DATEVALUE(MID(A1,9,2) & MID (A1,5,3) & amp; |
Using logical operators on loops results in contradiction | I'm dealing with a really, really weird issue in JavaScript. I'm working on a validator script that loops through a list of fields with jQuery. Each validation is tied to a regular expression on an object that goes like this:
var formats = {
email: /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g,
phone: /(?!:\A|\s)(?!(\d{1,6}\s+\D)|((\d{1,2}\s+){2,2}))(((\+\d{1,3})|(\(\+\d{1,3}\)))\s*)?((\d{1,6})|(\(\d{1,6}\)))\/?(([ -.]?)\d{1,5}){1,5}((\s*(#|x|(ext))\.?\s*)\d{1,5})?(?!:(\Z|\w|\b\s))/gm,
numeric: /(\d+)(((.|,)\d+)+)?/g,
url: /^((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www.))+(([a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(\/[a-zA-Z0-9%:\/-_\\?\.'~]*)?$/gi
};
Then I've created a function that given two parameters, the format and the test subject, returns true or false (merely a wrapper of the test method for the RegExp object):
validy.is = function(what, str) {
return formats[what].test(str);
};
On a jQuery collection, I have INPUT elements with classes named accordingly to each format:
<input type="text" class="field email" id="field-1-1" />
<input type="text" class="field phone" id="field-1-2" />
...
Then, my validation function goes like this:
formBuilder.validate = function() {
console.info("=== STARTING VALIDATE ===");
var isValid = true;
var allFields = $(".field", formBuilder.form).toArray();
var validable = ["email","phone","numeric","url"];
var errors = {
"email": "Debés ingresar una dirección de e-mail válida (por ejemplo: [email protected]).",
"phone": "Debés ingresar un número de teléfono válido.",
"numeric": "Debés ingresar un número.",
"url": "Debés ingresar una dirección Web válida (por ejemplo: www.misitio.com.ar)."
};
for (var f = 0; f < allFields.length; f++) {
var $field = $(allFields[f]);
console.info($field);
console.info("--> Field has classes: " + $field.attr("class"));
for (var v = 0; v < validable.length; v++) {
var validableClass = validable[v];
if ($field.hasClass(validableClass)) {
console.info("--> Validating against " + validableClass + " with value <<" + $field.val() + ">>");
console.info("--> Test result: validy.is(validableClass, $field.val()) = " + vw.validy.is(validableClass, $field.val()));
console.info("--> Last value of isValid = " + isValid);
isValid = isValid && (validy.is(validableClass, $field.val()) ? true : false);
console.info("--> Value of isValid is now = " + isValid);
break;
};
}
console.info("** Status of isValid: " + isValid + " **");
if (!isValid) {
console.info("--> Invalid field detected");
//vw.popoverError($field, "Error", errors[validableClass]);
break;
};
};
return isValid;
};
The problem with it is that even when the field value is valid and isValid == true, when it does the isValid == isValid && ... operation, isValid ends up being false.
How can it be possible for a true && true expression to throw false.
I know there must be some stupidity I can't see, but I can't seem to find it. Can anyone lend a hand on this one?
Thanks!
Update 1
Originally, the line:
isValid = isValid && (validy.is(validableClass, $field.val()) ? true : false);
was
isValid &= validy.is(validableClass, $field.val();
Update 2
At some point, apparently the test method is returning 1 or 0 instead of true or false. But I can't pinpoint the exact moment when it happens.
Update 3
So it turns out that I was misusing the &= operator as mentioned in the comments. But...
isValid = isValid && validy.is(validableClass, $field.val());
...returns false when isValid == true and validy.is returns true independently.
Update 4
Changed the validy.is definition according to answer by CaffGeek:
validy.is = function(what, str) {
return !!formats[what].test(str);
};
It had no effect, unfortunately.
| Try changing
validy.is = function(what, str) {
return formats[what].test(str);
};
to this to ensure it's a boolean result.
validy.is = function(what, str) {
return !!formats[what].test(str);
};
I haven't tested this, but you don't need all the loops with jQuery. It's set based. You can simplify your code along this manner.
formBuilder.validate = function() {
console.info("=== STARTING VALIDATE ===");
var isValid = true;
var allFields = $(".field", formBuilder.form).toArray();
var validable = ["email", "phone", "numeric", "url"];
var errors = {
"email": "Debés ingresar una dirección de e-mail válida (por ejemplo: [email protected]).",
"phone": "Debés ingresar un número de teléfono válido.",
"numeric": "Debés ingresar un número.",
"url": "Debés ingresar una dirección Web válida (por ejemplo: www.misitio.com.ar)."
};
var failedFields = $('EMPTYJQUERYSET');
$.each(validable, function(index, className) {
failedFields.add(
allFields.filter('.' + className).filter(function(index) {
return ! validy.is(validableClass, $(this).val());
});
);
});
isValid = !!(failedFields.length == 0);
console.info("** Status of isValid: " + isValid + " **");
if (!isValid) {
console.info("--> Invalid field detected");
//vw.popoverError($field, "Error", errors[validableClass]);
break;
};
return isValid;
};
| 0.777778 | Validy.is = function(what, str) return formats[what].test(str); |
Ensuring successful merges in Subversion | Subversion Re-education actually convinced me, but for now I'll stick to svn - mastering the use of a very popular tool can't be bad.
To date I've not used branching/merges in production code, now I decided to give it a try in a small team environment.
I'm afraid of suffering the same pain as the described in Spolsky's article. Is there a "right" way of working with branches in svn?
| Branching always begins with fear that merging will break things or leave unnoticed bugs for long.
However, it is the most essential element for a reasonably sized product or project. Here are the few distinct categories where branches are a must -
they are :
1. Branch post release
This is done to maintain post release patches. these patches are essential to support current versions in the market till next major releases are still not ready.
2. Branch per Task or component
Here a few independent groups are given the branch that they keep check-in while rest of the team (or other branches) doesn't have to accept any work till entire new functionality or project is completely finished and merged to trunk.
3. Branching for special customer support
Here a few branches are created to support only for a specific (set) of customers.
Branching and merging begins with some fear always, but in my experience, as people begin to put disciplined code, it becomes indispensable for any large development.
See URLS below for more details.
http://www.codinghorror.com/blog/2007/10/software-branching-and-parallel-universes.html
http://stackoverflow.com/questions/631900/branching-hell-where-is-the-risk-vs-productivity-tipping-point
| 0.888889 | Branching and merging begins with fear of breaking things or leaving unnoticed bugs for long . |
Can a wizard choose where to place their soul piece when creating a horcrux? | In the world of Harry Potter a wizard can remove a part of their soul and place it into another object through the act of homicide, thus creating a horcrux. Is the wizard able to direct their soul pieces such that they can choose what becomes a horcrux? Tied into that question, it seems possible that a wizard can kill someone and not create a horcrux (Peter Pettigrew killed Cedric Digory but no one seemed concerned that Peter made a horcrux), so how/why did Harry Potter wind up with a sliver of Voldemort's soul when it seems inconceivable that Voldemort's intention was to put one there?
| Yes, a witch or wizard creating a Horcrux can choose the object into which the Horcrux is concealed. Speaking specifically of Voldemort's Horcruxes, Harry and Dumbledore discuss vessels for Horcruxes:
"And they could be anything?" said Harry. "They could be old tin cans or, I dunno, empty potions bottles . . . ."
"You are thinking of Portkeys, Harry, which must be ordinary objects, easy to overlook. But would Lord Voldemort use tin cans or old potions bottles to guard his own precious soul?"
Half-Blood Prince - Page 504 - US Hardcover
What is a little murky is whether or not an ordinary object can be used to create a Horcrux, or if an item of significance (Slytherin's locket; Ravenclaw's diadem; Gryffindor's sword; Hufflepuff's cup; etc) is required. The above passage is referring specifically to Voldemort.
Simply committing a murder does not create a Horcrux. It is one step required. Reference Tom Riddle's conversation with Horace Slughorn while Riddle was still a student at Hogwarts:
"But how do you do it?"
"By an act of evil -- the supreme act of evil. By committing murder. Killing rips the soul apart. The wizard intent upon creating a Horcrux would use the damage to his advantage: He would encase the torn portion--"
"Encase? But how--?"
"There is a spell, do not ask me, I don't know!" said Slughorn . . .
Half-Blood Prince - Page 498 - US Hardcover
J.K. Rowling has not revealed the exact steps necessary in making a Horcrux; according to the HP Wiki, J.K. Rowling plans on releasing the exact spell and process in her Harry Potter Encyclopedia; the process is apparently very gruesome.
An accidental Horcrux can be created, such as in the case of Harry.
"[...]on the night Lord Voldemort tried to kill him, when Lily cast her own life between them as a shield, the Killing Curse rebounded upon Lord Voldemort, and a fragment of Voldemort's soul was blasted apart from the whole, and latched itself onto the only living soul left in that collapsing building. Part of Lord Voldemort lives inside Harry[...]"
Deathly Hallows - Page 686 - US Hardcover
"You were the seventh Horcrux, Harry, the Horcrux he never meant to make. He had rendered his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the attempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind. He left part of himself latched to you, the would-be victim who had survived."
Albus Dumbledore - Deathly Hallows - Page 709 - US Hardcover
So, technically, when Voldemort cast the Killing Curse, it rebounded against him, severing yet another part of his soul. That part of Voldemort's soul sought out a living host, the only available vessel being Harry; it attached itself to Harry. How Voldemort managed to create this Horcrux without the apparently necessary accompanying spell being incanted, I am unsure.
ETA: Regarding Horcruxes, JKR has this little tidbit up on Pottermore:
Professor Quirrell served as a temporary Horcrux when Lord Voldemort's soul occupied his body.
| 1 | How to create a Horcrux without an accompanying spell being incanted |
Subsets and Splits