Can I sell a handshake?

Question: Can I charge someone for a hand gesture such as a high five or a handshake? How would a receipt be written for such a thing? It seems like a silly question but I am genuinely curious and want to make sure my social experiment isn't subject to any sort of weird laws that I don't know about.
Comment: What makes you think that it might possibly be illegal?  How might a receipt be any different for any other receipt for a product or service?
Comment: Which jurisdiction?
Comment: Prostitution is geographically and temporally illegal - it's illegal in some places at some times and legal in others.
Comment: No clue, just wanted to make sure
Comment: I don't see how this would be any different from other trades that offer physical contact for money, like massage therapists or prostitutes.
Comment: prostitution is illegal
Answer: The way law works is that you don't need to find a law which says you can do something. Instead, there needs to be an absence of a law which says you cannot do that thing. In other words, you can do anything you want so long as there isn't a law which says you can't. It's unlikely that you will find a law in any jurisdiction which says you cannot charge for a handshake.
If you want the charge to be legally binding on the other party, then you need to ensure that the formalities of a valid contract are met. In particular, either each side needs to provide consideration (something of value) or the contract needs to be executed as a deed (england-and-wales).
The party who pays the charge is clearly providing consideration. What about the handshake? Is it something of value?
The rule is that consideration must be "sufficient" but does not need to be "adequate". That means that it must have some value (however small) but it doesn't need to be valuable enough to be a fair bargain for the parties. This was confirmed by the House of Lords in Chappell & Co. v Nestle Co. Ltd (1960) AC 97 (england-and-wales) which held that empty chocolate wrappers, which would be thrown away upon receipt, were sufficient consideration. A more common example of low-value but sufficient consideration is a "peppercorn" which is often used as token consideration where (in practical terms) a party is not offering anything of substance.
Note that "value" doesn't need to mean something that benefits the recipient. It can also be something which detriments the person who provides it. The courts have held that a promise to do something you were not otherwise legally required to do is sufficient consideration. For example, in Hamer v Sidway (1891) 27 NE 256 (new-york-state), the court held that a promise to quit smoking was sufficient consideration.
It doesn't matter whether the recipient values the consideration or not. In Chappell (see above) the court held:

It is said that when received the wrappers are of no value to
Nestle's. This I would have thought irrelevant. A contracting party
can stipulate for what consideration he chooses. A peppercorn does not
cease to be good consideration if it is established that the promisee
does not like pepper and will throw away the corn.

A handshake is almost certainly sufficient consideration because it involves doing something that you were under no legal obligation to do before you agreed the contract.
How you write a receipt is a matter of personal choice and therefore off-topic.
Comment: "In particular, each side needs to provide consideration" - that is not universally true.  You can form an enforceable contract in Scots law without consideration on at least one side.
Comment: @MartinBonnersupportsMonica Thanks, I added a jurisdiction tag. You can also avoid the need for consideration in E&W by executing the contract as a deed, so I edited that in as well.
Answer:
Can I charge someone for a hand gesture such as a high five or a handshake?

Only if you and the counterparty agree beforehand on the topic of compensation. That is because the formation of a contract requires that the parties commit to the terms and conditions knowingly and willfully. Since typically nobody charges for a hand gesture, you need something to supersede the common presumption that also your handshake or high five is for free.
Obviating the agreement about compensation is likely to render a controversy undecidable. For instance, once the handshake is completed and you tell the counterparty to pay you $5, the counterparty could say "Quite the contrary, you owe me $10 for the handshake with me".

Can I sell a handshake?


Django - Adding a 2nd form to a page dynamically

Question: I'm looking for guidance on creating a dynamic form in Django that changes depending on which participants are in a meeting.
The background is as follows: The app is used to track meeting scores across several teams, each with 4-8 members. Over the course of a few days a team may have 6 meetings. For each meeting the Team will elect 1 or 2 members to be meeting Participants. Each meeting requires the team to put forward members such that over the course of the training all team members have participated in one or more meetings. For each meeting all other team members are "Observers".
The challenge I'm facing is how to dynamically insert a form or form fields for each of the Observers given that the number of observers may be anything from none to 6. The idea is to allow Observers to "rate" the meeting and record this result in the Observer model.
The ScoreCreate view correctly sets the 1st participant and populates the "Other Participant" dropdown with all other team members.
HTMX in the template passes the 1st and if selected "other participant" to the observers function which is then able to sort out who the observers should be.
What I'm not able to figure out is how to generate and insert a form that is pre-populated with each of the Observers and allows for input of a score( Name of Observer, field: rating), given the number of Observers  will vary depending on the number of team members and whether or not there are two participants in the meeting.
Thoughts on how I might approach this are welcome.
MODELS:
from .choices import SCORE_CHOICES, RATING_CHOICES

class Meeting(models.Model)
    date = models.DateTimeField(auto_now=True)

class Team(models.Model):
    # up to 8 members per team
    name = model.CharField(max_length=25)

class Participant(models.Model):
    name = model.CharField(max_length=25)
    team = model.ForeignKey(Team, on_delete.models.CASCADE)

class Score(models.Model):
# primary is required, secondary is not required
    meeting = models.ForeignKey('Meeting', on_delete.models.CASCADE)
    primary_participant = models.ForeignKey('Participant', on_delete.models.CASCADE)
    secondary_participant = models.ForeignKey('Participant', related_name='secondary_participant', on_delete.model.CASCADE, blank=True, null=True)
    score = models.CharField(max_length=25, choices = SCORE_CHOICES)

class Observer(models.Model):
    score = models.ForeignKey(Score, on_delete.models.CASCADE)
    observer = models.ForeignKey(Participant, on_delete.models.CASCADE)
    rating = models.CharField(max_length=1, choices=RATING_CHOICES)

VIEWS:
class ScoreCreate(LoginRequiredMixin, CreateView):
    model = Score
    form_class = ScoreCreateForm
    template_name = 'score_create.html'

    def get_initial(self):
        participants = Participant.objects.filter(slug=self.kwargs['slug'])
        participant_id = self.kwargs['pk']
        other_participants = participants.filter(~Q(pk=self.kwargs['pk'])

def observers(request):
    participant = request.GET.get('participant')
    other_participant = request.GET.get('other_participant')
    team = request.GET.get('team')

    if other_participant:
        observers = Participant.objects.filter(~Q(id=participant) & ~Q(id=other_participant) & Q(team=team))

    else:
        observers = Participant.objects.filter(~Q(id=participant) & Q(team=team) & Q(role='PARTICIPANT'))

    return render(request, 'trial/partials/all_observers.html', context={'observers': observers})

TEMPLATE: score.html
<form method="POST" name="score_participants">

Meeting Details

        <input class="btn btn-md btn-warning g-mr-10 g-mb-15 g-rounded-50" onclick="location.href='#'" type="button"
               value="Cancel">
        <button class="btn btn-md u-btn-primary g-mr-0 g-mb-15 g-rounded-50" type="submit">Submit</button>

Participant:

        {{form.participant|as_crispy_field}}

{{participant}}

Meeting Number:

{{form.meeting_number|as_crispy_field}}

Name of other meeting participant:

            {{form.other_participant|as_crispy_field}}

...

TEMPLATE: observer.html
{% block content %}
    {% for observer in observers %}

{{observer}}

RATING (RADIO BUTTONS)

{% endfor %}
{% endblock %}

Answer: The idea is to use the view that handles that data coming from that page you've shown going to the next page that shows the forms. So if you are just trying to show the forms on the next page you can handle the logic within your view and say if there are 4 observers then you will want to have a for loop that creates a form for each of them and appends them to a list. Then in HTMX you have for each in that list, print that form out, and you can use id's on each html object in forms.py and manage them in css.
If you are looking to save this model for later use. You essentially want to do the same thing but instead of passing those values along URL(managing the parameters in a view) you can just use them straight from the database. In fact, this would simply work in either situation with that small caveat that using more database calls will slow the site down.


Get page count from multiple word documents by selecting them in a folder?

Question: Is there any way to get the total page count after selecting multiple word documents in a folder?
Answer: Hopefully this will enlighten you a little further than the rather brief answer provided by another user.
Simple answer: no.
Detailed answer: A MS Word document only has "pages" once it is generated (i.e. opened).  The main reason for this is to do with the page size.  For example: if you have three documents under scrutiny, formatted to sizes A5, A4 & A3 respectively, then to count the number of pages collectively would be practically impossible to display in a simple, logical / coherent format.
The only potential way around this is to write some custom software which opens each desired document one after the other, logs the page sizes of each respective document, and then counts the number of pages within each page size category and logs it before closing each document and proceeding to the next.
Hopefully this will be of help to you.
Many thanks.
UPDATE
Adam's response (Nov 22 '12 at 15:08) is also somewhat correct and I feel that I should elaborate on my answer; Word does store a page count for some document types, but not all, as Adam quite rightly states.  I chose to treat this factor as an 'all or nothing' property; either it stores a page count for all document types, or none at all.  Hence why if you extract the page count property from each document, it may result in incorrect / inaccurate data due to particular file types not being read.  This is why my suggestion of custom software would be the best overall option as the data can become stale or inaccurate and not always reflect the facts.  This is why it is better to consider Word as not storing any page number properties rather than just some.
I hope this also helps?
Comment: Thanks for the info. I don't suppose you have a link to any such custom software?
Comment: I'm afraid not; however, the logic behind the software should not be too difficult to implement.  The software is required to look in a directory, locate all `.doc` / `.docx` files and then from there, open the document, log the number of pages (if you wish to include page size here, it will require more detailed analysis of the document), add the total to a running count for each page size, then close the document and move onto the next until all have been analysed.
Comment: @SnookerFan please don't harass users to accept an answer, and please don't abuse flags to ask moderators to do so on your behalf. The choice to select an answer is entirely the user's; if they don't want to select an answer, they don't have to. I'm sure it's no coincidence that your sudden and intense interest in this user marking their solution is not coincidental. Don't worry about 15 points - just acknowledge that sometimes people don't mark an accepted answer, and your time is better spent writing new answers than begging for a checkmark on an answer from a year ago.
Comment: Not coincidental in relation to what, exactly?
Comment: Has this worked?
Answer: SnookerFan's detailed answer is a little off, Microsoft Word does store the number of pages in a document as a document property when the document is saved. This value is what shows up in the explorer when you view the properties of the file and it should be correct 99% of the time although I'm sure there are some situations where the value of this property could become stale and incorrect.
Therefore you could create a simple application and even make it into a shell plugin to query this property and add the values together.
One thing to keep in mind is this property is displayed for DOC and DOCX documents but isn't for RTF format even though it is written to the RTF document (represented by the {\nofpagesX} keyword).
Answer: This same question came up at work and Google brought me here.  There isn't a way to select the documents in Windows Explorer and obtain a page count, but there are other methods that might provide a good enough estimate.
I'm thinking of trying out this PowerShell script:
Hey, Scripting Guy! How Do I Count the Number of Pages in a Group of Office Word Documents?
For an end user I would set up a shortcut and maybe prompt for the folder location.


