Asterisk Server - System(asterisk -rx 'sip reload')

Question: I have the following line in extensions.conf
exten => s,1,System(asterisk -rx 'sip reload')
Is there a SipReload() command in asterisk that can replace my System() command?
Answer: The above method is the only way I've ever seen it done, providing you write in some kind of protection so someone can't just hit that context in your dial-plan and have fun reloading your server over and over ;)
Answer: A simple way to find out would be to do from the Asterisk CLI:
<code>asterisk -rx'core show applications'
</code>
The output currently does not show any such option. The output is:
    -= Registered Asterisk Applications =-
<code>          ADSIProg: Load Asterisk ADSI Scripts into phone
               AGI: Executes an AGI compliant application.
               AMD: Attempt to detect answering machines.
            Answer: Answer a channel if ringing.
      Authenticate: Authenticate a user
        BackGround: Play an audio file while waiting for digits of an extension to go to.
  BackgroundDetect: Background a file with talk detect.
            Bridge: Bridge two channels.
        BridgeWait: Put a call into the holding bridge.
              Busy: Indicate the Busy condition.
CallCompletionCancel: Cancel call completion service
  CallCompletionRequest: Request call completion service for previous call
     CELGenUserEvent: Generates a CEL User Defined Event.
     ChangeMonitor: Change monitoring filename of a channel.
       ChanIsAvail: Check channel availability
   ChannelRedirect: Redirects given channel to a dialplan target
           ChanSpy: Listen to a channel, and optionally whisper into it.
         ClearHash: Clear the keys from a specified hashname.
        ConfBridge: Conference bridge application.
        Congestion: Indicate the Congestion condition.
     ContinueWhile: Restart a While loop.
   ControlPlayback: Play a file with fast forward and rewind.
          DAHDIRAS: Executes DAHDI ISDN RAS application.
         DAHDIScan: Scan DAHDI channels to monitor calls.
          DateTime: Says a specified time in a custom format.
             DBdel: Delete a key from the asterisk database.
         DBdeltree: Delete a family or keytree from the asterisk database.
           DeadAGI: Executes AGI on a hungup channel.
              Dial: Attempt to connect to another device or endpoint and bridge the call.
           Dictate: Virtual Dictation Machine.
         Directory: Provide directory of voicemail extensions.
              DISA: Direct Inward System Access.
          DumpChan: Dump Info About The Calling Channel.
              EAGI: Executes an EAGI compliant application.
              Echo: Echo media, DTMF back to the calling party
          EndWhile: End a while loop.
              Exec: Executes dialplan application.
            ExecIf: Executes dialplan application, conditionally.
        ExecIfTime: Conditional application execution based on the current time.
         ExitWhile: End a While loop.
          ExtenSpy: Listen to a channel, and optionally whisper into it.
       ExternalIVR: Interfaces with an external IVR application.
             Flash: Flashes a DAHDI Trunk.
           ForkCDR: Forks the current Call Data Record for this channel.
          GetCPEID: Get ADSI CPE ID.
             Gosub: Jump to label, saving return address.
           GosubIf: Conditionally jump to label, saving return address.
              Goto: Jump to a particular priority, extension, or context.
            GotoIf: Conditional goto.
        GotoIfTime: Conditional Goto based on the current time.
            Hangup: Hang up the calling channel.
  HangupCauseClear: Clears hangup cause information from the channel that is available through HANGUPCAUSE.
              ICES: Encode and stream using 'ices'.
         ImportVar: Import a variable from a channel into a new variable.
        Incomplete: Returns AST_PBX_INCOMPLETE value.
               Log: Send arbitrary text to a selected log level.
             Macro: Macro Implementation.
    MacroExclusive: Exclusive Macro Implementation.
         MacroExit: Exit from Macro.
           MacroIf: Conditional Macro implementation.
     MailboxExists: Check to see if Voicemail mailbox exists.
       MessageSend: Send a text message.
         Milliwatt: Generate a Constant 1004Hz tone at 0dbm (mu-law).
     MinivmAccMess: Record account specific messages.
      MinivmDelete: Delete Mini-Voicemail voicemail messages.
       MinivmGreet: Play Mini-Voicemail prompts.
         MinivmMWI: Send Message Waiting Notification to subscriber(s) of mailbox.
      MinivmNotify: Notify voicemail owner about new messages.
      MinivmRecord: Receive Mini-Voicemail and forward via e-mail.
        MixMonitor: Record a call and mix the audio during the recording.  Use of StopMixMonitor is required to guarantee the audio file is available for processing during dialplan execution.
           Monitor: Monitor a channel.
         Morsecode: Plays morse code.
         MP3Player: Play an MP3 file or M3U playlist file or stream.
              MSet: Set channel variable(s) or function value(s).
       MusicOnHold: Play Music On Hold indefinitely.
            NBScat: Play an NBS local stream.
             NoCDR: Tell Asterisk to not maintain a CDR for this channel.
              NoOp: Do Nothing (No Operation).
         Originate: Originate a call.
              Page: Page series of phones
      PauseMonitor: Pause monitoring of a channel.
            Pickup: Directed extension call pickup.
        PickupChan: Pickup a ringing channel.
          Playback: Play a file.
         PlayTones: Play a tone list.
    PrivacyManager: Require phone number to be entered, if no CallerID sent
        Proceeding: Indicate proceeding.
          Progress: Indicate progress.
    RaiseException: Handle an exceptional condition.
              Read: Read a variable.
         ReadExten: Read an extension into a variable.
        ReceiveFAX: Receive a FAX and save as a TIFF/F file.
            Record: Record to a file.
          ResetCDR: Resets the Call Data Record.
         RetryDial: Place a call, retrying on failure allowing an optional exit extension.
            Return: Return from gosub routine.
           Ringing: Indicate ringing tone.
          SayAlpha: Say Alpha.
      SayAlphaCase: Say Alpha.
         SayDigits: Say Digits.
         SayNumber: Say Number.
       SayPhonetic: Say Phonetic.
       SayUnixTime: Says a specified time in a custom format.
          SendDTMF: Sends arbitrary DTMF digits
           SendFAX: Sends a specified TIFF/F file as a FAX.
         SendImage: Sends an image file.
          SendText: Send a Text Message.
           SendURL: Send a URL.
               Set: Set channel variable or function value.
       SetAMAFlags: Set the AMA Flags.
      SIPAddHeader: Add a SIP header to the outbound call.
       SIPDtmfMode: Change the dtmfmode for a SIP call.
   SIPRemoveHeader: Remove SIP headers previously added with SIPAddHeader
               SMS: Communicates with SMS service centres and SMS capable analogue phones.
        SoftHangup: Hangs up the requested channel.
SpeechActivateGrammar: Activate a grammar.
  SpeechBackground: Play a sound file and wait for speech to be recognized.
      SpeechCreate: Create a Speech Structure.
SpeechDeactivateGrammar: Deactivate a grammar.
     SpeechDestroy: End speech recognition.
 SpeechLoadGrammar: Load a grammar.
SpeechProcessingSound: Change background processing sound.
       SpeechStart: Start recognizing voice in the audio stream.
SpeechUnloadGrammar: Unload a grammar.
          StackPop: Remove one address from gosub stack.
  StartMusicOnHold: Play Music On Hold.
            Stasis: Invoke an external Stasis application.
    StopMixMonitor: Stop recording a call through MixMonitor, and free the recording's file handle.
       StopMonitor: Stop monitoring a channel.
   StopMusicOnHold: Stop playing Music On Hold.
     StopPlayTones: Stop playing a tone list.
            System: Execute a system command.
        TestClient: Execute Interface Test Client.
        TestServer: Execute Interface Test Server.
          Transfer: Transfer caller to remote extension.
           TryExec: Executes dialplan application, always returning.
         TrySystem: Try executing a system command.
    UnpauseMonitor: Unpause monitoring of a channel.
         UserEvent: Send an arbitrary user-defined event to parties interested in a channel (AMI users and relevant res_stasis applications).
           Verbose: Send arbitrary text to verbose output.
    VMAuthenticate: Authenticate with Voicemail passwords.
         VMSayName: Play the name of a voicemail user
         VoiceMail: Leave a Voicemail message.
     VoiceMailMain: Check Voicemail messages.
  VoiceMailPlayMsg: Play a single voice mail msg from a mailbox by msg id.
              Wait: Waits for some time.
         WaitExten: Waits for an extension to be entered.
      WaitForNoise: Waits for a specified amount of noise.
       WaitForRing: Wait for Ring Application.
    WaitForSilence: Waits for a specified amount of silence.
         WaitUntil: Wait (sleep) until the current time is the given epoch.
             While: Start a while loop.
        Zapateller: Block telemarketers with SIT.
-= 153 Applications Registered =-
</code>


Variants in Exome that affect miRNAs related to Schizophrenia

Question: I have 3 exomes results (VCF files), I would like to study variants (SNP, INDEL) that can affect the miRNAs, which are related to a complex disease (Schizophrenia). What is the best way to assess the effects of variants on miRNAs and how can I link between the damaged miRNAs and Schizophrenia. Can I find a help or advice please?
Comment: I assume that you want a bioinformatician approach, not an experimental one, and that depends on the data you have (or you can obtain). For instance, how do you measure the damaged miRNAs? What data do you already have?
Comment: Do you want effects on miRNAs, or effects on their targets?
Answer: I would run them through the Ensembl VEP, which will tell you which genes they hit and the effect they have on them. Then I would filter by consequence "mature_miRNA_variant", which will find you all the variants in your file that fall in the mature miRNAs. Or you could filter instead by the gene biotype "miRNA" which will tell you if the variants fall anywhere in the miRNAs (which will include the full stem loop structure). I would then export the list of miRNAs and try to find out about their targets using miRbase.


Will covering ring on male 1/4 TRS jack with tape work?

Question: I plan to connect balanced TRS output with unbalanced TS  input and I wonder if instead of cutting the cable and leaving ring floating I could just cover the male jack itself (the ring part that goes to the unbalanced input) with insulation tape. My guess is it should prevent the signal from the ring connect with the sleeve of the unbalanced, TS input.
Comment: Apart from the mechanical difficulty of plugging in the jack without removing the tape, this is unanswerable without details of the internal circuit implementation of the devices.  Things that would work in one case may vary well damage your gear or produce overwhelming mains hum in another.  Questions about the *usage* of products which do not have engineering documentation are off topic here.
Comment: Devices I'm connecting are tascam us2x2 audio interface and guitar pedal Behringer super fuzz. Their documentations doesn't provide information about such connections.
Comment: It's precisely the lack of documentation which makes *usage* questions off topic
Answer: Both are terrible "solution" in that they are no solutions at all.
Conversion from balanced to unbalanced isn't done by isolating conductors, since the "other" side of the balanced signal isn't at a defined potential. That's the whole point of balanced signalling. The potential difference between the two balanced conductors is driven by an output driver, but if you make one float and connect the other, then chances are that he floating one is the one that will be driven, whereas the one that you connect will be more or less at a fixed potential relative to the receiver. "More or less", because capacitive effects will probably make this sound like a high-pass signal.
Instead, properly convert your balanced output to an unbalanced one: A signal transformer would do that.
In a pinch, connecting one of the balanced lines to ground and using the other would probably work, too, but only if the introduced offset is in the range of what the output can drive.
Comment: Output of my audio interface says that balanced line out so yes it's balanced trs. I heard opinions that sometimes you want to leave ring floating and sometimes you want to connect it to sleeve but it depends on the connection and in my case it should be ring left floating. It's all a bit confusing.
Answer: Instead of cutting anything or sticking tape on things, just build yourself a short adapter cable from an inline TRS jack and a TS plug. Then, you can explicitly either wire the R to S or leave it open, as appropriate for your specific signal source. You could even include a small SPST switch that allows you to select either option.
In an ideal world, you'll make sure that both T and R are terminated with equal impedances to S — in which case, the switch becomes unnecessary.
Comment: Do you mean inline TRS jack like the REAN-NYS2203P ? I wonder if disassembling it would be as easy as just cutting through TRS male cable, then TS male cable and connecting them as I want.


Membrane permeate prediction software

Question: I wanted to know if there are any open software or even purchasable software available to predict the permeate quality through a nanofiltration module. I am designing a plant for my final year mechanical engineering undergraduate project and need to show what the results of my setup would be without actually building it.
Comment: Contacting the supplier may help, suggested here: https://engineering.stackexchange.com/a/37320/10902
Comment: Never worked with FEM myself, but I'd start writing down the models as equations to 1) confirm with my thesis supervisor that level of detail is the right one and 2) know exaclty what kind of specs I want from the modelling software.
Answer: We lived in information era. Software here are for any problem. But all sciences software are  very hard to master: today (IMHO) more than 80% physics evaluation base on finite-element method (FEM).
FEM has a lot tensor's equations. Solvation of these equations are frequently make big load to your computer (CPU and sometimes GPU). Because of this, FEM modeling are usually makes without 3D, only in one plane. It is very easy to make mistakes when you setting boundary conditions and equations. Besides - equations (if you all will make correctly) will be solved very-very approximately.
Answering to your question: software - is, but all of these products can to solve very small objective, and very incorrect to calc. Most widely physics software - probably comsol. For example calculation of membrane.  If you haven't 40 000$ to buy it, there are list of FEM software. For chosing program for FEM modeling I offered my students use scientific information finder - scholar.google.com. You have to step by step input request as @software name +  membrane permeate into scholar.google.com and look how many science articles was written with using of this program. After that you need to take a program which more often used by scientific community to your problem.

Membrane permeate prediction software


How accurate is "Business logic should be in a service, not in a model"?

Question: Situation
Earlier this evening I gave an answer to a question on StackOverflow.
The question:

Editing of an existing object should be done in repository layer or in service?
For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:
class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

A comment I received:

Business logic should really be in a service. Not in a model.

What does the internet say?
So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.
Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:

There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.
(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.

To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).
I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.

Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.

Which is reinforced here:

Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.

And here:

The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.

This is a serious contrast to other resources that talk about the Service Layer:

The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.

Or the second answer to a question I've already linked:

At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.

"Solution"?
Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:
class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

Conclusion
All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.
I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?
Is it supposed to form a contract between the controller and the domain?
Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?
Comment: I treat service layer as the place where to put the unavoidable part of transaction script acting upon aggregate roots. If my service layer becomes too complex that signals me that I move in direction of Anemic Model and my domain model needs attention and review. I also try to put the logic in SL which is not going to be duplicated by its nature.
Comment: IMHO, correct OOP-style domain model should indeed avoid "business services" and keep the business logic in the model. But practice shows that it's so tempting to create a huge business layer with distinctly named methods and also to put a transaction (or unit of work) around entire method. It's much easier to process multiple model classes in one business service method than to plan relations between those model classes, because then you would have some tough questions to answer: where is aggregate root? Where should I start/commit a database transaction? Etc.
Comment: Application flow control logic belongs in a controller.
Data access logic belongs in a repository.
Validation logic belongs in a service layer.
A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer.

The service layer contains business validation logic.