Verification of certificate trustworthiness (e.g. in JWS and Client Certificate)

Question: I am comparing implementation complexity of JWS and Client Certificate and troubleshooting Client Certificate at the same time.
I understand that both methods require to prove that the certificate (x5c in JWS or the actual Client Certificate) is trustworthy (as per https://www.rfc-editor.org/rfc/rfc7515#section-10.3). How should this validation process be achieved? Where do I get the root certificate from if I wanted to extract public key from the root?
For JWS I intended to hold a copy of a certificate (or at least its public key) in application memory. Before I validate the signature wih x5c certificate, I would validate the certificate itself. Is this correct approach?
For Client Certificates - the plot thickens, especially in my scenario (*) and it is not transparent to me since it is handled by HTTP server, not by my application, therefore I believe it can differ between server implementations, unless there is some standard? RFC5280 Section 6 on Path Validation cover this? My HTTP server expects me to install a "client certificate" (yes, on the server) and I am curious what the validation procedure would be (what is compared - just the keys or entire certificate, maybe just the root certificate?) and why it cannot use the same certificate that is already used for authenticating the server/domain (since they share the root certificate). In reality, each client has been issued their own certificate (with a shared root), so which client certificate am I expected to provide? Should I provide 1K client certificates for 1K clients?

(*) I am not a CA that self-signed client certificates, but they have issued a server certificate for my subdomain that is intended to handle the traffic. This means that I do not have direct access to private key and the root certificate.
Comment: Partially solved: I have access to CA's root certificate and I am able to validate the certificate in JWS (openssl verify) as well set set is as "client certificate" on the server for mTLS. Still, the correct approach for JWS remains a mystery to me.
Answer: By 'Client Certificate' do you mean in SSL/TLS and (thus) HTTPS? If so, 8446 (for TLS1.3) references 5280 for cert validation, although earlier versions were not explicit, and libraries generally implement this (or at least its predecessors; in OpenSSL for example the cert validation code didn't change much from about 2000 to about 2015). Typically a server wants you to configure one or more trust anchor(s) for the client certificate(s); while (often) this can be (an) individual cert(s), it can also be a cert for the/each CA that issued the child cert(s) (or usually its root) -- as long as you consider that CA reliable, i.e. you trust it adequately ensures the certs it issues (and does not revoke) are legitimate. Often this will even say something like 'tls-client-ca'. But a definite answer depends on the specific server: apache? nginx? haproxy? tomcat? Jboss/Wildfly? Liberty? other (custom) Java? Or C or C++? Or rust, or go, or whatever comes next? Or python, or nodejs, or perl, or ruby?
JWS also specifies 5280, in 7515 4.1.6, but implementations can vary a lot.

Added for comment:
(1) Okay, this is for Azure Gateway. Their documentation is confusing, inconsistent, and bloated, as typical for Microsoft. They use "client certificate", "client CA certificate", and "client CA certificate chain" in various places as if they were the same which they certainly are not. In https://docs.microsoft.com/en-us/azure/application-gateway/mutual-authentication-portal the "Before you begin" links back to its parent page https://docs.microsoft.com/en-us/azure/application-gateway/mutual-authentication-overview#certificates-supported-for-mutual-authentication which actually describes server certs not client, so is useless. However "Configure mutual authentication" step 5 (and the parent page also) says you should use https://docs.microsoft.com/en-us/azure/application-gateway/mutual-authentication-certificate-management
which describes a way (only for Windows) to get the intermediate and root CA certs for the client cert, not including the client cert itself. This is consistent with the option described (at length) on related pages for them to check/require that a client cert is directly issued by a configured CA, e.g. "Verify client certificate issuer's DN" on the portal config page; that direct issuer will usually be an intermediate CA thus for this option to work they need the intermediate not just the root which would be enough for normal validation. (It's not clear if they actually need intermediates other than the first/lowest when multiple intermediates are used; the example doesn't show that case, and they don't really explain or precisely specify. They also don't show the direct-root case, which is rare, although I'd expect/hope submitting only the root works.) Although they give you the procedure only for Windows, the format they show is a sequence-of-PEM, a common standard you can easily create with other systems and programs.
(2) "the origin of a root public key" -- well, the origin is the root CA. But what matters is how you get it onto your system(s) in a way that is trustworthy, so that you are certain it is not tampered or faked.
For public CAs this is normally handled by the root-CA programs of various software suppliers: Microsoft (Windows) and Apple (MacOS and iOS) each has a program to provide (and update) trusted roots as part of their systems (which are secured overall to prevent lots of attacks not just SSL/TLS certs); Mozilla has a program created for and used by Firefox and Thunderbird, which many Linux distros and some other software (e.g. curl) also use; Oracle-formerly-Sun has one used by their builds of Java while other (OpenJDK, IBM, ?) builds can use something different depending on the builder. I don't know what dot-net does on non-Windows platforms. There are undoubtedly others that are less known.
For other CAs it may vary. If you work in a business or organization that has an internal CA they will usually have a process to get you the correct root; for domain-managed Windows systems they can do this automatically so you may not even be aware of it. If you 'join' http://cacert.org (not https!) you are expected to handle these details yourself.
(3) The verify logic described in the OpenSSL man page is basically standard, although it doesn't automatically fetch CRLs or use OCSP (or caIssuer) -- which are not strictly required but very useful and some other software does. The truststore format OpenSSL uses (a file and/or a directory using subject hashes in the names) is an implementation detail and typically (though not necessarily) the same for https servers (and others) that use OpenSSL, but often different on other software or middleware. E.g. Windows used locally has its own 'machine' store or may use/share the domain controller; since Azure is cloud we don't really know what it does internally, only what the input (or output) is like.
Comment: 1. Actually, it is a brand new feature in Azure Application Gateway for full mTLS (https://docs.microsoft.com/en-us/azure/application-gateway/mutual-authentication-overview / https://docs.microsoft.com/en-us/azure/application-gateway/mutual-authentication-portal )

2. "[JWS] implementations can vary a lot." - well, that explains a lot :) Is my approach correct? Question on the origin of a root cert public key still remains.

3. So I should expect that https://www.openssl.org/docs/man1.0.2/man1/openssl-verify.html characterizes a typical client cert validation on my http server?


How can I block ping requests with IPTables?

Question: and stealth specific ports?
Answer: To deny responses to ping requests..Add the following iptable rule
iptables -A OUTPUT -p icmp -o eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp -i eth0 -j DROP

Comment: something is wrong with the rules or i just don't have dependencies, i changed the eth0 to wlan0 as i am on my laptop right now, and received the error "sudo iptables -A INPUT -p icmp –icmp-type destination-unreachable -s 0/0 -i wlan0 -j ACCEPT
Bad argument `–icmp-type'" and "sudo iptables -A INPUT -p icmp -i wlan0-j DROP
Bad argument `DROP'"
Comment: @david25 see my updated answer.
Answer: I believe iptables -I INPUT -p icmp --icmp-type 8 -j DROP should do the trick.
For IPv6 you would need something like ip6tables -I INPUT -p icmpv6 --icmp-type 8 -j DROP.
Answer: Simplest method of disabling ping response is to add an entry in /etc/sysctl.conf file. If the Iptables flushes or stop server will start responding to ping responses again. I suggest the following entry in your /etc/sysctl.conf file
net.ipv4.icmp_echo_ignore_all = 1

this will tell kernel to not respond any ping response, after this run sysctl -p on shell to implement the changes without reboot.
For more info please refer: http://www.trickylinux.net/disable-ping-response-linux/
Comment: This is probably the best way I have found in the past. It has the plus side that its persistent.
Answer: Drop ICMP echo requests ("Ping"):
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

What do you mean by stealth? You could just DROP all incoming packets. Google provided this:
iptables -A INPUT -p tcp -m stealth -j REJECT

But on (my) Ubuntu box, iptables does not know of a "stealth" match. As it seems, you can do lots of interesting stuff with xtables:
aptitude show xtables-addons-common


What is the best way to set an environment variable in .bashrc?

Question: When setting up a variable in .bashrc, should I use this?
export VAR=value

Or would this be enough?
VAR=value

What is exactly the difference (if there is one)?
Answer: The best way
export VAR=value

The difference
Doing
VAR=value

only sets the variable for the duration of the script (.bashrc in this case). Child processes (if any) of the script won't have VAR defined, and once the script exits VAR is gone.
export VAR=value

explicitly adds VAR to the list of variables that are passed to child processes. Want to try it? Open a shell, do
PS1="foo > "
bash --norc

The new shell gets the default prompt. If instead you do something like
export PS1="foo > "
bash --norc

the new shell gets the prompt you just set.
Update: as Ian Kelling notes below variables set in .bashrc persist in the shell that sourced .bashrc. More generally whenever the shell sources a script (using the source scriptname command) variables set in the script persist for the life of the shell.
Comment: "only sets the variable for the duration of the script (.bashrc in this case)"

That is false/misleading. Variables set in this way persist into the interactive shell that read .bashrc.
Comment: `PS1` is a bad example of a variable to be exported as an environment variable. It's only meaningful to child processes that are shells and it's interpreted differently by different shells (e.g., bash and dash). Best practice is to simply set it as a regular shell variable in the `.bashrc`. Better examples of environment variables include `HOME`, `PATH`, `EDITOR`, etc.
Answer: Both seem to work just fine, but using export will ensure the variable is available to subshells and other programs. To test this out try this.
Add these two lines to your .bashrc file
TESTVAR="no export"
export MYTESTVAR="with export"

Then open a new shell.
Running echo $TESTVAR and echo $MYTESTVAR will show the contents of each variable. Now inside that same shell remove those two lines from your .bashrc file and run bash to start a subshell.
Running echo $TESTVAR will have an empty output, but running echo $MYTESTVAR will display "with export"


Toolboxes are huge in inkscape

Question: Is there a way to resize docked toolboxes in inkscape? I dock toolboxes towards the right of my screen (see image below) but it is taking up too much space compared to my drawing layer. Dragging it by the three dots I can only completely hide it, not resize it. I use inkscape version 1.1.1
Comment: Try with the new version (inkscape 1.2)
Comment: Looks like you are using an old version of Inkscape. This was an issue when you had certain larger dialogs open - especially the document set up. The only real way to deal with it was to close the offending dialog.  I suggest you update to the most recent Inkscape 1.2. They appear to have fixed this issue now.
Answer: Close page setup tab, it makes all other tabs wider.
In 1.2 it was fixed, and you can resize tab to its minimum width, though.
Answer: The minimal width of the toolbox is dependent on its current displayed content (dialog), e.g., the Transform dialog may be narrower than the Document properties one.
You may always hide the dock by clicking at the center of its left side:

(To unhide it, click at the center of the narrow bar which remained after hiding it).
Comment: It is not the case for 1.1

Toolboxes are huge in inkscape


Changing values in Web.config with a Batch file or in .NET code

Question: I have a web.config file on my computer.
There are alot of things i need to change and add in the file.
(I am actually working with my SharePoint web.config file)
Can i do this with a Batch file, if so how would i do it.
Or how would i do it using VB.NET or C# code?
Any ideas guys?
Edit: i need to create a program to alter a web.config of lets say i web.config laying on my deskop and not the actual web.config of my project
Regards
Etienne
Answer: You can modify it from C# code, for example:
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

if (appSettingsSection != null)
{
  appSettingsSection.Settings["foo"].Value = "bar";
  config.Save();
}

where foo is the key and bar the value of the key to set, obviously. To remove a value, use Settings.Remove(key);
See the msdn documentation for more information about the OpenWebConfiguration method and more.
Comment: thanks, but i need to create a program to alter a web.config of lets say i web.config laying on my deskop and not the actual web.config of my project....how would i do this?
Answer: The context in which you want to change the file really affects how you should do it.  If you're looking at performing changes relatively frequently, but in an administrative domain, then some sort of command-line tool makes sense, and in this case I'd agree with JaredPar that PowerShell would be a valuable tool.
If, on the other hand, you find yourself in a situation where you need to modify the web.config in a more programmatic environment (e.g., as part of a setup program), then using programmatic technologies might make more sense.  I recently had to do such a thing and Linq to Xml proved very convenient.
For example, to open a document "C:\foo\bar.xml" you could do something like (untested, no convenient build environment at the moment):
XDocument config = XDocument.Load(@"C:\foo\bar.xml");

You could then carry on in the usual fashion with the API.  Note that this may be overkill if you're doing an administrative task as opposed to a programmatic task-- there are big, long-term advantages to learning a tool like PowerShell.
Finally, if you're modifying the web.config from within the program that the web.config is being used for, and you aren't doing anything too fancy or dynamic, then using the built-in Settings or ConfigurationManager may be the way to go.
Comment: thanks for the reply....i need to create a program to alter a web.config of lets say a web.config laying on my deskop and not the actual web.config of my project
Comment: Powershell and linq would still be perfectly capable of that.
Comment: Hi, i had a look now. Must i open my web.config with LINQ? If so, can you give me an example of what my code must look like to open a web.config laying on say C:\MyFile\web.config ...........
Answer: Your best bet might to change it using a MSBuild Script and the MsBuild Community Tasks XML Mass update task
Answer: I would personally recommend using PowerShell.  This is the next gen command line from Microsoft and it's sits right on top of .Net.  It was built to do items like batch edits across large sets of files.
Answer: For a change in web.config in a SharePoint environment you have classes specially developed for this task. You only have to search for SPWebConfigModification class.
Answer: To load an arbitrary .NET config file
string configLocation = @"C:\myconfigFile.Config";
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();

configFileName = configLocation;
configFileMap.ExeConfigFilename = configFileName;

Configuration configuration= ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

Then use Razzie's code to alter the actual config setting
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
    appSettingsSection.Settings["foo"].Value = "bar";
    configuration.Save();
}

Comment: Hi, thanks for the reply. Is the configFileName the name of my config file ----- meaning "Web.Config"?
Answer: This is what i needed to do.......thanks for all the help!!!
// Read in Xml-file
        XmlDocument doc = new XmlDocument();
        doc.Load("C:/Web.config");

        //SaveControl tag..........................................................
        XmlNode n = doc.SelectSingleNode("/configuration/SharePoint/SafeControls");

        XmlElement elemWeb = doc.CreateElement("SafeControl");
        elemWeb.SetAttribute("Assembly", "SamrasWebOption4");
        elemWeb.SetAttribute("Namespace", "SamrasWebOption4");
        elemWeb.SetAttribute("TypeName", "*");
        elemWeb.SetAttribute("Safe", "True");

        XmlElement elemSmartPart = doc.CreateElement("SafeControl");
        elemSmartPart.SetAttribute("Assembly", "Machine_Totals");
        elemSmartPart.SetAttribute("Namespace", "Machine_Totals");
        elemSmartPart.SetAttribute("TypeName", "*");
        elemSmartPart.SetAttribute("Safe", "True");

        //Appending the Nodes......................................................
        n.AppendChild(elemWeb);
        n.AppendChild(elemSmartPart);

        //Saving the document......................................................
        doc.Save("C:/Web.config");


Creating symbolic links

Question: How does one create a symbolic link in vifm? The documentation and help file mention no word of it.
Answer: I have this in my .vifm/vifmrc:
COMMAND=ln=!ln -s %d/%f %D

this way when you call :ln, a link of the selected file is made in the other directory (if you are in split view).  it even works with multiple files selected with visual (v) or tag (t).
Answer: For vifm version 0.8 you can add this to .vifm/vifmrc:
command ln ln -s %f:p %D

Then you can type :ln hit enter and symbolic link(s) of the file or directory under cursor (or selected files or directories) will be created in the directory of the other window.
Answer: I don't think there is a specific command, but you can execute any command using:
:! <command>

such as:
:! ln -s /media/usb usb

Creating symbolic links


How to get price data for a redeem without using chainlink

Question: Trying to make a ecosystem where you have two tokens (Token X, Token Y) Token X can be minted for $1 worth of Token Y burned. And Token X can be redeemed for $1 worth of Token Y. How would I do this in solidity without using a data feed like chainlink? I'm a horrible coder so advice would be appreciated lol.
Answer: If you plan to take the token outside your solidity project's world, there is no way of getting the price of the token without using an oracle service.
Comment: What if I used a twap over like a minute
Comment: I am not sure whether that can be very successful. Go through the failures of all algorithmic stable coins in existence to understand what not to do. I am no expert to comment further on it. Just know that oracle would give you the accurate value that you need when dealing with financial stuff.


Filing tax return and estimated payment without ITIN

Question: I married to an international person in 2022 who doesn't have SSN or ITIN. My spouse will be coming to the US in late April and I am preparing our taxes with married filing jointly. Since it will be late to file the paper tax return for us, I want to file extension and make estimated extension payment (federal tax refund expected so late filing is okay, but I owe state tax). My question is since the state estimated tax payment form requires ITIN/SSN of both tax filers, how can I make payment without spouse's ITIN? Also, when filing federal and state paper tax returns (Form 1040), what should I put on the SSN/ITIN line for spouse?
Answer: They can make estimated tax payments before applying for an ITIN, by writing "ITIN TO BE REQUESTED" in the space for SSN/ITIN. See W-7 instructions, in section "ITIN not needed for Forms 4868, 1040-ES, or 1040-ES (NR)":

ITIN not needed for Forms 4868, 1040-ES, or 1040-ES (NR).
If you're filing an application for an extension of time to file using
Form 4868, or making an estimated tax payment using Form 1040-ES or
Form 1040-ES (NR), don't file Form W-7 with those forms. Enter "ITIN
TO BE REQUESTED" wherever your SSN or ITIN is requested. An ITIN will
be issued only after you file a tax return and meet all other
requirements.

This addresses federal estimated tax payments but not state estimated tax payments, but the same probably applies to state too.
I am not sure what you mean by "Since it will be late to file the paper tax return for us, I want to make estimated state tax payment". The last quarter estimated tax payment for 2022 was due on January 15. Do you mean you will make a payment with your tax return? Or that you will be making an extension payment with a request for a tax deadline extension?
Another option is to make the estimated/extension tax payment with only your name and SSN (just like you would if you originally planned to file as Married Filing Separately). When you file taxes as Married Filing Jointly, you will be able to count the sum of payments made under either of your names.
Comment: ..."by writing "ITIN TO BE REQUESTED" in the space for SSN/ITIN" Does it apply to Federal and State From 1040 as well?
Comment: @ewr3243: Well, for federal tax return, you would file the 1040 and W-7 together to request an ITIN together with the tax return. (You generally can only apply for an ITIN at the time you are filing a tax return.) I don't know about state.


When publication A cites B, should I cite A or B?

Question: Let's say publication A has a nice overview of a topic and cites B and C sources to back up a few important points. Should I cite A, since it provided me with B and C? Or do I have a responsibility to read these citations? What if B is a 40-page, esoteric paper that I am unlikely to read. This seems like a rabbit hole, and I'm not sure how far down my due diligence should take me.
Comment: You would need to read/skim it to make sure A (was correct! and actually cited B in the correct context).
Comment: It really depends on what your due diligence is, to be honest. So it can really vary depending on the paper, discipline, etc. If you're speaking about something really essential to your thesis, make sure you've got a seminal work cited (and you really should read it), but otherwise it's up to you, however deep you need to go to find the basis of the model/concept/etc.
Comment: If you have not read the original source, you should cite it as (Original 1990, as discussed in Secondary 2005), or something along those lines. It is preferable to read the original source, but whether it's necessary depends on the level you're writing at. If you're writing for publication, you should read the original unless it is somehow impossible to find or if it's technical in a way that would require developing an entire new skill to understand (ex. proofs in math/logic). If you are writing a course paper, the bar is lower—ex. obscure notation, esotericness, even a simple lack of time.
Answer: Whenever possible, you should try and cite the original source to make sure proper credit is attributed, especially if the original work is not well known enough to constitute "textbook material". For example, you can probably skip citing Einstein's original paper on special relativity and cite a newer textbook instead, where current standard notation and more context to the theory is provided.
Some times citing the derivative work can add to the discussion in the way of a simplified treatment over the original, further clarifications, notes on implications, and so on. Keep in mind that original work is often obscure, may not yet incorporate terminology or concepts that became mainstream after it was published, etc. In these cases I would recommend citing both the original and the derivative work. In my own papers I have used sentences such as "... our treatment is based on the theory presented by Doe and collaborators in their seminal paper [1], later reviewed more pedagogically by Smith [2]." Some journal editors will ask you to remove citations if they think they are redundant. This usually applies to obvious cases such as "... according to literature sources [1-25]..", but I guess an occasional picky editor might ask you to remove some of the references even if you're using them reasonably. In that case you need to judge by yourself if its worth insisting on keeping all the citations.
To summarize, when it doubt, I think it's best to err on the side of inclusion and make sure 1) that due credit is given to all the authors that deserve it and 2) that previous work you rely on for your study can be traced back following the items provided in the list of references.


VBA Text to columns FieldInfo

Question: FieldInfo:=Array(Array(0, 5), Array(8, 1))

I am trying to use text to columns fixed width.
For this, I have recorded a macro.
I can understand some of the code since I am new to VBA.
However, The above code is not clear.
Can someone explain what this code does?
Answer: using the source from @Vityata's answer, it means that you made two columns with the two arrays inside the outer array representing the two resulting columns:
Array(0, 5) the 1st column starts at character #0 (the first char) and the type is YMD date (type 5)
Array(8, 1) the 2nd column starts at character #8 (the ninth char = the first column is 8 char wide) The second column's type is General (type 1)
Answer: FieldInfo:

An array containing parse information for the individual columns of data. The interpretation depends on the value of DataType. When the data is delimited, this argument is an array of two-element arrays, with each two-element array specifying the conversion options for a particular column. The first element is the column number (1-based), and the second element is one of the xlColumnDataTypeconstants specifying how the column is parsed.

The example:
Array(Array(3, 9), Array(1, 2))

If the source data has fixed-width columns, the first element of each two-element array specifies the starting character position in the column (as an integer; 0 (zero) is the first character). The second element of the two-element array specifies the parse option for the column as a number from 1 through 9, as listed above.

Source:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-texttocolumns-method-excel

VBA Text to columns FieldInfo


Are all Nexus 5 phones sold unlocked?

Question: Are all Nexus 5 phones sold unlocked (i.e., not tied to a specific carrier)? If I buy a Nexus 5 from a store in Germany will I be able to use it in another country (Brazil)?
Answer: Yes, at this point. But, there's a talk about Sprint-locked Nexus 5.
Note: If you intend to use 4G LTE, then you need to check LTE market-compatibility, too. Other than that, you're good to use the phone in both countries.
Answer: Yes, currently. However this could change, the US carriers sometimes sell locked phones.
There is currently only one Nexus 5 variant, so you don't have to worry about LTE compatibility issues.

Are all Nexus 5 phones sold unlocked?


Keep cat contained in a pet play fence. What to use for cover to not escape?

Question: My cat had surgery on the back foot with a split on for 6 weeks. Cat in a wired crate with an opening to a pet play fenced area without a cover. What do I use as a cover to keep the cat from climbing out?
Comment: do you mean splint? Also, how big is the play area and what is it made out of. A picture would be helpful
Comment: Are you restraining the cat because the vet said to limit his movement, or some other reason?
Comment: How big is the fenced area and what type of fence is it (i.e. can it support any weight on top)?
Answer: An easy way would be to cover the top of the enclosure with a thin blanket and clip it into place using something like binder clips. However, with this solution you run into the risk of the cat getting its nails caught in the blanket.
Comment: I am now using a wooden board to cover the wired pet playpen. Thank-you for your response


For a non-resident, Is it worth investing in a 401k?

Question: I'm planning to stay in the U.S. for 3 to 5 years. My company offers a 4% match for 401k contributions. Is it worth investing in a 401k plan with all the fees and penalties? Or is there a better way to save?
Comment: Have a look at: https://www.wellsfargo.com/investing/retirement/tools/401k-early-withdrawal-calculator/  That suggests that the total you must pay is 20% + 10% penalty = 30%... on the TOTAL withdrawal (your 4% plus your employers 4%).  I can't see a real negative.
Comment: So, if you put in 4% of your salary, the company matches with another 4%.  I gather the fees and penalties are not that bad (50%). It seems like free money for a little extra hassle (if you intend to withdraw it in 3 to 5 years), though it will depend on your tax rate...
Comment: also make sure you stay around long enough to be fully vested.
Comment: Let's assume that tax bracket is 20%
Comment: @balki 20% now, 0% when you're back to your home country and 401k withdrawals is your only US-sourced income. Better pay 10% then than 20% now, no?
Answer: You should fund the 401(k) and get the 4% matching because it's free money.
When you leave the US, patience is a virtue to get the money penalty-free:

Rollover to an IRA.
Take "Substantially equal periodic payments" for 5 years or until age 59 1/2, whichever is longer, to avoid the 10% penalty. A long payout time for someone starting out, but penalty-free.

Or you can take the 10% penalty and take out the money all at once. You'll still owe income tax in either case, something to keep in mind if an early withdrawal would put you into a higher tax bracket. Also see this article: Can Foreigners Withdraw 401(k) Funds Early?
Another thing to keep in mind is that you never know what might happen -- you could fall in love with the US (or someone in the US, [smiley face]), apply for residency, decide to stay a long time, and that 401(k) with the 4% matching might turn out to have been a very nice thing when you retire.
Comment: Where did the 5 years came from?


How fast can we measure using IR sensors

Question: Supposing I have an repeatedly object passing through IR sensors and I am looking at the output waveform. What is the maximum frequency the output waveform can have?
I think this maybe related to the frequency of IR rays used for detection but I am unable to come up with a concrete logic as to why it may depend on that.
PS: ignore other limitations such as the speed of the object to give rise to such high frequency and measuring instrument limitations.
Comment: What does the datasheet for your sensor say?
Comment: Photodiodes have a fast response time on the order of nanoseconds.
Answer: From a fundamental point of view there is practically no speed limit for IR detection (i.e., convert light intensity to an electrical signal). The frequency of the light is so high (in the 100 THz range) that there is practically no limit from that, given typical light modulation frequencies that can be electrically handled.
The fastest photodetectors for the IR that I know of, have cutoff frequencies in the 100 GHz range. This corresponds to rise times in the order of picoseconds.
Well this is an extreme example. Practically you have to take into account other constraints, e.g., the size of the detector (smaller is faster) which has an impact on the field of view with optics applied, the cutoff wavelength (different detector materials have different "speeds"), the detector noise level (there are detector types that are very fast but not low noise), the desired amplification gain (the gain bandwidth product is usually somehow limited) or, the detector price.
Often the amplifier imposes the bandwidth limitation, and for the high speeds, an integrated module (i.e. detector and amplifier) is required.
Answer: In addition to the other answer, the practical limitations include current levels, diode junction capacitance and load resistance as the breakpoint. Thus some have a rise time >>10x decay time.
A typical 5mm PD like LTR-323DB has a junction capacitance of 50pF and useable up to 3MHz.
By converting the PD current to voltage the trans impedance amplifier, (TIA) which is an OpAmp Vin-/Rf and making Rf low (xxx Ohms) you can cascade more gain to get a more useable voltage to detect.
If you have a narrow optical beam restricted by a PD aperture of 5mm and a recessed PD and narrow emitter Beamwidth of <10 deg. , it is possible to define a small path in between , you can now compute speed.  But since emitter power is the biggest variable you need AGC. This poses a problem with detection  but is easily solved by having 2 equal emitters , pulsed alternately , one blocked and the other not so that AGC always has a stable input to compare the dropout .  Then you need a simple sync pattern to discern 1 source from the other such as time duration.
Now you "can" detect the object relative transmission loss not only in short pulses ~1us but at high velocity in a very small aperture such as 1mm in the path between using a recessed 5mm 10 deg PD and detecting a 50% drop in transmission loss.  1mm/us is 1km/s which is pretty fast assuming high SNR with daylight blocking lens on PD.
Anecdotal
Now that does seem too fast to me but I have only done this with  1m path and detected a 1mm wire passing fast across the middle using 100us pulses to verify the optical design. It worked. With multiple detectors I detected direction.
Answer: Here are some facts about silicon.
The thermal timeconstant of a cubic meter of silicon is 11,400 seconds.
The thermal timeconstant of a cubic centimeter of silicon is 100*100 faster, or
11,400 / 10,000 = 1.14 seconds
The thermal timeconstant of a cubic millimeter of silicon is yet 10*10 faster, or 1.14 seconds / 100 = 11.4 milliSeconds.
The thermal timeconstant of a cubic micron of silicon (perhaps the junction depth of some detector) is 11.4 nanoSeconds.


Does having to turn on an iPhone by holding power and home indicate the device is dying?

Question: I had to press and hold the Power and Home buttons because my iPhone shut off and wouldn't turn on through normal measures. When I pressed the Power and Home buttons for 20 seconds the iPhone powered on, but does this mean the phone is dying?
Answer: If it's a one-off occurrence, it doesn't mean much and you can probably ignore it.
If it's a regular problem, it may indicate something more serious, either software or hardware. You can try restoring the device in iTunes to see if it is a software problem, or take it to an Apple Store.


What would I need to do to make sure my DB policies have to pass a security audit?

Question: I have an audit coming up, and I was wondering what physical, electronic, and logical access controls an auditor would look for when auditing a database for an ERP system.  I'm really new to this process and any guidance would be appreciated.
Answer: I applaud your effort, however the question asked is probably too vague. Different rules apply to different industries and furthermore, sometimes you have the opportunity to set your own rules, you just need to follow them.
I would suggest checking with someone as to what audit you are expected to pass, then finding the specific requirements.
Comment: Agreed - they can't very well expect you to meet expectations without publishing what those expectations are.  Is it related to HIPPA, Sarbanes Oxley, specific legal requirements related to the storage of criminal histories etc...
Answer: I do agree with DeCosta's answer.  What requirements, specifications are you going to be audited on?  But, as my best shot in the dark:  This is a "best practice" publication for security related to SQL 2005 that was published by Microsoft
http://download.microsoft.com/download/8/5/e/85eea4fa-b3bb-4426-97d0-7f7151b2011c/SQL2005SecBestPract.doc
And the books online article:
http://msdn.microsoft.com/en-us/library/ms144228.aspx
Also, here is a list of things that PricewaterhouseCoopers covers in their services related to Audits of ERP systems.  It may give you some ideas.  The menu on the left hand side covers a lot of topics that may be helpful in sparking things to research.
http://www.pwc.com/be/en/systems-process-assurance/erp-security-erp-control.jhtml
Comment: No problem, good luck with audit.
Answer: To add to the excellent links above; I found the following documents as helpful reference regarding security and auditing:

PCI White paper Deploying SQL Server 2008 Based on Payment Card Industry Data Security Standards (PCI DSS) : Link
HIPPA white paper: Link
Microsoft SQL Server security bench mark from Center for Internet Security. Link
Also google for a document called Microsoft SQL Server database security checklist from US Department of Defense (unclassifed) --
Answer: A point missed by those above is around identifying exactly what you are protecting - if it is credit card data, then it is easy to realise you need PCI-DSS, but in the wider scheme of things, PCI-DSS is not really that useful except as a bare minimum baseline. You need to identify what is of value to your company, whether for commercial reasons or because the regulator or shareholders say so, and ensure your audit takes these into account.
I would also suggest looking at security.stackexchange.com, which caters specifically for the security and risk professional, and there are a lot of us there who have carried out security audits, assisted with audit preparation, led large scale security improvement and testing programmes etc.


Why do I get this error (Cannot read from the source file or disk)

Question: Why do I get this error (Cannot read from the source file or disk) when trying to move a folder and its files from a document library on one My Site to desktop
Comment: Hi - this site is designed primarily for the administrators of such systems. I would suggest that, if you are not the administrator that you contact them and let them deal with the issue. If you are the administrator, please provide more information, such as your Sharepoint version (And maybe screenshots) so that we can better help you.
Answer: This is to do with the timing of how Windows treats a file 'Move'. Unfortunately it's incompatible with the way SharePoint works, so all you can do is to 'copy' the file to your desktop, then delete the file from your MySite afterwards.


What are different infinite sum representations of $e*\pi$?

Question: $e$ and $\pi$ both have plenty of different sum representations that show up with a simple google search but its harder to find for the multiplication of  $e*\pi$. Does anyone know a sum that equals the desired result? What would be the proper method of combining known sums for $e$ and $\pi$ into the proper result such as foiling using ceasero summation? Thanks for the help
Comment: You could take the Cauchy product of two absolutely convergent series for $e$ and $\pi$.
Answer: If you accept the trigonometric function $\sin$ then the $\exp$ function should be accepted too (no ?) :
$$e\,\pi=\sum_{k=0}^\infty (-1)^k\,\frac{\sin\left(\left(k+\frac 12\right)\,\exp(1)\right)}{2\;\left(k+\frac 12\right)^2}$$
(and yes $\,e=\exp(1)\,$ could be replaced by $x$ in a certain range...)

A neat infinite product by Melzak (from the ratio of the $n$-dimensional volumes of the sphere and its largest inscribed cylinder : Mekzak $1961$ "Infinite Products for $\pi e$ and $\pi/e$") :
$$e\,\pi=6\prod_{n=1}^\infty \left(\frac n{n+1}\right)^{2n}\left(\frac{2n+3}{2n+1}\right)^{2n+1}$$
Combining two infinite products may seem easy but the problem remains...
Comment: in the first equation the $2$ factor should be at the numerator and when $\exp(1)$ is replaced by $x$ the series becomes $\,x\,\pi$.
Answer: Probably the simplest is the following. Since $1-\frac{1}{e\pi}<1
 $ we have $$\sum_{k\geq0}\left(1-\frac{1}{e\pi}\right)^{k}=\frac{1}{1-\left(1-\frac{1}{e\pi}\right)}=\color{red}{e\pi}.$$


Creating fishnet grid Shapefile in QGIS?

Question: How do I create a fishnet shapefile using QGIS?
The equivalent task of "Create Fishnet" in ArcGIS.
Answer: Look at the Processing Toolbox and you may choose many algorithms without the need of a plugin

Answer: You don't need a plugin, just use a geoalgorithm from the toolbox:
Vector > Research Tools > Create Grid...

In QGIS 2.10 this is called 'Create Graticule'
Answer: Vector grid creation has been incorporated in QGIS for a long time:
Vector -> Research Tools -> Vector Grid

Note that the default grid spacing of 0.0001000000 units of the layer CRS is too small in most cases.
You might want to use Vector -> Geometry Tools -> Densify Geometries afterwards if you need to reproject the grid to another CRS where the lines should appear bended.
Answer: In QGIS 3.4, in the Processing toolbox, look for SAGA >> Vector general >> Create polygons graticule
Answer: In QGIS 3.16. Hannover.

Install the plugin MMQGIS.

Once MMQGIS shows up at the upper toolbar, select:
MMQGIS >> Create >> Create Grid Layer

When the window shows up, remember to select the Geometry type "Rectangle" and that the layer units are in meters with the appropriate projected CRS (for further information on this issue read this answer). This is an example:
Comment: This is the only usable one I found. All the rest don't work anymore.


Magento 1.8 Adyen Integration

Question: I have an issue with the adyen-magento module. When the payment is successful in adyen, the order status doesn't updated in Magento, so the order is not getting processed. Even though when the payment is confirmed in adyen, the order status doesn't updated in Magento. Can someone help me to figure this out please?
Answer: Often this issue comes up because notifications are not properly set up, or your cron job is not running.
Check your notification setup: https://docs.adyen.com/plugins/magento-1/set-up-adyen-customer-area-m1/#step-2-set-up-notifications
Configure your cron: https://docs.adyen.com/plugins/magento-1/set-up-the-plugin-in-magento-m1/#step-2-run-cron
P.S. I work at Adyen :)
Comment: ok back to work pls
Comment: Hi Thanks,I did check with adyen, it sends positive response but in magento it is not getting processed(failed response).
Also this is happening only with few orders.
Can you please help me with this?
Comment: If this is only happening to a subset of your orders, and you've checked both your notifications and cron setup, I would recommend reaching out to firstname.lastname@example.com so they can troubleshoot the specific orders affected. Please send over the affected PSP references. Thanks!
Answer: For us it was the notification url. Also make sure this url is outside of any cache mechanism that you have in place.
If you log into Adyen you should see warnings about notification url giving bad response. Trouble is last time I used the notification test screen it was buggy and gave false positives.
Also if I remember right there is a config within the official extension to password protect notification url. Make sure that matches config in adyen.  If the notification url is specific to a store in multistore make sure the settings are set at store level.
Comment: Hi Thanks,
This is happening only with few of the orders, my guess is not with the notification URL, is there anything else that could go wrong?

Magento 1.8 Adyen Integration


Subclipse problem: running .java file as Java application

Question: After checking out code for the first time from a repository into Eclipse using the Subclipse plugin, I've found that I am not able to run Java applications anymore.  Usually when I right click in the text editor window and select "Run As", I see the option to "Run as Java Application".  Now, however, all I see is "Run on server."  Is there another way to run it as a Java application or is there some option that I need to re-configure?
Answer: Does the class you're trying to run have a public static void main(String[] args) method signature?
Answer: I actually figured it out - I checked out the wrong directory.  Because the src directory was a sub-directory, it wasn't being recognized as a package and thus wasn't allowing the .java files to be run as Java apps.  Once I checked out the right directory, it worked.
Answer: You can go to Run As->Run configurations to set where your main class is located, as this was likely changed or not set.
Answer: I have seen this if the Eclipse project is not a Java project.
Does it have Java nature?
If not, delete it, and use Check out as.. to ensure it is setup correctly.   This behaviour depends on the existance of the .project and .classpath files in the source repository.


How to create a time-driven trigger in postgresql

Question: I have a table in my database (postgres), that keeps in it the user accounting trace. I need to create a trigger that will perform a clean up at a given amount of time (let's say 30 minutes.) Is it possible to do that from postgres, or do I need to use something else? (By something else I mean C or Java or any other programming language that can sleep for a given time).
Comment: You can use [pgAgent](http://www.pgadmin.org/docs/1.4/pgagent.html) for event scheduling.
Comment: Thanks for link, but I don't know how to insatll pgAgent in my machine (I'm running Centos6.2)
Answer: Without PgAgent, things like this can be done using a cron script.
In both cases the periodic thing will be running from a different context
(database owner, superuser, postgres), and in a separate transaction, obviously.


Enabling Apache

Question: I cannot find the web sharing option in the system preferences under "Sharing"(where the web sharing is supposed to be). I am using Mac Os x 10.9.4
Answer: Warning: The normal user will be happy with Server.app
Apache is still available, but the user interface is gone. If you are comfortable configuring Apache the traditional way via config files, you can activate it by running sudo apachectl start from the shell. You find the config files in /etc/apache2. Be prepared to restore your configuration on OS updates.
Answer:
Just run sudo apachectl start.
apachectl is a shell script and sudo apachectl start runs launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist as root, which modifies /var/db/launchd.db/com.apple.launchd/overrides.plist to enable apache permanently.
To make localhost/~yourusername point to ~/Sites/, run
echo '<Directory "/Users/'$USER'/Sites/">
  Options Indexes Multiviews
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
</Directory>'|sudo tee -a /etc/apache2/users/$USER.conf

and run sudo apachectl restart.
To enable PHP, uncomment
#LoadModule php5_module libexec/apache2/libphp5.so

in /etc/apache2/httpd.conf and run sudo apachectl restart.
Answer: If you're not comfortable with the command line methods,  you might consider installing MAMP, which offers a convenient GUI for starting, stopping and basic configuration: http://www.mamp.info/en/

Enabling Apache


Can a Green Lantern ring be summoned by its wielder?

Question: Much like how Thor's hammer goes to him no matter where he is, can GL call for their rings?
Answer: A Green Lantern can recall their rings from short distances, no more than twenty or thirty feet, even if it has been taken from them by subterfuge or force. However, unlike Mjolnir, a ring will not cross great distances to return to a ring-wielder, nor can a ring create a wormhole or cross dimensional barriers on its own.

Rings can, however, be programmed with instruction algorithms which could include a "program" to return to a location or perform a specific action under certain conditions.

Kyle Rayner preprogrammed his ring to seek him out and find him, should it ever be separated from him. Such programming was unique to Kyle Rayner's ring but likely could be replicated by other Green Lanterns who were willing to put in the time.

Rings ARE able to cross great distances and opening wormholes for one purpose: to find new ring-bearers in the event of the death of their primary user.
Comment: nice answer with new 52 screens?
Comment: Considering how sophisticated the rings are and the fact that they can act independently, it seems kind of silly that the weilder couldn't summon it. I mean, what if the weilder was in a predicament where he needed it?
Comment: Why would he need to take it off in the first place? The ring can be completely invisible, so he would never need to be separated from it? Given the nature of his work, if someone CAN take his ring and mean to do him harm, then he has few choices anyway. Can you create a circumstance where he intentionally would leave the ring behind and hope to have it find him later at a designated location? Perhaps you could, but it certainly would be a strange circumstance, to be sure.
Comment: There was an issue earlier in Green Lantern Volume 4 where Hal and Cowgirl get kidnapped and taken to Russia and he left his ring in his appartment. Whenever he flies, he leaves the ring off. I, personally, just find it a tad bit bizzare that the most advanced technology in the universe, which has an AI that can act independenlty and travel vast distances, does not have the capability to go to it's weilder when summoned.
Comment: You mean Hal's insistence on flying the experimental planes without wearing the ring? He says it makes him less vigilant and less aware. Okay, there is a precedent for it. As the Guardians have been fond of saying, the ring isn't magic. It is a technology and this ability you are speaking of isn't within its ability. It could be despite the sophisticated near AI capacity, the Guardians are leery of such independence due to their incredible mishap with their previous creations, the Manhunters. Given the massacre, I can understand their reluctance.


Does Wp-Ecommerce works with LinkPoint gateway?

Question: I have an online store working with osCommerce, actually works fine. But there is no integration with the store blog which is in Wordpress fortunatelly.
Now I've seen a new payment plugin for wordpress called Wp-Ecommerce , so i decided to migrate the whole store to wordpress since this can be treated like a CMS.
This plugin has really handy features like Meta Tag properties for each product in order to do SEO position for the store.
I've been reading about wp-ecommerce and searching through the web to find a chance to integrate it with LinkPoint, which is my client's store gateway. I must say this is an imperative requirement I have to do in order to migrate the whole site to Wordpress
Has anybody make this possible ? get wordpress working with LinkPoint ?
Answer: Looks like it currently only supports Authorize.Net. You may want to check out Shopp. The Linkpoint plug-in is not free but it is available.


Turn off user social registration in django-allauth?

Question: I noticed looking through the django-allauth templates there's a signup_closed.html users can be redirected to when user registration is closed or disabled. Does anyone who's familiar with that module know if there's a pre-configured setting that can be set in settings.py to turn off new user registration via existing social apps? Or do I need to configure that myself? I've read the full docs for allauth and I don't see any mention of it. Thanks.
Answer: Looks like you need to override is_open_for_signup on your adapter.
See the code.
Answer: There is no pre-configured setting but it's easy to make one (this is what I do).
# settings.py

# Point to custom account adapter.
ACCOUNT_ADAPTER = 'myproject.myapp.adapter.CustomAccountAdapter'

# A custom variable we created to tell the CustomAccountAdapter whether to
# allow signups.
ACCOUNT_ALLOW_SIGNUPS = False

# myapp/adapter.py

from django.conf import settings

from allauth.account.adapter import DefaultAccountAdapter

class CustomAccountAdapter(DefaultAccountAdapter):

    def is_open_for_signup(self, request):
        """
        Whether to allow sign ups.
        """
        allow_signups = super(
            CustomAccountAdapter, self).is_open_for_signup(request)
        # Override with setting, otherwise default to super.
        return getattr(settings, 'ACCOUNT_ALLOW_SIGNUPS', allow_signups)

This is flexible, especially if you have multiple environments (e.g. staging) and want to allow user registration in staging before setting it live in production.
Comment: This code does the trick.  However, let me add a warning label:  Implementing this custom adapter can prevent initial logins on social accounts, which can require operating signup methods to create the user's social account.  Users with pre-existing accounts will not be affected, but if you add a user to Azure AD (for example) and let them sign in with their microsoft ID, they'll be redirected to the non-working signup views, since their account can't be created automatically.
Answer: More information at http://django-allauth.readthedocs.io/en/latest/advanced.html#custom-redirects.
You need to subclass allauth.account.adapter.DefaultAccountAdapter to override is_open_for_signup, and then set ACCOUNT_ADAPTER to your class in settings.py
Comment: In case this helps others. I followed instructions above but named my custom adapter file `account_adapter.py` which is seems to be reserved name so it was giving `ModuleNotFoundError`. I had to rename it to something else eg `my_account_adapter.py` and then this worked.


iPhone - Triggering APNS

Question: I am working on a iPhone application which uses APNS. I am clear about the procedures in implementing APNS, creating device token, blah blah blah... I have no idea how to trigger and initiate the APNS from the provider side by web service. Can anyone suggest me some blogs or links which guide me to gain knowledge how to deal with it. Thanks in advance.
Answer: If you don't want to spend time doing it on your own, you can try Urban Airship. If you want to do everything on your own instead, check out this tutorial. It also explains how to create the required certificates.
Otherwise you can try libraries such as apns-php. Just make sure it works with lots of messages (I haven't tested it) and meets your requirements (you may want support for multiple apps). Avoid EasyAPNS because it just doesn't work with more than 10 messages (it tries to open a connection for each message and will probably get your IP banned).
Answer: If you just want to get a better understanding of APNS and don't want to get aboard one of the 3rd party services, then try:

NWPusher

It allows you to send pushes right from your Mac. Great for testing your client application and for setting up the right certificates.
Answer: You might want to take a look at Urban Airship, they will make things a lot easier for you.
Answer: If you want to roll out your own server, here are some good starting points in terms of documentation/help

apns-php
easy apns
Another tutorial
Comment: Avoid Easy APNS. http://stackoverflow.com/questions/5625480/easyapns-has-anybody-tried-it-with-large-amounts-of-notifications

iPhone - Triggering APNS


How do you symbolize "Unique Values, Many Fields" with more than 3 fields?

Question: I have data that has 5 fields with unique values that I need to symbolize at one time. Is there a work around to allow me to do this or a python code I can run to use more than three fields?
Comment: If you really needed to, you could concatenate a couple of fields into one, and still have the same number of unique values in your symbology.
Answer: Besides the obvious, the ArcMap interface really isn't suitable for so many fields. Even three fields is pretty cumbersome.
A workaround is to recode your five fields into a single, master symbology field. Then you can use the regular unique values symbology for this. Here's an example with some made-up data:
╔═════════╦══════════╦═══════════╦═════════╦══════════╦════════╗
║ Field 1 ║ Field 2  ║  Field 3  ║ Field 4 ║ Field 5  ║ Master ║
╠═════════╬══════════╬═══════════╬═════════╬══════════╬════════╣
║ USA     ║ New York ║ Buffalo   ║ Type 1  ║ Active   ║      1 ║
║ USA     ║ New York ║ Buffalo   ║ Type 2  ║ Active   ║      2 ║
║ USA     ║ New York ║ Rochester ║ Type 1  ║ Inactive ║      3 ║
║ Canada  ║ Ontario  ║ Toronto   ║ Type 2  ║ Active   ║      4 ║
║ Canada  ║ Ontario  ║ Toronto   ║ Type 2  ║ Inactive ║      5 ║
╚═════════╩══════════╩═══════════╩═════════╩══════════╩════════╝

By recoding the fields into the Master field, you can create a set of unique symbologies as needed. You could even concatenate values so that the master field had a value of USA, New York, Buffalo, Type 1, Active in the first row.
Answer: You could also load multiple copies of the same feature class into the map and then limit the features displayed using a definition query to sort out the first two columns, then use the three available in the symbology properties for the remaining three.
So, to build on the example from @dmhar:
Load one copy and set the definition query to only show the USA and New York features, then use the symbology properties to show Type 1 or 2, and Active or Inactive.
Load another, set the definition query to show Canada and Ontario features and use the same symbology for the last three classes.
Another thing to consider is what you are trying to show with the map.  Needing to categorize your symbology for five levels will likely be very confusing for the map user.  Perhaps it's better to make more maps, each showing a subset of the data.  That would probably provide your user with a more approachable map.


OpenStreetMap data OSMOSIS and MySQL - make faster?

Question: How can I make dumping .osm data into a MySQL database faster using Osmosis? Currently 3 hours so far for the USA file but MySQL is only using 10-15 percent CPU, 10 percent RAM and HD is negligible (32gb RAM, i7 12700 and M.2 4.0 drive). Something in my.ini that I need to adjust or just the limitations of osmosis and MySQL? Using Win 11 and Xampp.
Answer: Osmosis can be used to load OSM data into an apidb schema database. This database is particularly designed for the OSM API, which, many years in the past, used to use MySQL. You almost certainly want to use osm2pgsql, imposm, or other software to load a database suitable for rendering, analysis and other usage of OSM data.
If you do want an apidb database, you need to use PostgreSQL. The MySQL tasks in osmosis do not support 0.6, the current API and data model.
When loading into an apidb, I would expect loading all of the US to take about a week.


Slow image review after long exposure shot

Question: When I use the Bulb function for long exposure shots on my Canon 60D, I find the Image Review afterwards takes for ever to appear...  the camera displays 'busy' for nearly as long as the exposure took.  It does not seem right.  Any suggestion re settings?
Answer: That's long exposure noise reduction taking place.
See Is in-camera high-ISO noise reduction worthwhile?
You can switch this off in the shooting menu.


Client-Side Polygon split

Question: I wanted to know if there is a way to split a polygon using JavaScript.
So I have a web map which uses Leaflet API, and the user needs to cut polygons which are shown in the map using a straight line. I was hoping there would be a JavaScript library something JSTS or Turf but if that isn't possible an algorithm would do just fine.
Comment: Why is Turf not suitable?
Comment: I am pretty sure I have gone through the whole turf.js documentation and I haven't found any method that would deal with every type of polygon. I hope I am wrong because that means I have wasted 3 days of research.
Comment: This is not as simple as I thought, but it was a nice challenge. See one possible answer below.
Answer: Below is one possible solution using Turf library. Solution is not exact since Turf does not have method to split polygon with line and get as result two split polygons.
The closest method is turf.difference(poly1, poly2), which cuts out second polygon from first. If second polygon is very thin and long rectangle (line with small 'height'), this can be used as split method, where first polygon is split by second.
This is done in two steps. First step is to 'fatten' dividing line to one side (let's call it upper), cut polygon by it and take into account split polygon one the other (lower) side of the line. Then dividing line is 'fattened' to the other side (lower), polygon is cut by it and split polygon on upper side is taken into account.
Code below has been tested, but is more or less proof of concept and not very robust. Parameters polygon and line are considered to be geometries.
function cutPolygon(polygon, line, direction, id) {
  var i = -1;
  var j;
  var polyCoords = [];
  var retVal = null;

  if ((polygon.type != 'Polygon') || (line.type != 'LineString')) return retVal;
  if (line.coordinates.length != 2) return retVal;

  var intersectPoints = turf.lineIntersect(polygon, line);
  var nPoints = intersectPoints.features.length;
  if ((nPoints == 0) || ((nPoints % 2) != 0)) return retVal;

  var offsetLine = turf.lineOffset(line, (0.01 * direction), {units: 'kilometers'});
  var thickLineCorners = turf.featureCollection([line, offsetLine]);
  var thickLinePolygon = turf.convex(turf.explode(thickLineCorners));

  var clipped = turf.difference(polygon, thickLinePolygon);

  for (j = 0; j < clipped.geometry.coordinates.length; j++) {
    var polyg = turf.polygon(clipped.geometry.coordinates[j]);
    var overlap = turf.lineOverlap(polyg, line, {tolerance: 0.005});
    if (overlap.features.length > 0) {
      polyCoords[++i] = turf.coordAll(polyg);
    };
  };

  if (i == 0)
    retVal = turf.polygon(polyCoords, {id: id});
  else if (i > 0) {
    retVal = turf.multiPolygon([polyCoords], {id: id});
  }

  return retVal;
};

var upperCut = cutPolygon(polygon, line, 1, 'upper');
var lowerCut = cutPolygon(polygon, line, -1, 'lower');

Working fiddle is available at https://jsfiddle.net/TomazicM/2rdbcmL0/. If line is drawn across polygon, it will be split along line.
Comment: I'll give it a try man

Client-Side Polygon split


NSCopyObject considered harmful?

Question: In the Xcode documentation for NSCopyObject, the special considerations section states:

This function is dangerous and very difficult to use correctly. It's use as part of copyWithZone: by any class that can be subclassed, is highly error prone. Under GC or when using Objective-C 2.0, the zone is completely ignored.
This function is likely to be deprecated after Mac OS X 10.6.

Why is it difficult to use correctly? It performs a shallow (bit-for-bit) copy. Objects are not copied or retained. The documentation is pretty clear on this.
If I'm not missing other reasons, what is the preferred alternative for performing a shallow copy of an object?
Edit:
There are valid reasons to want to perform a shallow copy. One example: a class may have many instance variables, most of which are primitive types (integer, float) or objects that are intentionally not retained to avoid retain cycles (delegates). A shallow copy using NSCopyObject copies all of these in one nice, self-documenting line of code. Any remaining ivars that do need to be reference counted can be retained or copied individually.
The alternative to this is to either assign to the new object using pointer syntax (newObject->ivar = ivar) or to create an init method with a potentially large number of arguments (one for each ivar to copy). The latter strikes me as especially ugly, but I suppose it doesn't need to be in the header and exposed to the world.
Answer: You shouldn't make a shallow copy not involving the correct retain/release. Period.
Comment: Obviously, but fixing those references is up to the developer. Your answer does not address my question of why `NSCopyObject` "is dangerous and very difficult to use correctly."

NSCopyObject considered harmful?


How does "Concealment" transfer to Dedicated Transports?

Question: I have been looking over the combat benefits from the various force organisations granted by Gladius Strike Forces. The one that interests me is the 10th Company bonus where all units in this Company gain Concealment (Stealth until almost anything other than embarking, disembarking or shooting). However, I have a number of land speeder storms that act as dedicated transports that gain this status as well. So my question is if I disembark a concealed unit and its transport moves, does the entire unit loose concealment or just the Transport?
Comment: I'm going to check this in greater detail, but from the wording it looks like the unit and the transport both lose Concealment.
Answer: The 10th Company's special rule Concealed Positions gives Stealth to each unit in the formation that deploys using the Infiltration rule.  We also know that the Dedicated Transport is a separate unit from the unit that disembarked.

Dedicated Transports do not use up any slots on a Force Organisation
  Chart, but otherwise function as separate units.

Therefore, if the transport moves, only the Dedicated Transport will lose Stealth. Each unit--independently--will have special rule Stealth until it performs an action that cancels it.
Answer: Disembarkation is a move. So getting out will make the unit lose stealth, though the transport would retain stealth as long as it didn't move. If the transport moves (before or after disembarking) it loses stealth as well.


How to change EmailId of Trailhead account?

Question: I want to change email id of my trailhead account which is currenly set to my organization Email to my personal Email.
Answer: I had the same question once. I wrote to suppprt and got the following answer:

It is not possible to change the email address of the trailhead
  account. In this case, we suggest you create a new trailhead account
  with the required email address. By using merge process we can merge
  badges to the new account.

Please find the suggested solution below:

Create a new trailhead account with your personal E-mail address.
Merge the old account with the above newly created account. Here is how to do that Trailhead Self-Service Account Merge
Comment: The problem I have is once you merge, it's still creating playgrounds with old email, which may not even exist.
Comment: Were you able to merge trailhead accounts?
Comment: Yes, I merged my accounts successfully. If you face any issue with that, you better contact support to help you.
Comment: I can't create a new account because the email is already associated with the existing account


How does the 51 percent or 2/3 majority voting rule work?

Question: For a block to be added to the chain, it needs vote from majority of miners, is that correct? If yes, does that mean a single block gets worked upon by all of the miners?
Answer:
For a block to be added to the chain, it needs vote from majority of miners, is that correct? If yes, does that mean a single block gets worked upon by all of the miners?

There is no voting. Each miner works on their own version of blocks. Once they have found the hash of the block header which meets the difficulty target, they broadcast the block to the rest of the network. When the other full nodes and miners receive this block, they will first verify if the block meets all the protocol rules, and the transactions within the block are also valid. The bitcoin software is designed so as to accept the chain with the most proof of work. In most cases this is also same as the longest chain. So, when the new block is received by the nodes, they would add this block on top of the existing chain if the block is valid. When the block is received, the other miners would see that they have lost the 'race' for that particular block height. Now they will start working on the next block, by building on the top of the block that they just received.

How does the 51 percent or 2/3 majority voting rule work?

I assume you are referring to 51% attack. 51% attack basically means that if a miner has more than 50% of the hash power of the total network, he has higher probability of mining blocks that is faster than the rest of the network combined. If that is the case, then the miner can double spend the bitcoins. If you want more clarity as to what 51% attack is, then you can refer here. Regarding 2/3rd voting, you might have read that as a part of Byzantine Fault Tolerance (BFT) threshold. However, bitcoin doesn't exist within the normal model of BFT consensus. Under conventional assumptions bitcoin will converge on a stable history if honest participants have a majority hashpower (>50%).
Comment: "Blockchain is consensus-based; every transaction needs approval from more than half of the participants or nodes before execution." - Is this statement incorrect then? I read it in a paper [here](https://www.citiustech.com/uploads/knowledgehub/pdf/blockchain-for-healthcare-341.pdf)
Comment: @abhisheksingla you are comparing apples to oranges. In the example that you have described they are using private blockchains. There is no mining, there is no economic incentive for nodes to act honestly. It's just a glorified approval dabes database management system.


Entering the UK as a British citizen who is a Canadian permanent resident

Question: I am a permanent resident living in Canada; I hold a British passport. I am travelling back to the UK for a holiday, and was wondering whether, when arriving, am I able to walk straight through or do I have to join the line up as if I were a visitor?
Comment: Right, so does "home" denote your country of residence or your country of origin?  People sometimes use the word for one purpose and sometimes for the other.  Anyway, citizens of the UK have to show to an immigration officer that they are in fact citizens of the UK, so yes you'll have to line up.
Comment: I think there is some confusion about whether you consider UK or Canada "home" given the current comments and answers. Could you clarify?
Comment: I am a permanent resident of Canada, living  in Canada, born in the UK and hold a UK passport
Comment: Sorry for the confusion, I always call the UK home even though I reside in Canada
Comment: As a UK citizen you will have to join the queue as with anyone else on the flight.
Comment: With the circumstances outlined, a person in your position might consider Canada as their home because they are a permanent residence and that's where they live (i.e. their home) OR being born in Britain and being British the same person might call Britain as their de facto home.
Answer: As you're a British citizen, you'll be allowed into the UK with minimal fuss whether or not you actually live there. The border guards won't know or care what country you're living in, and are very unlikely to ask you any questions at all.
When you arrive in the UK, join the "UK and EU passports" line at passport control. You'll still have to wait (possibly a while at larger airports) but this line usually moves much faster than the line for non-EU folks.
EDIT: Notts90 raises a good point about which country you mean by "home". If you're talking about returning to Canada as a permanent resident, you'll still have to wait at passport control, although there might be a separate line for permanent residents.
Comment: Returning to Canada, Canadian residents can use the automated passport controls at the airport much as citizens can. These machines are actually better than the NEXUS on the Canadian side -- NEXUS is helpful when entering the USA and you can get it as a resident after three years. Source: I was a Canadian resident for a long while, very familiar with the rigmarole.
Comment: Can use automated passport control in the UK at most airports too, so you might not even speak to a border guard... Mine never works in them though hand always end up having to see one!
Answer: As a citizen of the UK, you are entitled to enter the UK.  To get past the immigration checkpoint, however, you have to establish to the satisfaction of an immigration officer that you are a citizen of the UK.  That means that you must wait for an available immigration officer (or automated passport gate) if one is not immediately available.  Furthermore, you have to stop at the gate or at the officer's desk to show your passport and wait for any validation process to be completed.
This process is much quicker than the full immigration checks that non-EU/EEA/Swiss travelers go through, so the line you will join will generally be much shorter and faster moving, but you certainly can't characterize it as "walking straight through."
Comment: I suspect the question is "Can I use the UK/EU passports line or do I have to use the other line?" rather than literally "Will there be any line at all?"
Comment: @DavidRicherby maybe. But I've encountered more than one person who has misunderstood the meaning of "not subject to immigration control" sufficiently to ask why they have to show their passport if they're not subject to immigration control.


Postgresql Master/Slave Using Patroni

Question: Can I promote a slave node to be a master for insert/update/delete using Patroni once the original master goes down?
Answer: The whole point of Patroni is that you don't have to do that yourself, but that Patroni does it for you automatically.
The nodes communicate regularly via a distributed consensus store that decides who is online and who isn't, and arbiters who of the available nodes should become the leader.
You can also tell Patroni manually to switch leader, even if all nodes are up (a "switchover").
Comment: If Patroni fails over to a standby, the standby is promoted and will become the new primary, so it is open for reading and writing.

Postgresql Master/Slave Using Patroni


Properties of transitors used as diodes

Question: Consider the NPN BJT. Normally, if you want to use it as a diode, you short base to collector and treat the emitter as the cathode. But in principle, you could also use the base emitter junction by itself (collector floating), or even the base collector junction (emitter floating). I guess you could even tie the emitter and base together and treat the collector as the cathode. What would the properties be of these diodes? Anything that might be useful in special circumstances?
Answer: If you follow BJT modelling, then you can conclude these facts

Emitter is doped highest but has considerable bigger area than base and lesser than collector
Base is doped considerable more than collector but less than emitter and is having least area
Collector is doped least and has maximum area among all three.

Now this will lead to Band diagram as shown below.

Thus for considerable amount of drift & diffusion currents as per study from  Energy levels , Base and collector must be shorted to make a P-type node of Diode and Emitter is heavily doped already hence it will make N-type node of Diode
NOTE : I might be not able to explain well , but I hope this facts come useful to understand

added later on
Why to short Base-Collector , Instead of Base-Emitter
Lets say following abbrevations for sake of explanation
BE: Base Emitter Junction
CB: Base Collector Junction
Consider the BE as single entity,Now since emitter is doped more heavy compared to base BE junction will act as N-Type element, since u are left with collector which is already N-Type element , Thus it will result in bad diode.
Now on other hand for CB as single entity, base is more heavy doped compared to collector, Hence CB will act as P-Type element, you are left with emitter which is already comparative doped as N-Type element. Thus this can result in well functional Diode.

More ....
$$
I_E = I_B +\ I_C \\
I_C = \beta  I_B \\
I_C = \alpha I_E \\
I_E = (\beta +\ 1)I_B \\
I_C=I_s e^{\left(\frac{V_{BE}}{V_T}\right)} \\
\text{Normal values of}~\beta = 99 ~ \& ~ \alpha = 0.01\\
I_E \approx I_C \approx \text{few hundreds}~mA \\
I_B \approx \text{few}~\mu A
$$
On study of above equations, we can have few conclusions

emitter & collector contribute major amount of currents. compared to base
base has to be in picture as its connecting link for collector & emitter

PS: this lab document has some good insights
Comment: I like the answer but I would welcome a better explanation why base and collector actually "have to" be shorted. Why not just use base and emitter? Maybe someone else can contribute some more details.
Comment: @Rev1.0 I think the later added explanation can help..
Comment: Maybe my question wasn't clear. That connecting BC still results in a p-region is understandable, there are simply more positive carriers in the base than negative in the collector region. My actual question was more: Why not ignore the collector? E-B should make a better diode than E-BC. That was essentially also part of the original question.
Comment: @JigarGandhi I am very interesting about this subject since this technick used very often inside of ICs. So please try again and edit.
Comment: i am not able to get exact reason i feel.. hope someone gets exact reason.

Properties of transitors used as diodes


c# sockets CONNECTIONS

Question: I'm trying to open a socket for wireless connection and from what I understand I need to open port 8888. What is this port? See link:
http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm
Answer: If you meant to ask what the meaning of this port is, it's not registered or known to be used by anything significant. IANA says it has at some point been used by a "NewsEDGE server", which I can't even find via a Google search. It's just a random port the person who wrote the tutorial chose to use as an example.
Answer: 8888 is the number of the port. That could be anything listening to that port.
IANA has a list of registered ports, but for private applications you usually borrow a port number that you don't expect to be used.
Answer: Anybody that writes an application that listens on a socket must pick a port number that's unique to the specific protocol he uses.  It is not a completely free choice, the application on the other end of the wire needs to use the same port number.  And having two distinct apps with different protocols listen on the same port is disastrous.  Furthermore, the firewall has to be opened for the port.
Picking a number like 8888 is the proper thing to do.  Although it is a bit unimaginative, the risk for picking the same number as used by a random other app is not zero.  These apps usually have a backdoor, a config file that lets you choose another one in case that happens.

c# sockets CONNECTIONS


How to access Ubuntu One server side logs for my account?

Question: I would like to have info (time, filename, and user when having shared folders) about file changes, uploads, downloads...
Comment: Please vote my answer up since you have accepted it as the best which means that my answer was helpful. Thanks in advance!
Answer: The syncdaemon.log (in ~/.cache/ubuntuone/log) provides that info too. If you want to have access to server side logs, you should contact U1 team at https://one.ubuntu.com/support/contact/


Does anyone know of a defrag program that can group files by folder?

Question: I have tried a few defrag programs, but I have never found one that allows the user to group files together by directory/folder. I ask this because I have an Excel program that gets all my mp3 files and lists them in a spreadsheet. I'm sure it would run quicker (it takes about five minutes now) if my mp3 files were grouped together. They are on a hard disk drive rather than an SSD. SSDs in the 4 TB region are still pretty expensive.Edit:File system is NTSFOS is Windows 7 x64Defrag programs I've used: Norton, Raxco's PerfectDisk, Defraggler that comes with CCleaner, of course Window's built-in defrag, and one other I can't recall the name of (QDisk?).None of them gave the option of grouping files by directory/folder.
Comment: @Mawg, this get complicated...I have several sheets in my workbook. The first sheet gets and lists all the mp3 files in my music folder and its subdirectories; there are just over 9,100 mp3 files. On the 2nd sheet I copy the songs from sheet1 that I want on my thumb drive; it has index/match formulas that get the full path. I then have another sheet that lists all the songs, which is written to via a macro. That sheet also has another macro that writes the batch file that I use to copy the files from the drive to the thumb drive. I could probably use iTunes, but I find it cumbersome.
Comment: For what filesystem? NTFS I guess?
Comment: Why would it matter where the files are? You won't be accessing them, just the File Allocation Table to get their names.
Comment: I strongly suspect that Excel is your bottleneck here. It is not designed to access files. I guess that you are using a VBA macro, which will be interpreted and that a compiled program would be much faster. There are many MP3 catalog programs out there. Perhaps, if you tell us the features that you want, we could recommend one.
Comment: Thanks for the explanation (+1)> But, lolx!  You start "this get complicated" and end "I could probably use iTunes, but I find it cumbersome" :-)  All that I can suggest is to try out a few ITunes competitors. Or, if you can code, code as much as you can in a some compilable language and call that from a VBA stub.
Comment: It's that first sheet1 that I would like to speed up. It takes a bit north of 5 minutes to get all the mp3 files, and I figured (hoped?) that maybe having all the mp3 files physically located in the same neighborhood of the hard disk would speed things up.
Answer: UltimateDefrag (Paid, 30 days trial)
This utility, aside from doing regular file consolidation, it able to reorder the files in disk. In particular, it allows you to specify what files and folders you want to move to the outer tracks of the disk (which are the ones that gives better performance).
You may also tell it to consolidate folders troghout the whole disk, or to sort them by last usage (placing those that have been used more recently in the outer tracks).
Comment: to you have any personal experience with this program, or is it just one you're aware of? (+1 for the answer).
Comment: @BillOertell I have used it. It is the only one I am aware of that can rearrange files. I suggest getting the last version (it is faster, and I had some issues with version 4 that I will not go into). Advice: set it to not move large consolidated files. If you only need to arrange a few folders, you can do it on the trial version with no problem. For sorting the full disk, I would advice to buy a license (because it takes too long, you probably want to split the work in multiple sessions, and your 30 days might be over before you finish... depending how big the disk is, of course).
Comment: thanks. I'm going to go ahead and mark this as answered. I see from your link that the current version is 5. You say you had problems with version 4; does that mean you prefer version 3 over version 4, or version 5 over version 4?
Comment: @BillOertell version 4 was the first one I used, never used version 3 so I can't really speak of how it works. Judging by the published fixes in version 4 (a crash condition and wrong handling of the MFT) I would suggest to not go back.
Comment: I downloaded the program and ran it today. It took about six hours to organize and defrag a 6 GB HDD with almost a TB of data on it. The Excel macro that gets all my MP3 files used to take about seven minutes to run. After the defrag it took five.