repository.http://www.asp.net/mvc/overview/older-versions-1/models-data/validating-with-a-service-layer-cs
Comment: Hi [@Jeroen-Vannevel](https://softwareengineering.stackexchange.com/users/82513), [@Pavel-Voronin](https://softwareengineering.stackexchange.com/users/71962), I would like to ask if there is supposed to be a `_userRepository.SaveUser()` after the `_userRepository.GetUserByName().makePayment()` in the code example above. Thanks!
Comment: I thought that services were part of the Model layer. Am I wrong in thinking that?
Comment: I use a rule of thumb: don't depend on what you don't need; otherwise I may be (usually negatively) impacted by changes on the part I don't need. As a consequence, I end up with lots of clearly defined roles. My data objects contain behavior as long as all clients use it. Otherwise I move the behavior into classes implementing the required role.
Answer: In order to define what a service's responsibilities are, you first need to define what a service is.
Service is not a canonical or generic software term. In fact, the suffix Service on a class name is a lot like the much-maligned Manager: It tells you almost nothing about what the object actually does.
In reality, what a service ought to do is highly architecture-specific:

In a traditional layered architecture, service is literally synonymous with business logic layer. It's the layer between UI and Data. Therefore, all business rules go into services. The data layer should only understand basic CRUD operations, and the UI layer should deal only with the mapping of presentation DTOs to and from the business objects.
In an RPC-style distributed architecture (SOAP, UDDI, BPEL, etc.), the service is the logical version of a physical endpoint. It is essentially a collection of operations that the maintainer wishes to provide as a public API. Various best practices guides explain that a service operation should in fact be a business-level operation and not CRUD, and I tend to agree.
However, because routing everything through an actual remote service can seriously hurt performance, it's normally best not to have these services actually implement the business logic themselves; instead, they should wrap an "internal" set of business objects. A single service might involve one or several business objects.
In an MVP/MVC/MVVM/MV* architecture, services don't exist at all. Or if they do, the term is used to refer to any generic object that can be injected into a controller or view model. The business logic is in your model. If you want to create "service objects" to orchestrate complicated operations, that's seen as an implementation detail. A lot of people, sadly, implement MVC like this, but it's considered an anti-pattern (Anemic Domain Model) because the model itself does nothing, it's just a bunch of properties for the UI.
Some people mistakenly think that taking a 100-line controller method and shoving it all into a service somehow makes for a better architecture. It really doesn't; all it does is add another, probably unnecessary layer of indirection. Practically speaking, the controller is still doing the work, it's just doing so through a poorly named "helper" object. I highly recommend Jimmy Bogard's Wicked Domain Models presentation for a clear example of how to turn an anemic domain model into a useful one. It involves careful examination of the models you're exposing and which operations are actually valid in a business context.
For example, if your database contains Orders, and you have a column for Total Amount, your application probably shouldn't be allowed to actually change that field to an arbitrary value, because (a) it's history and (b) it's supposed to be determined by what's in the order as well as perhaps some other time-sensitive data/rules. Creating a service to manage Orders does not necessarily solve this problem, because user code can still grab the actual Order object and change the amount on it. Instead, the order itself should be responsible for ensuring that it can only be altered in safe and consistent ways.
In DDD, services are meant specifically for the situation when you have an operation that doesn't properly belong to any aggregate root. You have to be careful here, because often the need for a service can imply that you didn't use the correct roots. But assuming you did, a service is used to coordinate operations across multiple roots, or sometimes to handle concerns that don't involve the domain model at all (such as, perhaps, writing information to a BI/OLAP database).
One notable aspect of the DDD service is that it is allowed to use transaction scripts. When working on large applications, you're very likely to eventually run into instances where it's just way easier to accomplish something with a T-SQL or PL/SQL procedure than it is to fuss with the domain model. This is OK, and it belongs in a Service.
This is a radical departure from the layered-architecture definition of services. A service layer encapsulates domain objects; a DDD service encapsulates whatever isn't in the domain objects and doesn't make sense to be.
In a Service-Oriented Architecture, a service is considered to be the technical authority for a business capability. That means that it is the exclusive owner of a certain subset of the business data and nothing else is allowed to touch that data - not even to just read it.
By necessity, services are actually an end-to-end proposition in an SOA. Meaning, a service isn't so much a specific component as an entire stack, and your entire application (or your entire business) is a set of these services running side-by-side with no intersection except at the messaging and UI layers. Each service has its own data, its own business rules, and its own UI. They don't need to orchestrate with each other because they are supposed to be business-aligned - and, like the business itself, each service has its own set of responsibilities and operates more or less independently of the others.
So, by the SOA definition, every piece of business logic anywhere is contained within the service, but then again, so is the entire system. Services in an SOA can have components, and they can have endpoints, but it's fairly dangerous to call any piece of code a service because it conflicts with what the original "S" is supposed to mean.
Since SOA is generally pretty keen on messaging, the operations that you might have packaged in a service before are generally encapsulated in handlers, but the multiplicity is different. Each handler handles one message type, one operation. It's a strict interpretation of the Single Responsibility Principle, but makes for great maintainability because every possible operation is in its own class. So you don't really need centralized business logic, because commands represents business operations rather than technical ones.

Ultimately, in any architecture you choose, there is going to be some component or layer that has most of the business logic. After all, if business logic is scattered all over the place then you just have spaghetti code. But whether or not you call that component a service, and how it's designed in terms of things like number or size of operations, depends on your architectural goals.
There's no right or wrong answer, only what applies to your situation.
Comment: Thank you for the very elaborate answer, you have clarified all I can think of. While the other answers are good to excellent quality as well, I believe this answer tops them all thus I will accept this one. I'll add it here for the other answers: exquisite quality and information, but sadly I'll only be able to give you an upvote.
Comment: I don't agree with the fact that in a traditional layered architecture, service is a synonym to the business logic layer.
Comment: @Aaronaught I wanted to clarify one thing if we have domain objects mapped to db via ORM and there are no business logic in them is this anemic domain model or no ?
Comment: Regarding #4 - even in DDD, how would you load your domain objects from the persistence layer? you probably want to avoid calling your DAL directly from the UI/Controller, so you'd call some service layer (which will probably call the dal, and maybe do some validations before) to get your object, Is this correct?
Comment: @Aaronaught how did you get so smart? Seriously. Best practices books?
Comment: @CodeART: It is in a 3-tier architecture. I *have* seen 4-tier architectures where there is an "application layer" between the presentation and business layers, which is sometimes also called a "service" layer, but honestly, the only places I've ever seen this implemented *successfully* are huge sprawling infinitely-configurable run-your-whole-business-for-you products from the likes of SAP or Oracle, and I didn't think it was really worth mentioning here. I can add a clarification if you like.
Comment: But if we take 100+ line controller (for example that controller accept message - then deserialize JSON object, make validation, apply business rules, save to db , return result object ) and move some logic to one of the that called service method doesn't that help us separately unit test each part of it painlessly ?
Comment: Regarding #3 I find that using Service-classes are useful when building RESTful services where one resource is presented along with related child entities for convenience and minimizing the number of requests needed by clients. Then I only have to combine returned values from different service classes without having to instanciate controllers in controllers.
Comment: @artjom: It *may* make it marginally easier to test, assuming that all of the individual operations that the controller performs aren't *already* abstracted in some way; serialization, validation, repositories, etc. are usually already hidden behind an interface. But that's still ignoring the anemic domain model problem and the fact that this logic should be part of the model, whereas "services" are more typically conceived and maintained as part of the controller layer. The latter still leads to code bloat, and using it to facilitate unit tests can lead to test bloat.
Comment: @artjom: If they have no business logic at all then they're pretty much just DTOs, not domain objects. In fact, in a case like that, I'd really urge you to make them pure DTOs; since they carry no additional semantic information, it's best to keep the nomenclature close to what's actually in the database in order to keep the relationships clear.
Comment: In a tiered architecture you'd still have business objects which implement the business logic, not services.  They'd be models or  roots/entity in ddd.  In fact, any aspects of ddd, tiered and mv-whatever overlap quite a bit.
Comment: @BornToCode - You load domain objects (specifically aggregate roots) using another class of objects called Repositories. Repositories will in turn be invoked by Services.
Comment: @artjom if your domain logic is detached from your domain objects then yes i think what you have there is what martin fowler describes as anemic domain model.
Answer: As for your title, I don't think the question makes sense.  The MVC Model consists of data and business logic.  To say logic should be in the Service and not the Model is like saying, "The passenger should sit in the seat, not in the car".
Then again, the term "Model" is an overloaded term.  Perhaps you didn't mean MVC Model but you meant model in the Data Transfer Object (DTO) sense.  AKA an Entity.  This is what Martin Fowler is talking about.
The way I see it, Martin Fowler is speaking of things in an ideal world.  In the real world of Hibernate and JPA (in Java land) the DTOs are a super leaky abstraction.  I'd love to put my business logic in my entity.  It'd make things way cleaner.  The problem is these entities can exist in a managed/cached state that is very difficult to understand and constantly prevents your efforts.  To summarize my opinion: Martin Fowler is recommending the right way, but the ORMs prevent you from doing it.
I think Bob Martin has a more realistic suggestion and he gives it in this video that's not free.  He talks about keeping your DTOs free of logic.  They simply hold the data and transfer it to another layer that's much more object oriented and doesn't use the DTOs directly.  This avoids the leaky abstraction from biting you.  The layer with the DTOs and the DTOs themselves are not OO.  But once you get out of that layer, you get to be as OO as Martin Fowler advocates.
The benefit to this separation is it abstracts away the persistence layer.  You could switch from JPA to JDBC (or vice versa) and none of the business logic would have to change.  It just depends on the DTOs, it doesn't care how those DTOs get populated.
To slightly change topics, you need to consider the fact that SQL databases aren't object oriented.  But ORMs usually have an entity - which is an object - per table.  So right from the start you've already lost a battle.  In my experience, you can never represent the Entity the exact way you want in an object oriented way.
As for "a service", Bob Martin would be against having a class named FooBarService.  That's not object oriented.  What does a service do?  Anything related to FooBars.  It may as well be labeled FooBarUtils.  I think he'd advocate a service layer (a better name would be the business logic layer) but every class in that layer would have a meaningful name.
Comment: Agree with your point on ORMs; they propagate a lie that you map your entity directly to the db with them, when in reality an entity may be stored across several tables.
Comment: @Daniel Kaplan do you know what the updated link is for the Bob Martin video?
Comment: The is it needed to have a layer that load the DTO from the data layer, conver it to the domain classes, call methods of the domain to do the business logic and finally persist the changes?
Answer: I'm working on the greenfield project right now and we had to make few architectural decisions  just yesterday. Funnily enough I had to revisit few chapters of 'Patterns of Enterprise Application Architecture'.
This is what we came up with:

Data layer. Queries and updates database. The layer is exposed through injectable repositories.
Domain layer. This is where the business logic lives. This layer makes a use of injectable repositories and is responsible for the majority of business logic. This is the core of the application that we will test thoroughly.
Service layer. This layer talks to the domain layer and serves the client requests. In our case the service layer is quite simple - it relays requests to the domain layer, handles security and few other cross cutting concerns. This is not much different to a controller in MVC application - controllers are small and simple.
Client layer. Talks to the service layer through SOAP.

We end up with the following:
Client -> Service -> Domain -> Data
We can replace client, service or data layer with reasonable amount of work. If your domain logic lived in the service and you've decided that you want to replace or even remove your service layer, then you'd have to move all of the business logic somewhere else. Such a requirement is rare, but it might happen.
Having said all this, I think this is pretty close to what Martin Fowler meant by saying

These services live on top of the domain model and use the domain
  model for data.

Diagram below illustrates this pretty well:
http://martinfowler.com/eaaCatalog/serviceLayer.html
Comment: Do yourself a favor and kill your service layer.  Your ui should use your domain directly.  Ive seen this before and your domain invariably becomes a bunch of anemic dtos, not rich models.
Comment: You decided for SOAP just yesterday? Is that a requirement or did you just have no better idea?
Comment: REST won't cut it for our requirements. SOAP or REST, this doesn't make any difference to the answer. From my understanding, service is a gateway to domain logic.
Comment: @AlvaroRodriguezScelza Authorization and authentication are business rules, so yes, you would.  Can I edit a purchase order is a business decision, not a technical one, so your domain should be able to answer that question in a UI independent way.  Http is conceptually part of the UI layer, so no, that happens in your UI layer.
Comment: Absolutely agree with the Gateway. SOAP is (standardized) bloatware, so I had to ask. And yes, no impact on question/answer either.
Comment: Those slides cover the explanation regarding service layer and this graphic above pretty neat: http://www.slideshare.net/ShwetaGhate2/domain-logic-patterns-of-software-architchture
Comment: @Andy but then wouldn't you have security and maybe http requests processing in your Domain Model?
Comment: @Andy I am agree that it is better in the UI to use the domain classes, but I have the doubt if the domain classes has to be responsible to persist the information or only do the business logic? Because sometimes I read domain classes should to be implemented thinking that is only in memory representation, so I understand that it should not concern about persistance.
Comment: @ÁlvaroGarcía I think the domain objects need to handler their own persistence.  The choices are let it do so and it "knows" more than it should, or have some other class handle it which would require breaking encapsulation.  IMO breaking encapsulation is way worse than the DO knowing about the persistence layer.  You tell your DO to "Save" and it figures out what exactly that means (insert, update, delete from DB).  How that's done is all an internal implemenation detail, and you can mock away using DB abstractions (in .Net, IDbConnection, IDBCommand, etc.)
Comment: @ÁlvaroGarcía So stick to those interfaces.  Breaking encapsulation means you need to expose things you normally wouldn't, and those things then typically end up getting used in your UI layer, making refactoring the DOs later harder.  It also means you lose access control (the data layer has to put data into the DO to populate it, for example).
Comment: @Andy I was reading seeing this example in: https://github.com/dotnet-architecture/eShopOnContainers/blob/630cb35cfb974b13332b9dc7164c0c465bee9729/src/Services/Ordering/Ordering.API/Application/Commands/ShipOrderCommandHandler.cs. In this, it goes in my way, the domain only do the core of the logic, when to get the data to update and when to persist the modifications done by the domain, it is responsability of the application layer, in this case, a handler in an ASP proyect.
Comment: @ÁlvaroGarcía Yeah, that example looks like its mapping a business object directly to the DB with EntityFramework... which breaks encapsulation.  Unless somethings changed with EF, you end up having to have your domain model match the DB table structure, and then you will use the same Order object everywhere, even in use cases were certain properties aren't needed/shouldn't be editable, it will be, because the property is also a field on the table.  Only in the most trivial apps have I ever found that to be maintainable.
Comment: @ÁlvaroGarcía Also, having the application layer know about the repository ends in leaky abstractions; the domain should know the "units of work," the application shouldn't.  I
Comment: @ÁlvaroGarcía This is how I suggest structuring things; the domain is built on the Csla framework: https://github.com/MarimerLLC/csla/blob/main/Samples/ProjectTracker/ProjectTracker.BusinessLibrary.Netstandard/ProjectEdit.cs
Comment: @Andy the new versions of EF Core adapts DDD very good, the domain classes doesn't need to mach 1:1 with the tables of the database. With fluent API, shadow properties and another techniques, the domain defines the classes, and it is entity framework who maps the classes from the domain to the tables of the database. Also, EF allows to map value objects. Yo can see some documentation here: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/net-core-microservice-domain-model
Answer: The easiest way to illustrate why programmers shy away from putting domain logic in the domain objects is that they're usually faced with a situation of "where do I put the validation logic?"  Take this domain object for instance:
public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            if(value < 0) throw new ArgumentOutOfRangeException("value");
            this.someProperty = value;
        }
    }
}

So we have some basic validation logic in the setter (cannot be negative).  The problem is that you can't really re-use this logic.  Somewhere there's a screen or a ViewModel or a Controller that needs to do validation before it actually commits the change to the domain object, because it needs to inform the user either before or when they click the Save button that they can't do that, and why.  Testing for an exception when you call the setter is an ugly hack because you really should have done all the validation before you even started the transaction.
That's why people move the validation logic some kind of service, such as MyEntityValidator.  Then the entity and the calling logic can both get a reference to the validation service and re-use it.
If you don't do that and you still want to re-use validation logic, you end up putting it in static methods of the entity class:
public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            string message;
            if(!TryValidateSomeProperty(value, out message))
            {
                throw new ArgumentOutOfRangeException("value", message);
            }
            this.someProperty = value;
        }
    }

    public static bool TryValidateSomeProperty(int value, out string message)
    {
        if(value < 0)
        {
            message = "Some Property cannot be negative.";
            return false;
        }
        message = string.Empty;
        return true;
    }
}

This would make your domain model less "anemic", and keep the validation logic next to the property, which is great, but I don't think anyone really likes the static methods.
Comment: @Flashrunner - my validation logic is definitively in the business logic layer, but is also duplicated in the entity and database layers in some cases.  The business layer handles it nicely by informing the user, etc., but the other layers just throw errors/exceptions and keep the programmer (myself) from making mistakes that corrupt data.
Comment: So what is the best solution for validation in your opinion?
Comment: @ScottWhitlock You think it is a good idea for having the validation logic duplicated or on your case even triplicated?
Comment: @FabianPicone - Having an entity model doesn't preclude some process accessing the database directly, so I want to put a constraint on the database. But allowing someone to create an entity and submit it to the database that violates that constraint is inefficient and creates cryptic error messages, so I duplicate that constraint in my entity model and throw an exception for the entity model user (a programmer). That other programmer can't display my exception message in the user's native language, or doesn't want the overhead of the web service call to see if my logic throws an exception.
Answer: This is one of those things that really depends on the use case. The overall point of a service layer is to consolidate business logic together. This means that several controllers can call the same UserService.MakeHimPay() without actually caring about how the payment is done. What goes on in the service may be as simple as modifying an object property or it may be doing complex logic dealing with other services (i.e., calling out to third party services, calling validation logic, or even just simply saving something to the database.)
This doesn't mean you have to strip ALL logic from the domain objects. Sometimes it just makes more sense to have a method on the domain object do some calculations on itself. In your final example, the service is a redundant layer over the repository/domain object. It provides a nice buffer against requirements changes, but it really isn't necessary. If you think you need a service, try having that do the simple "modify property X on object Y" logic instead of the domain object. Logic on the domain classes tends to fall into the "calculate this value from fields" rather than exposing all fields via getters/setters.
Comment: I find that it really depends on the TYPE of business logic and other factors, such as the language being used. Some business logic doesn't fit on the domain objects very well. One example is filtering/sorting results after pulling them back from the database. It IS business logic, but it doesn't make sense on the domain object. I find that services are best-used for simple logic or transforming the results and logic on the domain is most useful when it deals with saving data or calculating data from the object.
Comment: Your stance in favor of a service layer with business logic makes a lot of sense, but this still leaves some questions. In my post I have quoted several respectable sources which talk about the service layer as a façade void of any business logic. This is in direct contrast with your answer, could you perhaps clarify this difference?
Answer: I think the answer is clear if you read Martin Fowler's Anemic Domain Model article.
Removing the business logic, which is the domain, from the domain model is essentially breaking object oriented design.
Let's review the most basic object oriented concept: An object encapsulates data and operations. For instance, closing an account is an operation that an account object should perform on itself; therefore, having a service layer perform that operation is not an object oriented solution.  It is procedural, and it is what Martin Fowler is referring to when he is talking about an anemic domain model.
If you have a service layer close the account, rather than having the account object close itself, you don't have a real account object. Your account "object" is merely a data structure. What you end up with, as Martin Fowler suggests, is a bunch of bags with getters and setters.
Comment: There is one largely overseen downside of rich models. And that is developers pulling in anything slightly related into the model. Is the state of open/closed an attribute of the account? What about the owner? And the bank? Should they all be referenced by the account? Would I close an account by talking to a bank or through the account directly? With anemic models, those connections are not an inherent part of the models, but are rather created when working with those models in other classes (call them services, or managers).
Comment: @PiotrGolacki pulling too much into one class has the downside of creating god classes and mixing responsibilities, maybe even mixing up domains. I personally found it much easier to work with lightweight entities and tightly coupled service classes that work with one or more of these entities. Each service can take over a specific responsibility or capability. That said, there is always still coupling, but you still want to spread it a bit among multiple classes, or even packages/modules. As to where to draw the line, it's unfortunately more subjective than the pattern of anemic models.
Comment: @HubertGrzeskowiak 1. Why are they downsides? 2. Where do you draw the line?
Answer: How would you implement your business logic in the service layer? When you make a payment from a user, you a creating a payment, not just deducting a value from a property.
Your make payment method needs to create a payment record, add to that user's debt and persist all of this in your repositories. Doing this in a service method is incredibly straightforward, and you can also wrap the whole operation in a transaction. Doing the same in an aggregated domain model is much more problematic.
Comment: He is not creating a payment record though. That's why in his case this business logic should live in the entity. But if he had to create a payment record - you are right, the payment business logic would live elsewhere.
Answer: The tl;dr version:
My experiences and opinions say that any objects which have business logic should be part of the domain model. The data model should likely not have any logic whatsoever. Services should likely tie the two together, and deal with cross-cutting concerns (databases, logging, etc.). However, the accepted answer is the most practical one.
The longer version, which has kind of been alluded to by others, is that there is an equivocation on the word "model". The post switches between data model and domain model as if they're the same, which is a very common mistake. There may also be a slight equivocation on the word "service".
In practical terms, you should not have a service which makes changes to any domain objects; the reason for this is that your service will likely have some method for every property on your object in order to change the value of that property. This is a problem because then, if you have an interface for your object (or even if not), the service is no longer following the Open-Closed Principle; instead, whenever you add more data to your model (regardless of domain vs data), you end up having to add more functions to your service. There are certain ways around it, but this is the most common reason I've seen "enterprise" applications fail, especially when those organizations think that "enterprise" means "have an interface for every object in the system". Can you imagine adding new methods to an interface, then to two or three different implementations (the in-app one, the mock implementation, and debug one, the in-memory one?), just for a single property on your model? Sounds like a terrible idea to me.
There's a longer problem here that I won't go into, but the gist is this: Hardcore object-oriented programming says that no one outside of the relevant object should be able to change the value of a property within the object, nor even "see" the value of the property within the object. This can be alleviated by making the data read-only. You can still run into issues like when a lot of people make use of the data even as read-only and you have to change the type of that data. It's possible that all the consumers will have to change to accommodate that. This is why, when you make APIs to be consumed by anyone and everyone, you're advised not to have public or even protected properties/data; it's the very reason OOP was invented, ultimately.
I think the majority of the answers here, aside from the one marked accepted, are all clouding the issue. The one marked accepted is good, but I still felt the need to reply and agree that bullet 4 is the way to go, in general.

In DDD, services are meant specifically for the situation when you have an operation that doesn't properly belong to any aggregate root. You have to be careful here, because often the need for a service can imply that you didn't use the correct roots. But assuming you did, a service is used to coordinate operations across multiple roots, or sometimes to handle concerns that don't involve the domain model at all...
Answer: The answer is that it depends on the use case. But in most generic scenarios, I would adhere to business logic laying in the service layer. The example that you have provided is a really simple one. However once you start thinking of decoupled systems or services and adding transactional behaviour on top of it you really want it to happen as part of the service layer.
The sources you have quoted for service layer being devoid of any business logic introduces another layer which is the business layer. In many scenarios the service layer and business layer are compressed into one. It really depends on how you want to design your system. You can get the job done in three layers and keep decorating on and adding noise.
What you can ideally do is model services which encompass business logic to work on domain models to persist state.  You should try to decouple services as much as possible.
Answer: The concept of Service layer can be viewed from DDD perspective. Aaronaught mentioned it in his answer, I just elaborate on it a bit.
Common approach there is to have a controller that is specific to a type of client. Say, it could be a web-browser, it could be some other application, it could be a functional test. The request and response formats might vary. So I use application service as a tool for utilizing a Hexagonal architecture. I inject there infrastructure classes specific to a concrete request. For example, that's how my controller serving web-browser requests could look like:
class WebBroserController
{
    public function purchaseOrder()
    {
        $data = $_POST;

        $responseData =
            new PurchaseOrderApplicationService(
                new PayPalClient(),
                new OrderRepository()
            )
        ;

        $response = new HtmlView($responseData);
    }
}

If I'm writing a functional test, I want to use a fake payment client and probably I wouldn't need an html response. So my controller could look like that:
class FunctionalTestController
{
    public function purchaseOrder()
    {
        $data = $_POST;

        $responseData =
            new PurchaseOrderApplicationService(
                new FakePayPalClient(),
                new OrderRepository(),
                $data
            )
        ;

        return new JsonData($responseData);
    }
}

So application service is an environment that I set up for running business-logic. It's where the model classes are called -- agnostically of an infrastructure implementation.
So, answering your questions from this perspective:

Is it a means to simply extract logic from the controller and put it
  inside a service instead?

No.

Is it supposed to form a contract between the controller and the
  domain?

Well, one can call it so.

Should there be a layer between the domain and the service layer?

Nope.

There is a radically different approach though that totally denies the use of any kind of service. For example, David West in his book Object Thinking claims that any object should have all necessary resources to do its job. This approach results in, for example, discarding any ORM.
Comment: This answer pretty exemplary explains  2 **good reasons** for having a _service abstraction_  (e.g. class, module): #1 unit testable ; #2 reusability. Both can be changed and reused isolated from the entity (without touching it).
Answer: In MVC Model is defined as the business logic.  Claiming it should be somewhere else is incorrect unless he is not using MVC. I view service layers as similar to a module system.  It allows you to bundle up a set of related functionality into a nice package.  The internals of that service layer would have a model doing the same work as yours.

The model consists of application data, business rules, logic, and functions.
  http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Answer: For the record.
SRP:

Model = Data, here goes the setter and getters.
Logic/Services = here goes the decisions.
Repository/DAO = here we permantenty store or retrieve the information.

In this case, is OK to do the next steps:
If the debt will not require some calculation:
userObject.Debt = 9999;

However, if it requires some calculation then:
userObject.Debt= UserService.CalculateDebt(userObject)

or also
UserService.UpdateDebt(userObject)

But also, if the calculation is done in the persistence layer, such a store procedure then
UserRepository.UpdateDebt(userObject)

In this case, i we want to retrieve the user from the database and to update the debt then, we should do it in several step (in fact, two) and it's not requires to wrap/encapsulate it in a service's function.
User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)

And if it requires to store it then, we can add a third step
User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)
UserRepository.Save(userobject);

About the solution proposed
a) We shouldn't be afraid to left the end-developer to write a couple of instead of encapsulate it in a function.
b) And about Interface, some developers love interface and they are fine but in several cases, they aren't need at all.
c) The goal of a service is to create one without attributes, mainly because we can use Shared/Static functions. It's also easy to unit test.
Comment: What kind of Sentence is `"We shouldn't be afraid to left the end-developer to write a couple of instead of encapsulate it in a function.`"? I can only quote Lewis Black "if it weren't for my horse I wouldn't have spent that year in college".
Comment: how does this answer the question asked: _How accurate is "Business logic should be in a service, not in a model"?_


Best practice and starting point for designing a decomposable score metric

Question: I need to generate a 'score' metric (out of 100) to summarise a number of other features, and to allow comparison between sets.
Each feature in turn will be some numeric value (possibly another derived score) .
My instinct is to just scale each feature to a consistent size, multiple it by a weight factor, add them all together and then scale down to 100.
My first concern is that I expect this to experience something like regression to the mean. everything will wash out and look very average. How can i design a score to ensure meaningful differentiation.
Secondly, I would like to be able to decompose the score and speak to which sub components have impacted it the most or which are the lowest hanging fruit for improvement. This is easy enough with the simple weighting approach but i feel would be lost with more complex modelling.
Is there a normal name for this type of work (to allow me to research) or any know best practices or reading? Any general pointers?
Thank you
Answer: That is commonly called an index, an accumulation of scores from a variety of individual items. Creating indexes is very common in economic and financial fields (e.g., Consumer Purchasing Index and Standard & Poor's 500).


How to prove a Theorem numerically

Question: Setting: I have a function $f$ of 4 real variables $(x,y,w,z)$ in $\mathbb R^4$. The function $f$ satisfies $f(0,y,w,z)=1$ and $-I \preceq \mathsf{H}f(x,y,w,z) \preceq I$, $\forall x,y,w,z \in [0,1]$, where $\mathsf{H}$ denotes the Hessian operator. Otherwise, the function $f$ does not have any special structure in any of the variables (i.e. no monoticity, convexity, etc). (The analytical expression of $f$ is quite involved and very hard to study analytically.)
Goal: I want to show that $f(\mathbf{v})\leq 1$ for all $\mathbf{v}\triangleq(x,y,w,z)$ in $[0,1]^4$, by showing that $\partial f /\partial x(\mathbf{v})\leq0$, for all $\mathbf{v}$ in $[0,1]^4$.
Since $f(0,y,w,z)=1$, for all $y,w,z\in [0,1]^3$, showing that $\partial f /\partial x(\mathbf{v})\leq0$, for all $\mathbf{v}$ in $[0,1]^4$, will certainly get me what I want. However, the expression of $\partial f/\partial x$ is very involved making it very hard to show any inequality analytically.
Desired Strategy: Numerical optimization suggests that $\partial f /\partial x(\mathbf{v})\leq -0.1$. Given that I also know that $-I \preceq \mathsf{H}f \preceq I$, my strategy was to evalutate $\partial f /\partial x(\mathbf{v})$ on a fine enough grid in $[0,1]^4$ and then invoke Taylor's Theorem to argue that $\partial f /\partial x (\mathbf v)<0$, for all $\mathbf{v} \in[0,1]^4$. Would this be an acceptable proof?
Side Note: The result that I am chasing will ultimately be part of a Theorem in a research article (my field is maths/computer science). And so I want to know if my strategy above for proving the result is still ``acceptable'' even though it relies on the numerical evaluating of a function (in this case $\partial f/\partial x$) on a (large) set of grid points.
Answer: Conterexample: $f(x,y,z,w):=1+\frac{1}{2}x^2.$   Then $f(0,y,z,w)=1$ and $\partial^2 f /\partial x^2=1.$
But $f(1,0,0,0,)=\frac{3}{2}>1.$
Comment: Your example does not satisfy ∂/∂()<0. As I explain in the description of my question I can verify (numerically) that ∂/∂() <-0.1.

How to prove a Theorem numerically


Definition of inner product for vector spaces over arbitrary fields

Question: Is there a canonical definition of the concept of inner products for vector spaces over arbitrary fields, i.e. other fields than $\mathbb R$ or $\mathbb C$?
Answer: As Qiaochu wrote, the answer to the question is "not really, but..." Let me amplify on the "but" part.
Positive-definiteness inherently requires an ordering on your field.  Conversely, if you have an ordered field, then the theory of inner products goes through verbatim.  (The ordering does not have to be Archimedean, so this indeed gives lots more examples.)
Let's assume that you have a field K of characteristic different from 2 which cannot be ordered: by a theorem of Artin-Schreier, this is equivalent to -1 being a sum of squares in the field.  Then you don't have "positive definiteness".  What is more, the "standard inner product"
$$q(x_1,...,x_n) = x_1^2 + ... + x_n^2$$
will be isotropic for sufficiently large $n$, i.e., there will exist nonzero vectors
$v = (x_1,...,x_n)$ such that $q(v) = 0$.  For instance, if K is finite, this occurs as soon as $n \ge 3$.
Let me remark that "isotropic inner products" are not inherently worthless. I have a preliminary version of a wonderful book, "Linear Algebra Methods in Combinatorics" by Laszlo Babai, which indeed makes nice use of the above inner product over finite fields, even in characteristic 2.
(See https://web.archive.org/web/20100205064709/https://cs.uchicago.edu/research/publications/combinatorics.  Unfortunately it seems that the book never came to fruition.  I got my copy more than 10 years ago when I took an undergraduate course in combinatorics from Babai.)
On the other hand, to any quadratic form over a field K of characteristic not 2, you can associate a symmetric bilinear form.  See (among infinitely other references) p. 2 of
http://alpha.math.uga.edu/~pete/quadraticforms.pdf
As above, it is plausible that an algebraic substitute for "inner product space" is "vector space endowed with an anisotropic quadratic form", i.e., a regular quadratic form without nonzero vectors v for which $q(v) = 0$.  Witt discovered that you can do a lot of "geometry" in this case: especially, he defined reflection through the hyperplane determined by any anisotropic vector: see (e.g....) pp. 17-18 of the above reference.  More is true here than is included in my introductory notes: for instance the orthogonal group of an anistropic quadratic form has the "compactness properties" of the standard real orthogonal group O(n) (that is, it contains no nontrivial split subtorus).
Comment: Isotropic subspaces give rise to point-line geometries called polar spaces: https://en.wikipedia.org/wiki/Polar_space, and thus to several other interesting structures like strongly regular graphs (collinearity graph of almost every polar space is strongly regular), some extremal graphs, perfect codes, etc. See http://www.maths.qmul.ac.uk/~pjc/pps/, and Simeon Ball's new book: http://www.cambridge.org/hr/academic/subjects/mathematics/discrete-mathematics-information-theory-and-coding/finite-geometry-and-combinatorial-applications.
Answer: No.  The axiom that fails is positive-definiteness, which doesn't mean anything for an arbitrary field.  But one can still define symmetric bilinear forms.
Comment: The ordering needs to be compatible with the field operations, but yes, you can do that.
Comment: Thank you. What about fields which are also ordered sets?
Comment: Just a trivial remark: for the quaternions, which you can think of as a "skew" field, you cannot define bilinear forms, but only  sesquibilinear forms.  At any rate, the important property is not so much bilinearity as non-degeneracy.
Comment: I feel like there's a way to do this for fields of characteristic zero, or if not, at least real closed number fields and their algebraic closures.
Answer: Several approaches have been tried to conceive a well-behaved "inner product" on non-Archimedean valued fields. Let's see some examples:
Option 1:
    Let $\lambda\mapsto\lambda^*$ be a field automorphism of order $2$ defined on $K$. Let $E$ be a $K$-vector space. An inner product is a map $\langle,\rangle:E\times E\to K$ such that:

$\langle x,x\rangle\neq 0$ for all $x\neq 0$, $x\in E$.
$\langle x,y\rangle=\langle y,x\rangle^*$ for all $x,y\in E$.
$x\mapsto \langle x,y\rangle$ is linear for each $y\in E$.

Note that if axioms 1,2,3 are assumed in the complex case then either
$\langle ,\rangle$ or $-\langle ,\rangle$ is positive definite.
It is proved in this book1 that $\langle ,\rangle$ satisfies the Cauchy-Schwartz inequality, it induces a norm, $\langle ,\rangle$ is continuous in the topology induced by the norm and more. The down side is that there is no infinite-dimensional Hilbert-like spaces over $K$.
Option 2: A similar approach was taken in the paper: A non-Archimedean inner product, L. Narici, E. Beckenstein, Contemporary Mathematics, AMS, vol.384, pp.187--202 (2005). There, the "inner product" $\langle ,\rangle$ is defined by the axioms:

$\langle x,x\rangle\neq0$ whenever $x\neq0$.
$x\mapsto \langle x,y\rangle$ is linear for each $y\in E$.
$|\langle x,y\rangle|^2\leq|\langle x,x\rangle||\langle y,y\rangle|$.

This map defines the norm $\|x\|=|\langle x,x\rangle|^{1/2}$.
Also, it is proved that in $C_0$, the sup norm is induced by $\langle x,y\rangle=\sum x_ny_n$
(for $x=(x_n)_n$ and $y=(y_n)_n$ in $C_0$) if and only if the residue class field of $K$ is real closed.
Subsequent study of operators in $C_0$ over an ordered non-Archimedean valued field was developed in here2, here3, here4 and here5.
As in the option 1, in this case there are no infinite-dimensional Hilbert-like spaces. This is shown in this other paper6. However, when the valuations take values in ordered groups rather than the real numbers, the situation changes as we see in the following.
Option 3: It is possible to conceive Quadratic spaces over Krull valued fields. Under certain conditions, it is even possible to have infinite-dimensional Hilbert-like spaces.
For this topic, in particular, I recommend the papers:
a. On a class of orthomodular quadratic spaces, H. Gross, U.M. Künzi - Enseign. Math, 1985.
b. Banach spaces over fields with a infinite rank valuation - [H.Ochsenius A., W.H.Schikhof] - 1999
c. After that see: Norm Hilbert spaces over Krull valued fields - [H. Ochsenius, W.H. Schikhof] - Indagationes Mathematicae, Elsevier - 2006

1Perez-Garcia, C.; Schikhof, W. H. Locally convex spaces over non-Archimedean valued fields
2J. Aguayo and M. Nova: Non-Archimedean Hilbert like spaces, Bull. Belg. Math. Soc. Simon Stevin, Volume 14, Number 5 (2007), 787-797.
3 José Aguayo, Miguel Nova, and Khodr Shamseddine: Characterization of compact and self-adjoint operators on free Banach spaces of countable type over the complex Levi-Civita field, Journal of Mathematical Physics 54, 023503 (2013); https://doi.org/10.1063/1.4789541
4 José Aguayo, Miguel Nova, and Khodr Shamseddine: Inner product on $B^*$-algebras of operators on a free Banach space over the Levi-Civita field, Indagationes Mathematicae, Volume 26, Issue 1, January 2015, Pages 191-205; https://doi.org/10.1016/j.indag.2014.09.006
5 José Aguayo, Miguel Nova, and Khodr Shamseddine: Positive operators on a free Banach space over the complex Levi-Civita field, p-Adic Numbers, Ultrametric Analysis and Applications, April 2017, Volume 9, Issue 2, pp 122–137; https://doi.org/10.1134/S2070046617020029
6 M. P. Solèr: Characterization of hilbert spaces by orthomodular spaces, Communications in Algebra, Volume 23, 1995 - Issue 1,  Pages 219-243; https://doi.org/10.1080/00927879508825218
Comment: Surely you want $(-)^*$ to square to the identity, not have order 2, right?
Comment: @DavidRoberts, [re](https://mathoverflow.net/questions/6701/definition-of-inner-product-for-vector-spaces-over-arbitrary-fields#comment1174567_288568), actually, in the description of unitary groups over arbitrary fields (which one might reasonably hope to correspond to "inner products"), one usually does require that the involution be "of the second kind", i.e., genuinely of order $2$, not just of order dividing $2$.
Comment: @LSpice but then this definition rules out taking K to be the reals, which definitely works here! The question is not about unitary groups, in any case.
Comment: @DavidRoberts, [re](https://mathoverflow.net/posts/comments/1174580), but the question *is* about inner products, which one might expect, [Erlangen](https://en.wikipedia.org/wiki/Erlangen_program)-ly, to correspond to unitary groups.  I would argue that an inner product on a real vector space is more properly viewed as a symmetric bilinear form, and its positive definiteness as a manifestation of the corresponding orthogonal group being anisotropic.  But, of course, only @Chilote can say for sure what they meant.
Comment: @LSpice when I studied from the mentioned references, I assumed they meant $(\lambda^*)^*=\lambda$ for every $\lambda\in K$. In this way the proofs made sense. I am not familiar with another interpretation of "automorphism of order 2".
Comment: [Re](https://mathoverflow.net/questions/6701/definition-of-inner-product-for-vector-spaces-over-arbitrary-fields/288568#comment1174710_288568), the identity automorphism $(-)^* = (-)$ has order $1$, but satisfies your condition.  For an automorphism to have order $2$, it must square to the identity, *but not itself be the identity*.
Comment: @LSpice, oh I see. Well, in that case, I am sure the authors meant $(\lambda^*)^*=\lambda$ for every $\lambda\in K$, not just $(-)^*$ of order 2.
Answer: To get an analogue of hermitian inner products, generalizing the inner product of complex vector spaces, one usually considers fields endowed with an involution (just as complex conjugation) and uses that in the more or less obvious way. This is how one can define the unitary groups, for example; see Dieudonné's Sur les groupes classiques.


Get a matrix with absolute values in PETSc

Question: Is there any function to create or change a matrix, to have $A_{ij} = \text{abs}(A_{ij})$ in PETSc? If possible it should work with MPIAIJ matrices, not only local.
Answer: Though this question is about a particular functionality of an individual library, I stumbled upon the same problem some time ago.
As far as I know, there is no ready matrix function in PETSc (3.8.3) that will do it for you right out-of-the-box. I was surprised not to find a solution back a couple of years ago and now, considering the existence of such functions as:

VecAbs that will do exactly what you want, but for vectors only
MatImaginaryPart, MatRealPart, and MatConjugate which will perform $A_{ij}=\Re(A_{ij})$, $A_{ij}=\Im(A_{ij})$, and $A_{ij}=A^*_{ij}$, respectively.

Considering that element-wise Re, Im, and conjugation operations on matrices are supported, I would assume that all the necessary building blocks for the MatAbs are there, but not formally coded up.
From MatRealPart subroutine source code, the following excerpt is doing the job
(*mat->ops->realpart)(mat);

The list of supported and propagated operations on matrices is stored in include/petscmat.h in MatOperation typedef. Technically, you can code up your own operation and propagate it to the datatypes you require (maybe, even by using custom user matrix MatOperation and MatShellSetOperation). However, the question is if such a development is worth the required time and pain.


Migrating MariaDB from Stretch to Buster

Question: I am currently in the process of migrating my ownCloud from my old Pi 3B to a Pi 4B.
On the 3, I made a backup of my MariaDB with mysqldump:
mysqldump --single-transaction --routines --triggers --all-databases | gzip > backup_db.sql.gz

Here is the version info from that file:
-- MySQL dump 10.16  Distrib 10.1.38-MariaDB, for debian-linux-gnueabihf (armv7l)
--
-- Host: localhost    Database:
-- ------------------------------------------------------
-- Server version   10.1.38-MariaDB-0+deb9u1

Now on my Pi 4, I tried to restore this with
gunzip <backup_db.sql.gz | mysql

Unfortunately, this gave the following error:
ERROR 1805 (HY000) at line 869: Column count of mysql.proc is wrong. Expected 21, found 20. The table is probably corrupted

I realize the mismatching MariaDB versions may be a problem, but I can't install an earlier version on the Pi 4:
apt list -a mariadb-server
Listing... Done
mariadb-server/stable,now 1:10.3.17-0+deb10u1 all [installed]

According to Install MariaDB 10.2 on Raspbian Stretch, installing 10.3 on the Pi 3 is probably also not an option.
I also found this in the MariaDB/mysqldump documentation:

mysqldump from an earlier MariaDB release cannot be used on MariaDB 10.3 and beyond

How do I resolve this?
Answer: I resolved my problem by creating a new database dump that only includes the owncloud database:
mysqldump --single-transaction --routines --triggers owncloud

Of course, any additional databases need to be migrated separately.


Is there any quality difference between PNG vs BMP image formats?

Question: I have just learned that PNG is a lossless image format while BMP can be both uncompressed or lossless format. Should there be a quality difference between these two? If not, does it mean that other lossless formats like TIFF, JPEG2000 and PNG offer the same quality as BMP?
Comment: JPEG2000 is **not always lossless**. You can use it lossless, but mostly, it's used to compress images in a lossy way.
Answer: BMP is both uncompressed and lossless. PNG is compressed but lossless. Thus, with a lossless format the only visible difference is the file size. I'd recommend using PNG over BMP unless you can't for compatibility reasons.
Comment: BMP does support alpha channel (transparency) [since Windows 95](http://en.wikipedia.org/wiki/BMP_file_format#DIB_header_.28bitmap_information_header.29). Just that Paint in Windows does not save the file with transparency (for compatibility reason?), which I think *might* have been the source of misconception.
Comment: That is correct. The pixels will be 1:1.
Comment: PNG also supports transparency while BMP doesn't.
Comment: You said _visible_ difference. Should there really be any difference except for file size?
Answer: There's no quality difference between BMP & PNG format (except PNG is compressed using deflate algorithm).
BMP8 can be compressed using RLE (run-length-encoding) algorithm, but BMP16/24/32/64 doesn't support compression yet.
BMP32 support alpha channel just like PNG32 support transparency.
Answer: No difference in quality, both standards are lossless. BMP uncompressed takes more space, but when compressed (e.g. when put in a .zip or .7z file) BMP can be better.
Having done some experiments, I saved a photo in BMP and in PNG, and compressed both files. (.zip) The BMP was 1.8% bigger, but that would vary between photos.
If you are compressing photos, it makes no difference.
However simple picture, such as a drawing you did in paint, or a diagram, will compress much better with .bmp rather than .png.
I again, tested this. I did a logo in paint (similar to a ford logo) and compressed it with 7zip.
Uncompressed, the png was 136kb, the bmp 1.7 MB.
Compressed, the png was ~100kb and the bmp was 18kb.
If you want to compress pictures, save in .bmp. If not, use .png.
Both when compressed whooped jpeg btw.
Comment: I confirm this. Illustration images tend to compress so much better in BMP than PNG. Difference is like day and night in some occasion, 10GB of images could be compressed to mere 100MB while PNG couldn't even reach under 95% compression ratio.


filesystem from ISO

Question: Installation of Linux yields the filesystem which consists of folders like bin, boot, dev etc.
When one extract a iso file, files like autorun.inf, preeseed, dists, install , pics etc appears.
How can one see the Linux filesystem.
Answer: If you want to get the Ubuntu file system from the Ubuntu ISO image you might want to look inside (archive) file casper/filesystem.squashfs from the Ubuntu ISO image.
Un-archiving this file on the target file system is actually part of the Ubuntu installation procedure (performed by the Ubuntu installer, which does other things as well so in the end one can get a running system).
Hope this helps!
Answer: You download the ubuntu*.iso image from the community, then mount that iso image in your system. Open the mounted directory you can see the Hierarchy of the iso image tree-like boot, casper, dists, EFI and pool etc. The casper/filesystem.squashfs contain all directories(usr,lib,sys and dev etc). once you unsquashfs the file-system using the below command then you can see what you expected.
$ unsquashfs -d path_for_where_the_file_unsquasfs path_for_filesystem.squashfs
or double click the downloaded iso image it's automatically mounted then you continue unsquashfs steps.

filesystem from ISO


What to do when request is sent to server and while waiting for response internet connectivity lost?

Question: I am sending a huge amount of data to server. Now while I have sent the data and waiting for server response, suddenly my android device gets internet connection lost.
So what I used to do is, showing an alert dialog of connection lost, but at server side the data was already processed and it updated somewhere e.g. on any URL. But my android phone does not know this as it did not get response ever. How to resolve it. Whether it could be done on server side or on android itself How? How server would know that android phone is not going to listen the response?It may be client-server communication optimization perspective.
Comment: How much data are we talking about? Gigabytes?
Comment: Not much 7-8 MB around, but server response time is too long, and uploading rate from phone is around 128 KB/S. I am not talking about data size but connection problem.
Answer: This is a fairly common problem with asynchronous transactions, and falls into several parts.

How do both sides know that the transaction request has been successfully received?
How do you resend a transaction request that the client believes has not been received properly?
How does the server detect repeat requests from the client when the server successfully received the first request?
How does the client know where to get the transaction results from?

The great thing about HTTP is that its fairly easy to solve all of these issues.
Imagine a URL structure like this:

POST http://my.server.com/application/engine/queue
GET  http://my.server.com/application/engine/results?jobid=43425

Using HTTP post to send a request to the server, using a unique client request id - and have the server respond with the job ID. From a clients perspective, if this response does not occur, then the request needs to be resent.  From a servers perspective client request id's need to be cached for a few minutes, in-case the client sends duplicated requests. Duplicated requests are handled simply by returning the same job ID to the client.
The client gets the results of the request from the results URL. This call can be repeated as often as needed to get the results. If its called before the results are available, then the response could be a NO-CONTENT response so the client knows that the server recognises the job id but does not have the content yet.  If the job id is not recognised then NOT-FOUND is the appropriate response.
End result is that the client can always make a sensible action when the network is lost and recovered, and likewise the server can always process requests from the client sensibly
Comment: That, or simply doing a short request asking for a transaction ID, then several requests adding data to the transaction (you could split the transfer into smaller chunks here, to get partial acknowledgements), then a final "commit" request. You can then have different timeouts for completely empty transactions (client most likely did not receive ID), partially uploaded transactions, and results (if the client did not receive the results, it may retry the "commit" request).
Comment: That is also handled. The "commit" transaction is small and uses the transaction ID, so it can be reissued cheaply without retransmitting the data, and the server can either start processing, or return the result from the earlier invocation. This is very similar to what you are suggesting; the difference is that I have a separate request to create the job ID, so I have an additional synchronisation point, so the client can know whether the job already exists without retransmitting the full request.
Comment: That would manage the situation where the connection was being lost during the transmission of the request. The question as asked is talking about connection lost after the data was sent, but before processing the request has completed.
Comment: yeah, that makes sense.
Comment: This way, if a transaction contains partial data on the server, I know that a client exists that knows this ID and tries to complete the transaction, so I can keep the partial state and offer to resume transmission halfway, minimizing bandwidth requirements and removing the need to compare request content to find duplicates.
Comment: The client request ID is not a transaction ID. Its generated anew each time for each message, except when a client needs to resend the same message.  That's how the server knows its got a duplicate message, not by doing a full comparison
Comment: Ah, so your client side IDs are globally unique, not merely sequence numbers to allow command queueing between server and client? In that case, you can use the client ID and a counter to split the transaction across multiple requests, avoiding the round trip at transaction start; my suggestion to split the transfer across multiple requests remains.
Comment: Use Case: I typically find out that WiFi is disabled when an app takes long to respond, at which point I enable WiFi to save money. A few seconds later, connection switches to a public WiFi. Your next request is redirected to the login page. I find out that I cannot be bothered, and turn off WiFi again. Upon reconnecting to the mobile network, your app should attempt to resume the transfer rather than restart from scratch.
Answer: This falls under the basics of protocol communication. A transaction has been requested by the Android client, and the Server has to perform the transaction. If the transaction is dependant upon the Android client acknowledgment than this is call ACK/NAK communication.
ACK (acknowledgment) and NAK (negative-acknowledgment) are used to tell the other-side the result of a request.
What you are asking about is a type of handshaking exchange between the client and server, and it can be performed with a basic ACK/NAK exchange.
Here is an example of Android uploading a file with two way acknowledgment.
Android -> upload files -> Server
Android <- ACK #id <- Server
Android -> ACK #id -> Server

In the above example I've added a #id unique identifier for the transaction. The server should receive the files, create a transaction record and send that as the response back to Android. Android should then follow with an acknowledgement of that transaction (or alternatively a NAK for a rejection).
Here is an example of an Android disconnecting during the handshaking.
Android -> upload files -> Server
Android <- ACK #id <- Server
/** no ACK response **/

In the above example the Server has accepted the uploaded files and sent a #id ACK response back to Android, but Android never responds with an ACK. The Android device has failed to complete the handshaking. It's up to you to decide how the Server should handle this. Destroy the transaction, keep the transaction and wait for the Android device to return later or complete the transaction anyway.
The Server can assume that since the device did not respond with ACK. That the Android device did not update it's internal state to indicate that the upload was successful. I would discard the transaction and allow the device to repeat it in the future.


Bath room exhaust fan not working. The light is working on a separate switch right next to the fan switch

Question: I tested the fan and there is power. However the switch to the fan has no power. The light switch next to the fan switch is working.  Could there be a problem between the exhaust fan and the switch to block the power?
Comment: Can you post a photo of the inside of the switch box please?
Comment: Can you post another photo, looking into the back of the box please?
Comment: Is the broken switch the one on the right?
Comment: More information is needed. Is this a new install or is this a previously installed unit that was functioning and now is inexplicably not functioning. Please provide as much information as possible to get an informed answer.
Answer: I have repaired dozens if not hundreds of bathroom fans, flick the fan if it doesn't spin for at least 5 seconds it needs lubricant, most are sleeved bearings and some wd40, or 3 in 1 oil may bring it back to life , I get slammed for suggestions of wd40 but it works to free things up in oil light bearings, a few drops of 15 to 40 weight motor oil will also work but it may take longer. I have got vent fans going many times with light oil or penetrating oil and even wd40 has lasted for a year or2 but a light oil is better


What is the chemical formula for snake venom?

Question: I haven't been able to get this question answered through the internet so far, so I was looking for a more professional angle in which this question can be answered.
Comment: Snake venom is almost entirely made up of proteins...thousand of different proteins, which means thousands of different chemical formulae.
Comment: In cobras its a protein unimaginatively its called cobratoxin. (You can see x-ray structures on web). The active site has been studied and shown (by time resolved fluorescence; it has a singe trp) to be rather rigid and by being so mimics the geometry of curare type molecules.
Answer: There are several kinds of snake venom, and as far as I know they are all complex enzymes: it means that they are complex macromolecules, made by amminoacids (these, "small molecules") bound with peptide bonds.
For enzymes and proteins, the chemical nomenclature is quite impratical: it's way easier to define the enzyme by giving the names of the amminoacid chain it's made of.
For instance, for crotamine the amminoacid sequence is: YKQCHKKGGHCFPKEKICLPPSSDFGKMDCRWRWKCCKKGS—G
Answer: The wikipedia article of snake venom clearly defines the composition of snake venom. To prevent being a wall of text, I arranged them in points and bolded the chemicals.

Proteins constitute 90-95% of venom's dry weight and they are responsible for almost all of its biological effects. Proteins are
  toxins, neurotoxins in particular, as well as nontoxic proteins (which
  also have pharmacological properties),
Enzymes (molecular weight 13-150 KDa) make-up 80-90% of viperid and 25-70% of elapid venoms: digestive hydrolases, L-amino acid
  oxidase, phospholipases, thrombin-like pro-coagulant, and
  kallikrein-like serine proteases
  and metalloproteinases (hemorrhagins), which damage vascular
  endothelium.
Polypeptide toxins (molecular weight 5-10 KDa) include cytotoxins, cardiotoxins, and postsynaptic neurotoxins (such
  as α-bungarotoxin and α-Cobratoxin), which bind to acetylcholine
  receptors at neuromuscular junctions.
Compounds with low molecular weight (up to 1.5 KDa) include metals, peptides, lipids, nucleosides, carbohydrates, amines, and oligopeptides, which inhibit angiotensin converting enzyme (ACE) and
  potentiate bradykinin (BPP). Inter- and intra-species variation in
  venom chemical composition is geographical and ontogenic.
Phosphodiesterases interfere with the prey's cardiac system, mainly to lower the blood pressure.
 Phospholipase A2 causes hemolysis by lysing the phospholipid cell membranes of red blood cells.
Amino acid oxidases and proteases are used for digestion. They also triggers some other enzymes and is responsible for the yellow
  colour of the venom of some species.
Hyaluronidase increases tissue permeability to accelerate absorption of other enzymes into tissues.
Some snake venoms carry fasciculins, like the mambas (Dendroaspis), which inhibit cholinesterase to make the
  prey lose muscle control.
Comment: While I appreciate this answer, the list format that was necessarily adopted, as well as the inevitable brevity of each entry, make me doubt the usefulness of the question.
Answer: Snake Venom is a mixture of chemical compounds. It certainly doesn't have "a chemical formula". Your question is similar to one asking "What is the color of a car?" Just like cars come in a wide range of colors, venoms have a wide variety of recipes (mixtures) and even snakes of the same species may have different compositions of their venoms.
More details are easily available, and easily found on-line. For example: https://en.wikipedia.org/wiki/Snake_venom and https://en.wikipedia.org/wiki/Venom#Snakes. For more specific information, you should A. Determine the formal taxonomic name of the species you are interested in and then B. Use Google Scholar or some other search engine which includes the academic literature. Many of these articles won't be satisfactory, I'd guess, because they generally address specific ingredients of the "witch's brew". But you'll most likely find some older articles which are broader. (Many of which will be behind pay-walls, unfortunately. You may have to visit the nearest public university for "free" access.


Options for one-time login browser session

Question: I always log out from all my accounts on websites when leaving the computer when using other computers than my own, for instance a public computer. This means I have to log in to several accounts every time I switch computer. What are the options to restore all logins with just one log on? Is there any browser that support this? or do I have to run a remote desktop to my home computer?
Comment: Public computers may not give you the ability to use different browsers (even if they had the capability you ask about). You have, however, added an excellent point regarding Remote Desktop. Although not all public computers will allow this, either (ports can be blocked easily), you may be able to use a standalone software that can "Remote Desktop" over HTTPS - I'm unsure whether, say, LogMeIn or TeamViewer have standalone applications... You could then, in theory, have the application and your home IP on a USB stick and run the portable app?
Answer: Let's look at this from a different perspective: Why do you have to log in an account in the first place? Because the site want's to ensure you are the legit owner of the account.
What you are trying to achieve is some kind of sharing your account credentials over several computers. This would e.g. involve copying all your session cookies from different websites to the other computer.
Apart from the fact that depending on the website this would not even work because some sessions are bound to your IP-Adress, this is in general not a very good idea for multiple reasons:

How can the browser (most likely an Add-On) know, which data/cookies/session/login information it has to copy? It can't - every site uses different mechanisms. Such a tool could only support specific websites, or it cannot be sure it copies all necessary information
The tool you use must be installed on both computers, so also on a potential public PC and it needs a server side synchronization or direct access to your home computer. In both variants you give your most important data - login/session information - out of your hands
How should the website handle the fact, that you are using the same session from multiple computers/locations at once? Many sites have mechanisms to prevent exactly that, as this is the common case when hacking/stealing sessions
How can you be sure that no data is left behind if you don't logout from your accounts (otherwise you couldn't restore you logins)?
...

This list could be extended much further.

So I have 2 suggestions for you:

Use a secure remote desktop or ssh or whatever connection to you home PC to ensure that your session cookies etc. never leave your private computer
Or, what I would propose: Use a password manager like KeePass, which dramatically helps in remembering your credentials and makes the login to multiple accounts a negligible effort

Even if there would be a browser supporting such a functionality, I would be very careful in using it. Think about the reasons for having accounts and the importance of logging out in the first place and then think about what you want to achieve with such a single sign-on one once more. I also suggest reading the Wikipedia article about SSO.


Disable Incognito mode in google chrome

Question: Can I disable incognito mode in google chrome? We have Windows 8 home version. I was able to do it on an older computer, but can't find the answer for this newer version.
Comment: Hi, and wishing you a belated welcome to Super User! Why do you want to disable incognito mode?
Answer: This answer to that question was found here
I paste below the relevant one.
You will need to add an entry to the windows registry in order to disable it.

simply add the following dword entry in the registry as this link describes
  http://dev.chromium.org/administrators/policy-list-3#IncognitoModeAvailability
Windows registry location:
  Software\Policies\Google\Chrome\IncognitoModeAvailability
Supported on: Google Chrome (Linux, Mac, Windows) since version 14
  Google Chrome OS (Google Chrome OS) since version 0.14
Description: Specifies whether the user may open pages in Incognito
  mode in Google Chrome. If 'Enabled' is selected, pages may be opened
  in Incognito mode. If 'Disabled' is selected, pages may not be opened
  in Incognito mode. If 'Forced' is selected, pages may be opened ONLY
  in Incognito mode.
  0 = Incognito mode available.
  1 = Incognito mode disabled.
  2 = Incognito mode forced.
OR have this reg file do it for you
  http://www.mediafire.com/file/dylcbs7aqpjc9vl/incognito diable.reg

I haven't tried it myself, as I don't have Windows 8. Although it seems that it's working.
Answer: I have tried a software IncognitoGone and it is marvellous. It is a permanent removal of the private browsing system, and works well for Chrome and Internet Explorer. You can download it here.

Disable Incognito mode in google chrome