Is there a way to get this (URL inside) JQuery counter to read JSON every 20seconds

Question: Currently im using PrivatePub(faye) in a rails app for chat but so far every post i read it looks like faye is unable to provide a count of open sockets subscribed to a specific event(or chat room) So unless anyone here can give me a better idea of how to approach this issue then ill be hacking up a fix for this issue but an explanation of how im going to do that is beyond what i need to ask in this post.
(Counter URL) http://bloggingsquared.com/jquery/flipcounter/
I've found a counter I would like to use but i know very little JavaScript and looking through the options of this script it doesn't seem to have an option to pull data from a JSON url. I would like to know if it is easy to make this counter do a $.getJSON() and set it to a timer to pull every 20 seconds?
Please if you have any other solution to my issue speak up or you can simply help me out on how to make the counter read JSON from a url on an interval.
Thanks in advance.
Answer: You can set up a timer using setTimeout() or setInterval():
Jquery/Ajax call with timer
And inside the success response of an AJAX request set the counter:
<code>$.ajax({
  url: "test.php",
  success: function(r){
     $("#counter").flipCounter("renderCounter", r.count);
  }
});
</code>
This is assuming that "r" is a JSON response, that has "count" inside it. If you're unsure of the response object, just console.log it.
Comment: No problem at all, I'm glad it helped


Rodar código antes de iniciar os services - AngularJS

Question: Há alguma maneira de rodar um código que execute antes dos services?
Porque quero usar a funcão $http.defaults.headers antes de iniciar os services para que eu possa instanciar o header em todos services que eu requisitar, mas parece que ele carregar todo o código e depois me retorna isso.
A função que faz isso está abaixo:
function get(url) {
        var deferred = $q.defer();
        $http.post(url,{'device_id':testedevice})
        .success(function (data) {
            deferred.resolve(data);
        })
        .error(function (error) {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    get(base_url+"/api/access/token")
        .then(function (data) {
            if(!localStorage.getItem("access_token")){
                localStorage.setItem("access_token",data.token);
                $rootScope.keyUser = data.token;
            }else{
                var userToken = localStorage.getItem("access_token");
                $rootScope.keyUser = userToken;
            }
    })
    .finally(function(){
        $rootScope.on(function(){
            $http.defaults.headers.get = {'access_token': userToken,'device_id':testedevice}
        });
    });

PS: o header é aplicado, mas depois que os services já foram chamados.
Answer: O que você precisa é criar um interceptor utilizando o $httpProvider.
Talvez este link te ajude Interceptor
Answer: Você pode implementar um interceptor exclusivamente para o serviço $http, e manipular os cabeçalhos diretamente.
module.factory('sessionInjector', ['SessionService', function(SessionService) {
    var sessionInjector = {
        request: function(config) {

            // Trecho executado antes de todo request:

            if (!SessionService.isAnonymous) {

                config.headers['access_token'] = SessionService.userToken;
               config.headers['device_id'] = SessionService.testedevice;
            }
            return config;
        }
    };
    return sessionInjector;
}]);

module.config(['$httpProvider', function($httpProvider) {
    // .config() ocorre antes de .run(), guarantindo assim que
    // sessionInjector esteja definido e preparado antes da
    // inicialização da aplicação.

    // Adiciona o injetor de sessão à lista de interceptors do
    // serviço $http
    $httpProvider.interceptors.push('sessionInjector');
}]);

Fonte original: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/


Event log subscription returns error code (0x138C)

Question: I have been battling getting event log subscriptions to work on my Server 2012 R2 domain controllers. I have created the collector-initiated-subscription using the GUI and selecting the defaults whenever possible. I selected my desired events and tried using the machine account, and several domain admin accounts.
At first I ran into access denied errors in the runtime status, but after much research I added the user accounts and the machine accounts to the AD Builtin group Event Log Readers. Ran GPUPDATE /Force, restarted Winrm and now I get Code (0x138C). Researching that error pretty much points at WinRM problems but I have verified WINRM functionality on both computers.
To summarize:

Created subscriptions using both computer account and domain admin accounts
Verified WINRM is functioning
Added computer account and user account to the Event Log Readers group
Gpupdate, restart services, still I get:

Error - Last retry time: 3/10/2016 1:17:37 PM. Code (0x138C): Windows Event Forward plugin can't read any event from the query since the query returns no active channel. Please check channels in the query and make sure they exist and you have access to them.  Next retry time: 3/10/2016 1:57:37 PM.

Here is the result of the wevtutil as taken of the source machine from the collector machine.
C:\Windows\system32>wevtutil gl /r:server1 security

name: security
enabled: true
type: Admin
owningPublisher:
isolation: Custom
channelAccess: O:BAG:SYD:(A;;0xf0005;;;SY)(A;;0x5;;;BA)(A;;0x1;;;S-1-5-32-573)
logging:
  logFileName: %SystemRoot%\System32\Winevt\Logs\security.evtx
  retention: false
  autoBackup: false
  maxSize: 134217728
publishing:
  fileMax: 1

As you can see, the Event Log Readers group (S-1-5-32-573) has Allow Read (A;;0x1) to the security log.
Firewalls are off. Both machines are on the same subnet. My google fu keeps sending me down the same rabbit holes.
Can anybody show me a new tact to try?
Answer: The solution is to add the "channel access permissions" for the security log.
•   Ensure the computer account of the collector is in the "Event Log Readers" builtin local security group.
•   Configure Event Collection on the computer to be monitored - Add the SID (S-1-5-20) of the Network Service account to the Channel Access permissions of the Security Event Log.
-   From an elevated command prompt:
wevtutil sl security /ca:O:BAG:SYD:(A;;0xf0005;;;SY)(A;;0x5;;;BA)(A;;0x1;;;S-1-5-32-573)(A;;0x1;;;s-1-5-20)

After approximately 20 minutes you should start to see events in the Forwarded Events
Reference: https://rockyprogress.wordpress.com/2011/12/04/security-event-log-collection-from-a-domain-controller/


Game: 5 attempts to guess the number between 1 and 100

Question: As the title suggests, I'm playing a game where I have 5 attempts to guess the number between 1 and 100. Each time I guess, the game tells me whether the number is higher, lower, or if I guessed it correctly.
I've been playing it by always making my first attempt as 50. If it says it's lower than 50, I divide 50 by 2 and make my second attempt as 25. If it says number is higher than 25, I then add 50+25 and divide the answer by 2 and round up. Making my third attempt 38. If it says lower than 38, than I know the number is between 25 and 38. So, again I add 25 and 38 and divide the number by 2 and round up. Making my fourth attempt 32. The game then says it's lower than 32. So the correct number is between 25 and 32. I have 1 final attempt left. So I repeat the procedure above again (add, divide, round up) and come up with my final 5th attempt as 29. And I happen to guess it correctly.
However, in the example above, I could have got it wrong and the number could've been anything between 25 and 32. The game is reset each time, can be same answer as previous game as it's always a new random number between 1 and 100.
My question: Is there a better method than the one I described above to guess the number correctly more often?
Comment: This is the heuristic of the https://en.m.wikipedia.org/wiki/Binary_search_algorithm
Answer: Assume n numbers. If n = 1 then you know the number.
Assume one guess. You can get 2 or 3 numbers if n = 2 or n = 3, and 2 numbers if n >= 4.
Assume two guesses. Up to n = 7 you can get all numbers: Guess the one in the middle and you have two groups with n <= 3. With n >= 8 you can get the number you guessed, three of a group of 3, and two of a group of 4 or more, total six numbers.
And so on. With three guesses you find all of fifteen, or fourteen out of more than fifteen. With four guesses you find all of 31, or 30 out of 32 or more numbers. With five guesses you find all of 63, or 62 out of 64 or more numbers. Given 100 numbers, you can find 2/6/14/30/62 with 1-5 guesses.
Six guesses guarantees you find the number: Guess 64; worst case 63 numbers left. Guess 32, worst case 31 numbers left. Guess 16, worst case 15 numbers left. Guess 8, worst case 7 numbers left. Guess 4, worst case 1-3 left. Guess 2, and you know the result.
Answer: There is no better strategy. With just five guesses each of which has a two way answer you can distinguish among at most $2^5 = 32$ numbers with certainty.
Here you can do a little better than among $32$ because the answer to each question is not just higher or lower, it can also be correct! . But there's no way to distinguish among $99$.
Six guesses would not be enough if you were not told if you guessed the number exactly. Careful analysis might say six would work in your game. (@gnasher says that in a comment on another answer.)


How to sketch $y=2\tan(x+\frac{\pi}{4})$ , $x \in (0,2\pi)$

Question:
How to sketch $y=2\tan(x+\frac{\pi}{4})$ , $x \in (0,2\pi)$

$2\tan$ , 2 is used to be amplitude in $\cos$ and $\sin$ graph but for the $\tan$ there is no
amplitude,so where will that $2\tan$ sketch, also
$x+\frac{\pi}{4}=\pi$
$x=\frac{4\pi}{4}-\frac{\pi}{4}$
$x=\frac{3\pi}{4}$
it is right?
Can you please explain me in step by step and show me how to sketch.
Thank you so much.
Comment: Oh, you don't have to apologize. It does irritate me that your teachers have neglected to teach you how to draw the basic function and then ask you to draw something a bit more elaborate... their fault, not yours.
Comment: Well, you weren't taught first how to draw $\tan\,x$ itself?
Comment: yes! sorry for my lack of maths knowledge. thx
Comment: If I were you I would ask this in general...there is nothing special about this function any you still want extremum points of y and y'...
Comment: yes! please provide me solution step by step. Appreciate it!
Comment: [This link](http://mathsisinteresting.blogspot.com/2008/08/how-to-sketch-trigonometric-graph.html) might be useful (and probably many similar can be found easily).
Answer: 1) Open any basic calculus, or even trigonometry, book and look and understand the graph of $\tan x$
2) Now "shift" that graph by a rate of $\frac{\pi}{4}$ to the right to get $\tan\left(x+\frac{\pi}{4}\right)$ (thus for ex., for $x=0\,\,$ we'll have now the value that $\tan x$ had at $x=\frac{\pi}{4}$...
3) Finally, multiply every value of $\tan\left(x+\frac{\pi}{4}\right)$ by 2, thus "expanding the graph"
DonAntonio
Comment: Are you sure that to get $\tan\left(x+\frac\pi4\right)$ you should shift the graph *to the right*? (I agree with what you wrote in parenthesis after that, but I would call that shift *to the left*, e.g. $\frac\pi4$ is shifted to $0$.)
Comment: I think you may be right, it looks geometrically more logical to call that a shift to the left.


Multisite with content sharing

Question: The last couple of days I have been looking into Drupals multisite with content sharing. Got some great information like http://palantir.net/blog/multi-headed-drupal and http://munich2012.drupal.org/program/sessions/multi-headed-drupal
It gives me a good idea of the options I have building a multisite and content sharing setup. As I am quite new to Drupal I am trying to get input on my setup and the architecture that is required to build it. I will briefly explain the architecture and then the options I think will be suited for this.
Basic setup
The basic setup is as follows. There will be 1 global website with an own admin/editor. Next to the global site there will be 10 regional websites with their own regional admins/editors. The regional websites will have content in their own language, but in the CMS there is an option to translate the content to English.
Global website
The global website will be a 1 page website and it displays content (English) from the regional websites. Content that needs to be curated by the global content-editor.
Regional websites
The regional websites are all the same (pages , nodes, content types) except for some different styling and logo's.
Access levels
The global admin can access all the websites, this can be using other logins or preferably an own global account. The regional admins/editors can only access and edit their own site.
From the information I have so far, this will require a combination of Domain Access and Organic groups but I am not sure if this is going to work.
My main concern is combining a global home with the regional websites and push content to the global home. Not only pushing but the the global editor will need to approve content before displaying it on the global home.
Does anyone know if we can build such a setup with Drupal?
Thanks in advance.
Comment: Your approach looks good. Start doing it and come back with more direct questions. We can't design it from the ground up for you.
Comment: Apparently this isn't to common with Drupal. Any ideas on other approaches?
Answer: I might think about using a login mechanism like OAuth (with its Connector module) or an LDAP instance so that your global admin can login to any site with the same login.
To distribute the content, I would try using a REST API from the regional sites via the Services module which supports login if content or views needs access control.
Good luck!!
Answer: Make views from reginonal site content that global can include in some admin page.
From that page global admin can pick url of the regional content and paste it in to list of "approved content".
Build stripped custom entity-view for the content available at regional url so the global site can parse the approved content list to list of entity-views.
This wouldnt necessarily need any cross site permission integration.

Multisite with content sharing


Showing that $\Gamma(X,\mathcal{O}_X)=k$

Question: Let $X$ be an integral scheme, proper over an algebraically closed field $k$. It is known that $\Gamma(X,\mathcal{O}_X)=k$. In the book that I am reading, the author claims that this fact follows from the following fact:
If an integral affine scheme $\operatorname{Spec}A$ is proper over a field $k$, then $A$ is also a field, i.e. $\operatorname{Spec}A$ is a single point.
My question is, how do we use this fact to deduce that $\Gamma(X,\mathcal{O}_X)=k$? I have been pondering over this for awhile and am unable to get why. Any hints given would be greatly appreciated!
Answer: I'm unsure what the author meant, but there's a standard proof as follows: a global section $f \in \mathcal{O}_X(X)$ induces a natural morphism $\hat{f}: X \rightarrow \mathbb{A}^1$. Composing with the natural open immersion $i$ from the affine space to the projective space, we get a morphism of proper $k$-schemes $\hat{f}': X \rightarrow \mathbb{P}^1$, so it is closed. Thus the (topological) image $I$ of this morphism is a proper closed irreducible subset of $\mathbb{P}^1$, because $X$ is irreducible.
Therefore $I$ is a $k$-point of $\mathbb{P}^1$ (because $k$ is algebraically closed) thus $\hat{f}$ is a morphism to a $k$-point, thus $f$ is an element of $k$ plus a nilpotent – as $X$ reduced, $f \in k$ and we are done.
Answer: Any proper morphism is of finite type by definition, so $A$ is a field which is finitely generated as an algebra over $k$. By Zariski's lemma, any such field must be finitely generated as a module over $k$. Since $k$ is algebraically closed by assumption, we conclude $A = k$.
Comment: Hi Alex. I understand the proof on why $A$ must be a field. However, it seems that we need to show first $\Gamma(X,\mathcal{O}_X)$ is a field. How do we go about showing that?
Comment: @thedilated: mindlack's nice proof is the one I typically see given. I only know of one other, which uses a bit of sheaf cohomology technology. You might want to edit your question to reflect that you are interested in the proof of this fact: the way your post is currently written, it reads to me like you are wondering why $A$ is a field *given* that $\Gamma(X, \mathcal{O}_{X})$ is a field.
Comment: Er, that should read why $A = k$, not why $A$ is a field.


How can I let users rate content with half stars in Fivestar?

Question: This is a quite regular feature request on the Drupal website (see for example this article), but there hasn't been provided a full answer anywhere and the answers only cover Drupal 6.
Instead of rating content with whole stars, I'd like my users to be able to vote with half stars (0.5, 1, 1.5, 2, etc.). On my website, voting on nodes happens via comments.
How can I achieve this? Which CSS and/or PHP changes do I eventually have to make to the Fivestar module?
Comment: @FelixEve: Thanks for your help. The error messages disappeared, but I still can't vote with half stars in a comment. When I expose the node's Fivestar field for voting, I get an error and strange things happen: after voting, 10 stars are displayed in the node and 2.5 stars are displayed in the comment. Also, the average score isn't updated. I'm sure you can get it completely right after some testing.
Comment: I found a module, but we need to give input as text (at the time of node creation) the output will rendered as stars.half starts works for this.But user can't rate starts at output.
Comment: I've just put a fix in place based on that error but not had a chance to test it yet. I've only tried it in one environment so will need a bit more work yet I suspect. [The same link](http://felixeve.co.uk/halfstar/halfstar.zip) has the updated copy.
Comment: Sorry - your being a proper guinea pig! I've spotted the issue and done some more testing and is working fine for me on a fresh install now. Same link updated again - I hope it will work for you this time. I've put it on [DO](https://drupal.org/sandbox/dahousecat/2233333) here but waiting to get though the peer review process.
Comment: @FelixEve: I have great news: after some testing, Halfstar finally seems to work for my purposes! I'll therefore accept your answer and post future issues to https://drupal.org/project/issues/2233333?status=All&categories=All. I'm sure I may thank you for your formidable module in the name of every Fivestar user!
Comment: Phew - finally got there :) Glad you are finding it useful - is good to finally release a module to the Drupal community :)
Answer: I've written a module that alters the fivestar module to allow halfstar voting:
Halfstar
After installing the module an option is added to the field instance setting form allowing half star voting:

Which then allows voting with half stars:

There is a rounding bug that occurs occasionally at the moment when using the Stars (rated while editing) widget. If you have 9 stars and then vote 5.5 is display as 5.6.


Radio button doesnt work inside css accordion

Question: I have a radio button inside a css accordion and for some reason it doesnt work.  Maybe the css I'm using for the accordion is overriding the radio button?  maybe because the accordion is made from a check box that is causing problems? I've also put dojo controls inside the accordion and some work, some don't Below is the code:   The first radio button outside the accordion works fine
HTML:
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="red" />Red

        <input type="checkbox" id="checkMTF-1" checked="checked" />
        Input System Info

            <input type="radio" name="colors" value="green" />Green
            <input type="radio" name="colors" value="red" />Red

        <input type="checkbox" id="checkMTF-2" />
        Input Marking Information

Fill out form

        <input type="checkbox" id="checkMTF-3" />
        Complete and Submit

Fill out form

css:
/Mark Ticket Form Accordion/
#accordionMTF input {
        display: none;
    }
    #accordionMTF label {
        background: #eee;
        border-radius: .25em;
        cursor: pointer;
        display: block;
        margin-bottom: .125em;
        padding: .25em 1em;
        z-index: 20;
    }
    #accordionMTF label:hover {
        background: #ccc;
    }
    #accordionMTF input:checked + label {
        background: #ccc;
        border-bottom-right-radius: 0;
        border-bottom-left-radius: 0;
        color: white;
        margin-bottom: 0;
    }
    #accordionMTF article {
        background: #f7f7f7;
        height:0px;
        overflow:hidden;
        z-index:10;
    }
    #accordionMTF article p {
        padding: 1em;
    }
    #accordionMTF input:checked article {
    }
    #accordionMTF input:checked ~ article {
        border-bottom-left-radius: .25em;
        border-bottom-right-radius: .25em;
        height: auto;
        margin-bottom: .125em;
    }

I have a fiddle:
here
Thanks
Comment: your radiobox are hidden via css: `#accordionMTF input { display: none }`. You should also use a different name (`colors` was already used)
Comment: when you say "it doesnt work" do you mean to say "it doesnt show up"? because your css clearly hides it `#accordionMTF input {display: none;}`
Answer: So long as you continue to use the same HTML structure, all you need to do is rework your css a little bit. The follow css
#accordionMTF input {
    display: none;
}

Needs to look like this
#accordionMTF > div > input[type='checkbox'] {
    display : none;
}

This is an excellent attempt to create an accordion without javascript. You might also consider incorporating CSS3 animations.
There is also a bug where your labels have the wrong for attribute value.
Here is a working fiddle http://jsfiddle.net/czo2m22s/21/
Answer: here is the reason:
accordionMTF input {
        display: none;
    }

Answer: The developer of you accordion has decided to hide ALL inputs (!?)
#accordionMTF input {
    display: none;
}

A more sane approach would be to give the inputs that are required for the accordion functionality a class (.hidden) and use that as a selector instead of blanket hidding all inputs:
<input type="checkbox" class="hidden" id="checkMTF-1" class="hidden" />

.hidden {
    display: none;
}

WORKING EXAMPLE


Shared Data Service AngularFire2

Question: I Basically needs a Shared service that stores the Realtime data from Firebase in a Variable. Various Components would then call a custom method in the service which would return the latest data from the Data store. This would mean instant data rather having to fetch the data which is the case when I return a FirebaseObservableList from Service. Hope you understand
Please have a look at the Service
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable, FirebaseListObservable } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';

@Injectable()
export class TransactionService {

    protected userTransactions;
    private bought: Array<any> = [];
    constructor(private db: AngularFireDatabase, private auth: AuthService) {
        // Listener to User Transactions
        this.getUserTransactions(this.auth.getUserKey())
            .subscribe((transactions) => {
                this.userTransactions = transactions;
                this.processTransactions();
            });
    }
    getUserTransactions(userKey: string): FirebaseListObservable<any[]> {
        return this.db.list('/UserTransactions/' + userKey);
    }
    getCurrentUserTransactions() {
        return this.userTransactions;
    }

    /**
     * Process the Transactions and
     * Categorize them
     */
    processTransactions() {
        this.rewarded = [];
        this.userTransactions.forEach(transaction => {
            let rewardType = transaction.transactiontype;
            switch (rewardType) {
                case "bought":
                    this.bought.push(transaction);
                    break;

                default:
                    break;
            }
        });
    }
    getBought() {
        return this.bought;
    }

}

Now the Component
import { Component, OnInit } from '@angular/core';
import { trigger, state, transition, style, animate } from '@angular/animations';
// Services
import { TransactionService } from '../../../services/transaction.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  animations: [
    trigger('fadeInOut', [
      transition('void => *', [
        style({ opacity: 0 }),
        animate(150, style({ opacity: 1 }))
      ]),
      transition('* => void', [
        animate(150, style({ opacity: 0 }))
      ])
    ])
  ],
})
export class HomeComponent implements OnInit {
  public bought: Array<any>;
  public activeTab: string = 'recieved';
  constructor(private transactions: TransactionService) {
    this.bought = this.transactions.getBought();
  }
  ngOnInit() {

  }
}

PS : I'm pretty new to Angular2 and Observables
Answer: So Guys finally found the answer myself. Created another Observable (BehaviorSubject) to store the latest data. Components then subscribed to this observable.
private _rewards: BehaviorSubject<any[]>;

constructor(private db: AngularFireDatabase, private auth: AuthService) {

        this.dataStore = {
            rewards: [],

        };

        this._rewards = <BehaviorSubject<any[]>>new BehaviorSubject([]);

        this.subscribeToRewarded();

    }

    subscribeToRewarded() {
        this.db.list('< DB Path >', {
            query: {
                orderByChild: 'transactiontype',
                equalTo: "reward"
            }
        }).subscribe((reward) => {
            this._rewards.next(reward);
        });
    }

    getRewarded() {
        return this._rewards.asObservable();
    }

Shared Data Service AngularFire2


Is there a place to get scoreless film clips to practice with?

Question: I have written a lot of pieces that I feel would fit nicely for a film or commercial and I would like to practice doing some scoring for films. Rather than filming myself, is there a website made for this kind of thing? One where you can download a sample clip with no soundtrack and can practice creating?
--Edit--
My current method right now has been searching on YouTube for videos that seem dramatic with no music. For example: This speech.
I have a hard time finding similar videos and the quality is usually not very good as you can see when he turns away from the camera the dialog is hard to hear.
Comment: I have a good idea: turn off the audio track when watching tv or streaming movies.
Comment: @AlbrechtHügli Yes that is one way I can do that but I still want to have the dialog and other sound effects. right now I just look on YouTube for videos without any soundtrack but those aren't usually good quality.
Comment: Similar to User Albrecht Hügli's suggestion, you could try movie scripts online, although the timing won't be fixed.
Answer: I used to just gate the heck out of the soundtrack whilst trying to keep any useful dialog's head just above the water. Start by hard-cutting all the bits that don't have dialog.
I used to use movie trailers straight from YouTube, rather than try to find bits of full movies I could re-score. You kind of have to pick ones you think you'll get the best separation from, rather than just go for your favourite movie. It leaves the choice rather eclectic & probably more of a musical challenge.
If you mix the dialog low & the score high, you kind of get away with it.
I wasn't hugely successful at this, but it was fun to try -
These days you might get luckier & the soundtrack is in 5.1 - giving you a much simpler way to pull out the centre channel.
Three examples - quite old now, so the videos are pretty low quality; not really important in the overall scheme of things.
This first one had a lot of dialogue, some of which I managed to keep intelligible, some… not so much, but it gets the feel across, which is really all you need.

This one got the same treatment, but had cast singing in one part, so I incorporated that in my score.

This one had a voice-over, no dialog, but was impossible to separate from the original score, so I re-did it myself.

I wouldn't claim any of these were great, but I enjoyed doing them ;)
Another thing you could do is hook up with amateur or student film-makers. Many of them are in need of scoring for their movies - usually shorts - so you can usually knock out the first draft in a day, finalise the next.
Comment: That's great. That is basically what I need. I wonder why there is no site dedicated to this type of thing though. I wish I could make one. What is the easiest way to pull the center channel?
Comment: If you've got the video track in your DAW, you should have control over all the channels. tbh, my audio rig isn't 5.1 capable & when i did these it wasn't really a concern; I worked from stereo videos, so I've never actually done this from 5.1 - but such as Cubase/Nuendo can extract the audio from the video so you get individual control. Probably Premier/Final Cut Pro could do it too - I re-combined my audio in FCP.


A compatible way to show users a browser warning

Question: There are countless questions about this but the answers to all of them are out of date with IE no longer supporting conditional statements, jQuery no longer supporting detection without a migrate plugin etc. This question has been asked before but there are no answers that remain supported in 2020.
The  tag is a perfect example of how simple this should be. Surely there must be a way to detect the browser (IE) and then set a DIV with a warning message to visible.
There have been answers in the past but even they aren't supported now. Of course any JS used to detect the browser would need to be compatible with IE.
My first thought was to do something that would detect MSIE and then display a DIV. It seems up for debate as to if you should use feature or browser detection based on everything I've looked through for the last few hours.
The reason I need this message in IE is because the site isn't compatible due to new JS and CSS features. I wouldn't know where to start with this so apologies for not posting any code. All it needs is something like this.

// Detect if Internet Explorer
//   If no do nothing
// If Internet Explorer
//   Set iewarning to visible
.iewarning {
  display: none;
}

Update your browser

I don't know how to go about detecting features, the browser or user agent but this question has to be asked again now that there's no conditional statements or jQuery support. Pure JS is the most ideal solution. Any approaches using that would be appreciated. Thanks in advance.
EDIT
If feature detection could be used to make a DIV visible.

if (typeof Promise == "undefined") {
  document.getElementByClass("iewarning").style.display = "block";
}
.iewarning {
  display: none;
}

Please upgrade your browser

That doesn't work though but seems like it could be a more minimal solution.
EDIT
Using a query selector instead should work? I'm entirely lost but willing to use feature detection if someone can help me get it working.

if (typeof Promise == "undefined") {
  document.querySelector("div.iewarning").style.display = "block";
}
.iewarning {
  display: none;
}

Please upgrade your browser

Comment: Would [this](https://stackoverflow.com/questions/31757852/how-can-i-detect-internet-explorer-ie-and-microsoft-edge-using-javascript) help?
Comment: refer this link https://stackoverflow.com/a/10047391/4964569
Comment: Unfortunately all of the answers there rely on alerts not DIVs for messages and aren't fully supported anymore @Artur
Comment: Same issue there @HienNguyen, the accepted answer isn't compatible anymore.
Comment: As to the code you added, There's no `getElementByClass` method. You're thinking of `getElementsByClassName`, which returns a list, so you'd need to access the first index. Or just use `.querySelector`.
Comment: You're right. I'd forgot to specify name. I'm not sure how to use `.querySelector` or where. If you're able to update your answer that'd be appreciated. Am I at least on the right track?
Comment: `.querySelector` is a way of selecting an element from the DOM using the same selector syntax that CSS uses. But it won't work in IE 6 and below, but nether will `getElementsByClassName`. You'd be probably better off giving it an ID and using `getElementById`
Answer: OK based on your comments so far here is the most simplfied browser detection approach I could devise using a div in the HTML as you requested.

function isUnsupported (browser) {
    return (browser.name === "MSIE" || browser.name === "IE")
}
var isUnsupported = this.isUnsupported(this.get_browser());
// Uncomment to simulate being in an IE browser.
//var isUnsupported = true;

this.listen("load", window, function() {
  if (isUnsupported) {
    var warning = document.querySelector(".iewarning");
    warning.style.display = 'block';
  }
});
function listen(evnt, elem, func) {
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+evnt, func);
         return r;
    }
    else window.alert('Error: unsupported browser!');
}
function get_browser() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
      tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
      return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
      tem = ua.match(/\bOPR\/(\d+)/)
      if (tem != null) { return { name: 'Opera', version: tem[1] }; }
    }
    if (window.navigator.userAgent.indexOf("Edge") > -1) {
      tem = ua.match(/\Edge\/(\d+)/)
      if (tem != null) { return { name: 'Edge', version: tem[1] }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
    return {
      name: M[0],
      version: +M[1]
    };
}
.iewarning {
  display: none;
}

Welcome to the Website

IE not supported. Please upgrade your browser.

Comment: I've tried it hosted via a page on a domain actually in IE11 and it didn't. I'm not too sure why.
Comment: When you uncomment `//var isUnsupported = true;` it's fine but actually viewing the page in IE doesn't show the message. I think given feature detection too it's best to just leave this even though it should be so simple when it's something plenty of sites have.
Comment: I am not sure what you are talking about. Edge browser? Stackoverflow wont let you run a code snippet in Internet Explorer as they do not support Internet Explorer. I tested the original version of this with vscode live server in Internet Explorer 11 and it worked.
Comment: Yeah I just tested the version you said didnt work in vscode live server and it didnt work for me either. It is not the browser detection portion, rather its most likley that the HTML display portion of the code is not supported by IE, haha. Thats why I used the modal approach I saw on codepen in the first place. I might fix it.
Comment: @learningtoanimate Yeah I found the problem. The way the style was being set to display the warning div was not IE friendly so I fixed it by changing the line `warning.style = 'display: block;'` to `warning.style.display = 'block';`. The snippet has been updated. Thank you.
Comment: Amazing thank you. Definitely seems the best approach knowing that IE won't receive support but people tend to keep other browsers up to date so support issues aren't as likely.
Answer:
There are countless questions about this but the answers to all of them are out of date with IE no longer supporting conditional statements, jQuery no longer supporting detection without a migrate plugin etc.

They're not out of date, since those features are still no longer supported, and nothing new has arrived to replace them.

This question has been asked before but there are no answers that remain supported in 2020.

There's a reason for that.

The tag is a perfect example of how simple this should be. Surely there must be a way to detect the browser (IE) and then set a DIV with a warning message to visible.

There are ways, but they have varying degree of reliability, and none match what conditional comments provided.

There have been answers in the past but even they aren't supported now.

That's basically your answer right there.

Of course any JS used to detect the browser would need to be compatible with IE.

Would it? If it's not compatible, wouldn't that give you an indicator that the browser doesn't support the features you want to provide?

My first thought was to do something that would detect MSIE and then display a DIV. It seems up for debate as to if you should use feature or browser detection based on everything I've looked through for the last few hours.

Yes, read those debates. If you want to detect features, then detect features. If you actually want to detect browsers, then do so with the user agent.

The reason I need this message in IE is because the site isn't compatible due to new JS and CSS features.

What about other legacy browsers that don't support the features you want? Why do you only want to deal with one specific browser in this situation.

I wouldn't know where to start with this so apologies for not posting any code.

You already had a good start when you read the myriad of other discussions on this topic.
You seem unwilling to listen to any previous discussion and are hoping there's some magic that hasn't yet found its way to the internet.
There isn't.
Here's a summary of some options.

IE's legacy features - If the specific versions of IE that you want to detect have conditional comments enabled, then use that feature.
User agent sniffing - gives detailed information about the user agent. It can technically be spoofed by the user, but that's very rare, and who cares. If the user wants you to believe they're using a different browser, then let them.
Feature detection - If missing features are your concern, then this would seem to be the obvious choice. However, if you load libraries that provide compatibility for some of the missing features, it could get a little complicated. As long as you're aware of the 3rd party code you load, it shouldn't be an issue.
Let it break - Why not? Do you think your site is the only one they'll encounter that uses modern features? Most sites take this approach, and it works incredibly well.
Ask the user - Kindly request upon entry that the user tell you their browser and version. Say things like "pretty please" and convince them that it's of the utmost importance (lie to them), and you may have some success.
Write a virtual psychic library - This would harness the unseen powers of the universe to detect the exact browser and version of the visitor to your site. Seems like a winning solution to me.

You're not the first to want this, but you're sort of acting like this topic hasn't really been explored in full until today. It has. There's nothing new at the moment. When there is, it will be big news, and you'll see it discussed in those old posts.
Comment: Your answer isn't correct though because other websites have managed to do this. I'm willing to listen to other approaches but none that work are available. Even if you detected features then showed a DIV that would be more appropriate.
Comment: [codepen.io](https://codepen.io/) does it pretty solidly.
Comment: @learningtoanimate: They either use legacy features in those legacy browsers, or they use the other available features. Just because you see a div, doesn't mean they're *not* using the solutions you've been told about countless times.
Comment: I'm not against using those features, I just don't understand them and I don't think your attitude is particularly helpful.
Comment: @learningtoanimate: Up until this point you've seemed very much against using those features. Unfortunately, that's about as good as you're going to get. My attitude does seem to be helping, since you seem to be getting closer to dealing with the unfortunate reality of the situation.
Comment: It's not conducive to a simple working answer though. If it's something that works to achieve the result it seems like it could at least be considered. The last snippet in my question is the closest I've got @slappy so help with that (if salvageable) would be appreciated.
Answer: I just wrote a codepen a couple of days ago that uses the approach codepen.io utilizes in production to notify a user when they come to their site with an IE browser. The notification is modal. It's pretty solid.
CSS:
* {
    margin: 0;
    padding: 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
#unsupported-message :last-child {
    margin-bottom: 0px;
}
html, body {
    height: 100%;
    -webkit-overflow-scrolling: touch;
}
body {
    background: #131417;
}
/* @media all and (min-width:831px) */
body {
    position: relative;
    height: auto;
    min-height: 100vh;
}
body {
    color: white;
}
body {
    position: relative;
    overflow-x: hidden;
    overflow-y: auto;
    height: 100vh;
    background: #131417;
}
/* @media all and (min-width:831px) */
body:not(.sidebar-false) {
    padding-left: 188px;
}
html {
    font-family: "Lato", "Lucida Grande", "Lucida Sans Unicode", Tahoma, Sans-Serif;
    line-height: 1.5;
    font-size: 15px;
    font-weight: 400;
}
html {
    overflow-x: hidden;
}

#unsupported-overlay,
#unsupported-modal {
    display: block;
    position: absolute;
    position: fixed;
    left: 0;
    right: 0;
    z-index: 9999;
    background: #000;
    color: #D5D7DE;
}

#unsupported-overlay {
    top: 0;
    bottom: 0;
    opacity: 0.7;
}

#unsupported-modal {
    top: 80px;
    margin: auto;
    width: 90%;
    max-width: 520px;
    max-height: 90%;
    padding: 40px 20px;
    box-shadow: 0 10px 30px #000;
    text-align: center;
    overflow: hidden;
    overflow-y: auto;
    border: solid 7px #ffdd40;
}

#unsupported-message :last-child { margin-bottom: 0; }

#unsupported-message h2 {
    font-family: 'Telefon', Sans-Serif;
    font-size: 34px;
    color: #FFF;
}

#unsupported-message h3 {
    font-size: 20px;
    color: #FFF;
}

body.hide-unsupport { padding-top: 24px; }
body.hide-unsupport #unsupported-message { visibility: hidden; }

#unsupported-banner {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background: #ffdd40;
    color: #000;
    font-size: 14px;
    padding: 2px 5px;
    line-height: 1.5;
    text-align: center;
    visibility: visible;
    z-index: 199;
}

#unsupported-banner a {
    color: #000;
    text-decoration: underline;
}

@media (max-width: 800px), (max-height: 500px) {
    #unsupported-message .modal p {
    /* font-size: 12px; */
    line-height: 1.2;
    margin-bottom: 1em;
    }

    #unsupported-modal {
    position: absolute;
    top: 20px;
    }
    #unsupported-message h1 { font-size: 22px; }
    body.hide-unsupport { padding-top: 0px; }
    #unsupported-banner { position: static; }
    #unsupported-banner strong,
    #unsupported-banner u { display: block; }
}

JS:
// dirty vanilla listen method
function listen(evnt, elem, func) {
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+evnt, func);
         return r;
    }
    else window.alert('Error: unsupported browser!');
}
// dirty browser detection but production worthy
function get_browser() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
      tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
      return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
      tem = ua.match(/\bOPR\/(\d+)/)
      if (tem != null) { return { name: 'Opera', version: tem[1] }; }
    }
    if (window.navigator.userAgent.indexOf("Edge") > -1) {
      tem = ua.match(/\Edge\/(\d+)/)
      if (tem != null) { return { name: 'Edge', version: tem[1] }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
    return {
      name: M[0],
      version: +M[1]
    };
}

function isUnsupported (browser) {
    return (browser.name === "MSIE" || browser.name === "IE")
}

var isUnsupported = this.isUnsupported(this.get_browser());

/*
  Uncomment the below line of code to simulate
  being in an IE browser.
*/
//var isUnsupported = true;

if (isUnsupported) {
    this.listen("load", window, function() {
        var d1 = document.createElement('div');
        var a1 = document.createElement('a');
        var d2 = document.createElement('div');
        var title = document.createElement('h2');
        var p1 = document.createElement('p');
        d1.id = 'unsupported-message';
        a1.id = 'unsupported-overlay';
        a1.href = '#unsupported-modal';
        d2.id = 'unsupported-modal';
        d2.role = 'alertdialog';
        d2['aria-labelledby'] = 'unsupported-title';
        title.id = 'unsupported-title';
        title.innerHTML = '⚠ Unsupported Browser ⚠';
        d2.appendChild(title);
        d2.innerHTML += "This site does not support Internet Explorer. We generally only support the recent versions of major browsers like Chrome, Firefox, Safari, and Edge."
        d2.appendChild(p1)
        d1.appendChild(a1);
        d1.appendChild(d2)
        document.body.appendChild(d1);
    });
} else {
  var instructions = document.createElement('div')
  instructions.innerHTML = "Uncomment line 45 (//var isUnsupported = true;) in the javascript to simulate being in an unsupported browser."
  document.body.append(instructions)
}

Comment: That is useful but is it something that needs to be so complex? Also, please correct me if I'm wrong but does that not show a popup alert rather than being part of the page?
Comment: If you want production worthy code it does not get much more succinct than that. The message is part of the page but it is made to look like a modal popup so the user will go away and come back with a supported browser but you could edit that part to serve your needs.
Comment: Can you please see my question update with feature detection, it seems like it could be a quicker way to do this.
Comment: You can't really use `attachEvent` for a blanket `addEventListener` substitute. There needs to be a good bit of patching to make them equivalent.
Comment: @slappy it's just for IE users, why not?
Comment: @apena: There are a number of reasons, but probably the most important is that it doesn't set the value of `this` to the element that received the event listener. Using `this` is very common, so handlers that use it would break. There are other incompatibilities too, but that's arguably the most serious.
Comment: @learningtoanimate I got my answer down to 45 lines of code in pure vanilla javascript [here](https://codepen.io/ApoloPena/pen/jOWVvvQ?editors=0110). The solution I offer is browser detection. Feature detection can be messy for a number of reasons, but you need to make up your mind as to which you will use, that is up to you of course.
Comment: @slappy The `listen` method is just used once on `load` to send the user away if they have IE. Are you talking about using the `listen' method for more than that?
Comment: I'm still trying to figure out which offers the best support. I do like the shorter version. I just don't know if feature detection will be better for older versions of browsers. A way to combine both and a DIV in the HTML vs being created by the JS would be most ideal.
Comment: Oh, sorry. I thought you were providing that as a shim. I didn't look closely enough.
Comment: @slappy no worries.
Comment: @learningtoanimate I guess a good way to figure out which way you should go is to analyze how many features you will need to detect and how many new features you will want to implement in the future. If those numbers are low enough and your IE user base is high enough then feature detection might be a better approach. Otherwise keep it simple.
Comment: Browser detection could work best given that it's likely new features won't be supported by old browsers. I'm close to leaving it entirely and just having a site that doesn't function correctly. Your most recent pen was close but a DIV is needed to be made visible within the HTML, not generated because it may need changes which will be much easier when not in JS.
Comment: @learningtoanimate I posted another answer with a code snippet that addresses your request. Good luck to you ;)


Closed sets in Zariski Topology

Question: What are the closed sets on $\mathbb{Z}$, $\mathbb{R}[x]$, $\mathbb{Z}[x]$? I was given this question, but it seems trivial, because aren't the closed sets only the affine varieties? So for each is just the irreducible varieties?
So I understand better, could you also give me an example of a set in one of those that is not closed? Would one be a line without the origin?
Edit: this is with regards to the spectrum of a ring R, defined to be V(S)=$\{P \in SpecR  | S \subseteq P\}$ where P is a prime ideal. Then the collection $\{V(S)|S\subseteq R \}$ determines a topology on SpecR, the zariski topology. (If someone could explain why this is true, that would be great too!)
Comment: This is note quite as easy as you believe. For example, telling me what the closed subsets of $\mathbb{Z}[x]$ are is equivalent to telling me what $V(I)$ is for all ideals $I$. While this is easy for the first two, since they are PIDs, this is slightly trickier for this last ring.
Comment: When you say "closed sets on $\mathbb Z$" etc., I assume you mean "closed subsets of the topological space $\operatorname{Spec}\mathbb Z$" etc.? Do you have the spectra of all three rings at hand?
Answer: I) The irreducible closed subsets of $\mathbb A^1_\mathbb Z=\operatorname {Spec}\mathbb{Z}[X]$ are exactly the following, listed by dimension:
Dimension two
$\mathbb A^1_\mathbb Z=V(0)$
Dimension one
$\bullet$ The curves $V(f) $ where $f\in \mathbb Z[X]$ is an irreducible polynomial
$\bullet \bullet$ The curves $\mathbb A^1_{\mathbb F_p}=V(p)$ here $p$ is a prime integer.
Dimension zero
The closed  points $V(p,f(X))$ where $f(X)\in \mathbb Z[X]$ is a polynomial whose reduction $\overline {f(X)}\in \mathbb F_p[X]$ modulo the prime $p$ is irreducible.
II) An arbitrary closed subset of  $\mathbb A^1_\mathbb Z$ is a finite union of some  of the above  irreducible closed subsets of $\mathbb A^1_\mathbb Z$, where mixing subsets of different dimensions is of course allowed.
[The empty set is thus closed : it is the union or the empty set of irreducible closed subsets.
If you are allergic to such set-theoretical sophistry, just explicitly add $ \emptyset$ to the above description]
Comment: I'm sure you will be able to  solve the easier problem of determining the closed subsets  of the spectrum of $\mathbb Z$ or $\mathbb R[X]$ once you have read the above answer.
Answer: Since the rings you list are domains but not fields, in all three cases the set consisting of just the ideal $(0)$ is not closed in the Zariski topology.
For different examples you may consider:

a set consisting of infinitely, but not all, primes in $\Bbb Z$,
the set of ideals $(X-r)$ for all $r\in\Bbb R$ in $\Bbb R[X]$,
The set consisting of the single ideal $(X)$ in $\Bbb Z[X]$.

Closed sets in Zariski Topology


Como criar uma função pra exibir os maiores números de uma arvore B em Java?

Question: Pessoal tenho uma duvida, como fazer uma função que retorne o Nó com o maior valor de uma arvore B que armazena inteiros. Estou tentando adaptar o código de passeio em ordem para tentar retornar, porém só retorna null.
Na classe Node criei a seguinte função
Classe Node
public Node maiorValor() {
    int i;
    Node aux=null;
    for (i = 0; i < this.n; i++) {
        if (this.filhos[i] != null) {
            this.filhos[i].percorrerEmOrdem();
        }
         aux = this.filhos[i]; // recebe o valor

    }
    if (this.filhos[i] != null) {
        this.filhos[i].percorrerEmOrdem();
    }

    return  aux;// retorna aux
}

}
`

Na Classe BTree criei a seguinte função que será chamada pela classe Main que possui uma instancia de BTree
public Node maiorValor() {
        int i;
        Node aux;
        if (this.isEmpty() == false) {

            aux= root.maiorValor();
            return aux;
        } else {
            return null;
        }
    }
    }

Alguém pode me ajudar?
Comment: Se é uma árvore B, então ela mantém a ordem dos elementos. Neste caso, bastaria pegar a folha mais à direita (não precisa percorrer todos os nós). Algo como `maiorValor() { if (this.filhos[this.n] == null) return this.filhos[this.n]; else return this.filhos[this.n].maiorValor(); }`
Answer: Olá, eu não sei se entendi o que você precisa fazer, mas se você precisar pegar o maior valor de um array de inteiros basta você usar a api stream.
   int[] nros = {3,6,7,20,4,5,98,65,7,9,43,57,86,46,8,34,67};
   int maior = Arrays.stream(nros).max().getAsInt();
   System.out.println(maior);

[]'s
Comment: Não é um array é uma [BTree](https://pt.wikipedia.org/wiki/%C3%81rvore_B).


Biologically inspired ANNs

Question: Does anyone know what kinds of pattern classifier artificial neural networks are more biologically inspired?
Comment: I would recommend you have a look at "Theoretical Neuroscience" by Dayan  and Abbott (2001). As for the differences between ANNs and their biological counterpart, MacKay (2003) offers a small comparision. Moreover, you might also be interested in "On Intelligence" by Hawkins (2004).
Answer: Convolutional Neural Networks are biologically inspired by the virtual cortex's arrangement in mammals. For example the sensitivity of vision system to local receptive fields is one of the defining properties of convolutional nets.

Biologically inspired ANNs


Surreal numbers and function growth

Question: I have read in several sources (I didn't keep the references) that surreal numbers are well suited for describing function growth, but none of the texts I have seen went into any detail on this nor did they provide a reference. Google searches on "surreal functions function growth" only got me to the same point. What would be a good starting point to read about this?
Update: I would primarily be interested in simple cases (up to generation $ω$ or, say, $ω^ω$) and only then generalizations to more generic cases. I would expect either something along the lines of
$$\begin{aligned}
u&&\cdots&&&x^u&&(u\text{ real}) \\
ω&&\cdots&&&e^x \\
ε&&\cdots&&&\ln x \\
\end{aligned}$$
(but I don't know what multiplication of surreals would correspond to in this model to reflect that $ω.ε = 1$) or perhaps even
$$\begin{aligned}
u\in\mathbb{R}&&\cdots&&&\text{finite limit} \\
ω&&\cdots&&&x \\
ε&&\cdots&&&1/x \\
ω^2-2ω+3+ε&&\cdots&&&x^2-2x+3+1/x
\end{aligned}$$
(which looks somewhat more consistent but simply replacing $ω$ by $x$ would break at e.g. $ω^ε = \ln ω$).
Introductory stuff is welcome.
Answer: I think the clearest account of this idea can be found in this article of Aschenbrenner, van den Dries and van der Hoeven. It is a sort of survey article, easy to read.
The basic ideas are:
-A good framework to speak of the growth of function is that of Hardy fields which are ordered field of sufficiently differentiable real valued functions whose elements and their derivatives are monotonous on neighborhoods of $+\infty$.
-Hardy fields are hard to study, but it is possible in certain cases to describe their general properties (from a model-theoretic standpoint) using formal series called transseries whose model theory is known.
-Transseries are formal but can act as functions on fields of formal series, thus giving a direct link between the growth of a function and the series which represents it.
-Finding correspondences between formal series and functions can give much information about the latter, whereas formal series are subject to more computations and algorithmic methods.
-Transseries can be naturally interpreted as surreal numbers.
-Describing certain functions (with transexponential growth for instance) cannot be done using regular transseries but requires additional types of series, called hyperseries.
-It is conjectured that such hyperseries can also be naturally interpreted as surreal numbers. Provided every surreal number can be represented as a hyperseries, it is believed that the resulting structure has good closure properties in a similar way as regular transseries have good closure properties.

In any case, the middle step between surreal numbers and functions is the notion of transseries, or hyperseries.

At a more basic level, your second line of correspondences is correct in that this is how the functions on the right side are represented as surreal numbers in the natural correspondance between transseries and certain surreal numbers.
This correspondance is the only one which fixes real constants, sends $x$ onto $\omega$ and commutes with $\exp$, $\log$ and with transfinite sums.
The surreal numbers below generation $\omega^{\omega}$ are just sums $\sum \limits_{n \in \mathbb{N}} r_n \omega^{d_n}$ where $(d_n)_{n \in \mathbb{N}}$ is a strictly decreasing sequence of dyadic numbers and $(r_n)_{n \in \mathbb{N}}$ is a sequence of real numbers. Those correspond to formal generalized power series $\sum \limits_{n \in \mathbb{N}} r_n x^{d_n}$ which can act as functions on subclasses of $\mathbf{No}$. Notice that this already flows outside of the class of classically convergent series.
If you allow length $\omega^{\omega}$, you get $\omega^{\omega}=\exp \omega$ itself, which corresponds to the exponential function or the transseries $\operatorname{e}^x$; or $\omega^{\frac{1}{\omega}}=\log \omega$ which corresponds to $\log x$. You also obtain $\omega^{-\omega} \equiv \operatorname{e}^{-x}$, the numbers $\omega^r\equiv x^r$ for non-dyadic $r \in \mathbb{R}$ and the products $\omega^{d\pm\frac{1}{\omega}}\equiv x^d (\log x)^{\pm 1}$ where $d$ is dyadic.
[edit: the following is actually false: I believe every number of generation $<\varepsilon_0$ corresponds to a so-called exponential-logarithmic transseries but I don't have a proof right now. Generation $\varepsilon_0$ brings a lot of more complicated behavior which cannot be described by regular transseries, but rather "nested transseries" $\sqrt{\omega}+\operatorname{e}^{\sqrt{\log \omega}+\operatorname{e}^{\sqrt{\log \log \omega}+\operatorname{e}^{\cdot^{\cdot^{\cdot}}}}}$ or transexponential hyperseries such as $\varepsilon_0 \equiv \operatorname{e}^{\operatorname{e}^{\operatorname{e}^{\cdot^{\cdot^{\cdot}}}}}$.]

Surreal numbers and function growth


How can I utilize a condition on className to run a function?

Question: I am designing a trivia app where 1 of 4 options can be selected. Upon clicking the element, the class changes from selectedFalse to selectedTrue. Then, the idea is that clicking the "submit" button will pull the next question (working) and increase the correct variable (not working)
PullQuestions() Iterates through the questions. I've included the code for just one of the questions.
if (question.id == 0) {

    document.getElementById("headerQ").innerHTML = question[0].headerQ;
    document.getElementById("content").innerHTML = question[0].content;
    document.getElementById("op1").innerHTML = question[0].op1;
    document.getElementById("op2").innerHTML = question[0].op2;
    document.getElementById("op3").innerHTML = question[0].op3;
    document.getElementById("op4").innerHTML = question[0].op4;

    if (op1.className == "selectedTrue") {
        isCorrect();
    }

    console.log("Scoring System Logging: ", question.id, correct);
    }
}

Because the condition is true, I was expecting the isCorrect() function to fire. According to the console, the function is not firing.
isCorrect() Function
function isCorrect() {
    correct++;
    console.log("isCorrect()", "Scoring System Logging: ", question.id,  correct);
}

Submit Button Function
function submitA() {
    question.id++;
    pullQuestions();

    console.log("submitA()", "Scoring System Logging: ", question.id, correct);
}

I don't know why I can't get the score to increase based on the className of the selected object.
EDIT
Here's the code for the "options." The styles work accordingly. Clicking any of the options sets the class from selectedFalse to selectedTrue. Clicking any other option will revert the original selection back to false. Additionally, clicking the same option twice will revert back to false. I can confirm this is working both visually (true turns green, false turns orange) and in the Console tab.
// Option 1
function select1() {

        if (op1.className == "selectionFalse") {
        document.getElementById("op1").className = "selectionTrue";
        document.getElementById("op2").className = "selectionFalse";
        document.getElementById("op3").className = "selectionFalse";
        document.getElementById("op4").className = "selectionFalse";

        console.log("selected1()", "If Condition", op1.className);
        }

        else {
        document.getElementById("op1").className = "selectionFalse";
        console.log("selected1()", "If Condition", op1.className);
        }
    }

// Option 2
        function select2() {

        if (op2.className == "selectionFalse") {
        document.getElementById("op1").className = "selectionFalse";
        document.getElementById("op2").className = "selectionTrue";
        document.getElementById("op3").className = "selectionFalse";
        document.getElementById("op4").className = "selectionFalse";

        console.log("selected2()", "If Condition", op2.className);
        }

        else {
        document.getElementById("op2").className = "selectionFalse";
        console.log("selected1()", "If Condition", op2.className);
        }
    }

// Option 3
        function select3() {

        if (op3.className == "selectionFalse") {
        document.getElementById("op1").className = "selectionFalse";
        document.getElementById("op2").className = "selectionFalse";
        document.getElementById("op3").className = "selectionTrue";
        document.getElementById("op4").className = "selectionFalse";

        console.log("selected3()", "If Condition", op3.className);
        }

        else {
        document.getElementById("op3").className = "selectionFalse";
        console.log("selected3()", "If Condition", op3.className);
        }
    }

// Option 4
        function select4() {

        if (op4.className == "selectionFalse") {
        document.getElementById("op1").className = "selectionFalse";
        document.getElementById("op2").className = "selectionFalse";
        document.getElementById("op3").className = "selectionFalse";
        document.getElementById("op4").className = "selectionTrue";

        console.log("selected4()", "If Condition", op4.className);
        }

        else {
        document.getElementById("op4").className = "selectionFalse";
        console.log("selected4()", "If Condition", op4.className);
        }
    }

Any help is appreciated.
Comment: Have you checked what `op1.className` is set to? It would help to see a full working example of the issue, including the HTML, as I'm sure you can simplify and DRY this code up
Comment: According to what you say, the problem is here " if (op1.className == "selectedTrue") " so we can't help unless we what is op1 and it would be better if you share the rest of the code
Answer: if you want check if an element has a class name, you should do:
if(op1.classlist.contains("selectedTrue")){
 // your logic here
}

Comment: Thanks. I gave this a shot and I got an error in the console tab. "Cannot read properties of undefined reading 'contains'. I don't think that's an issue because when the trivia part loads there is no option set to `selectedTrue`. Though, when I click the `op1` button and then click submit the function still doesn't fire.


Serving secure static S3 site without www

Question: I'm trying to set up AWS to serve a static S3 site over SSL with a custom domain. I'm so close but I'm missing one piece.
S3 static website (works): xyz.s3-website.us-east-2.amazonaws.com
CloudFront distribution: abc.cloudfront.net w/SSL cert from Certificate Manager for mydomain.com with behavior of Redirect HTTP to HTTPS
DNS (GoDaddy): CNAME www abc.cloudfront.net

https://www.example.com/ works perfectly
https://example.com/ does not (privacy error)
http://www.example.com/ redirects to https abc.cloudfront.net
http://example.com/ redirects to https abc.cloudfront.net

The cert is set up for both www and none.
What am I doing wrong?
Comment: have you checked binding settings ?
Comment: @Aravinda Can you be more specific please?
Comment: what is the websrver used ?
Comment: @Aravinda There is no web server. This is hosting static files directly from an S3 bucket.
Answer: You need to create another CloudFront Distribution and another S3 Bucket (www-bucket). You can use your current SSL certificate since you mentioned it's valid for both none and www
Read about redirecting from your www-bucket to the main bucket - How Do I Redirect Requests to an S3 Bucket Hosted Website to Another Host?

You can use this CloudFormation template cloudformation-s3-website-ssl-with-redirect  to implement this solution.
You can also read this nice blog post - How to do Site redirection using AWS S3?


UIWebView can't inject HTML

Question: I'm trying to put some HTML in a div in a UIWebView. Although the code seems correct it won't work.
This works:
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"testdiv\").innerHTML = \"Test text here\""]];

This doesn't:
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"testdiv\").innerHTML = \"%@\"", htmlString]];

In the second case 'htmlString' is just some HTML within a blockquote.
Basically when I do it with the HTML it fails. My first thought it that the HTML could be invalid but I thought it would still attempt to display it.
The 'error' I'm getting as a result of the operation is just an empty (non-nil) string.
Any ideas?
Edit:
Here is an example of the HTML that won't display:

<meta http-equiv="Content-Type" content=
"text/html charset=us-ascii" />
<title></title>

TestTESTEST

The htmlString variable is just that HTML within a blockquote tag.
Edit 2:
If I take the HTML and put it directly in the document and then load it it works. It's only having issues when I try to insert it via JS.
Comment: I have only one idea about this: you provide invalid Html. So remove all newline characters and check for not closed tags.
Comment: May be your data is terminating in between the escaped characters?, Can you check using `NSLog`?
Comment: also check your data in browser's debug console
Comment: Would invalid HTML cause nothing to display? @iphonic I NSLog the result of stringByEval and get an empty string returned. I also get nothing in webViewFailed delegate.
Comment: can you provide example of `htmlString` that doesn't work ?
Comment: @sage444 working on that now, I'll post something in a few minutes.
Comment: @sage444 done. The HTML is taken from an email and displays correctly in a UIWebView via the loadHTMLString method.
Comment: Now we can see that you load whole html document into div, I'm not sore that it's valid structure, but to ensure try to load only content from between ``
Comment: @sage444 Still the same problem just loading the body tags content.
Comment: hmm, last idea, can you try single quotes in string format: `[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"testdiv\").innerHTML = '%@'", htmlString]];`
Comment: Ok, now we're getting somewhere.  If I take the content between the body tags (and exclude the body tags) and use single quotes in the string format the stringByEvaluating method returns the content. I'm guessing your original diagnosis of invalid HTML is the problem so I'll look into that a little more.
Answer: Temporary solution:
As the HTML document I want to insert into is just a template I'm copying it into the code and just building the entire string and loading it into the UIWebView:
e.g. NSString *s = @"<div1></div1><div2>%@</div2>", contentToInsert.
Ideally I still want to get this working as if I can insert the HTML via JS I can use multiple HTML templates and just fit the content into them as needed. So if you can find a solution please let me know.

UIWebView can't inject HTML


Specify LMM in lme4 with two predictors but random intercepts for just one of both predictors

Question: I want to specify a linear mixed model with one dependent variable (DV) and two independent variables (IV). Furthermore, I want to add random intercepts for each of my participant but just for my first (IV1) and not the second (IV2) independent variable. How do I specify that using lme4 in R?
Currently I use the following specification, which in my understanding includes the random intercepts for both of my IVs.
DV ~ 1 + IV1 + IV2 + IV1:IV2 + (1|participant).
With IV1 and IV2 being my fixed effects, IV1:IV2 representing an interaction between my fixed effects and (1|participant) representing my random intercepts.
However I want to specify random intercepts per participant for my IV1 only. How do I do that?
Thanks a lot :)
Answer: It makes no sens to add a random intercept "for an independant variable". A random intercept is as its name suggests an intercept. You can see it a a kind of bonus/penalty for each participant added to the regression formula (this is not exactly the case). However, you can also change the slope of independant variables according to the participant. In that case, you will add a bonus/penalty to the global coefficient depending on the participant.
So this formulation is the random intercept only :
DV ~ 1 + IV1 + IV2 + IV1:IV2 + (1|participant)
Here you have a random slope only for IV1 :
DV ~ 1 + IV1 + IV2 + IV1:IV2 + (0 + IV1|participant)
And here both of them combined :
DV ~ 1 + IV1 + IV2 + IV1:IV2 + (1 + IV1|participant)
You could read the vignette of the lme4 package to get a better grasp on mixed effect models (https://cran.r-project.org/web/packages/lme4/vignettes/lmer.pdf)
I hope it will help !
Comment: Thanks for the answer and clarification.

Luckily I arrived at the same conclusion myself after thinking it through once more. The random intercept of course refers to how high the intercept per participant is with regard to my DV right? So it makes no sense to specify it per IV.

I am confused though by the way you specified the combination of two random slopes though. I thought it should look like this:

DV ~ IV1 + IV2 + IV1:IV2 + (1 + IV1 + IV2 | participant)
Comment: yes,  DV ~ IV1 + IV2 + IV1:IV2 + (1 + IV1 + IV2 | participant) is the way to go to have a random slope for both. Note that the model will estimate also the correlations between your random effect. These parameters can be very interesting to analyze bet require enough data and participants. You could also specify independant random effects with : DV ~ IV1 + IV2 + IV1:IV2 + (1 | participant) +  (0 + IV1  | participant) +  (0 + IV2  | participant)


RxJava: window/buffer overload questions, incompatibility with Rx.NET?

Question: I'm reading http://www.introtorx.com/content/v1.0.10621.0/17_SequencesOfCoincidence.html#SequencesOfCoincidence and found the following part there about the window operator:
"The first of these complex overloads allows us to control when windows should close. The windowClosingSelector function is called each time a window is created. Windows are created on subscription and immediately after a window closes; windows close when the sequence from the windowClosingSelector produces a value. The value is disregarded so it doesn't matter what type the sequence values are; in fact you can just complete the sequence from windowClosingSelector to close the window instead."
This seems to be different than the public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) method documentation and behavior. My tests show that the Func0 to produce the closing observable is only ever called once, neither does completing this observable work as described above - only one window is ever created. This method actually works the same as the public final  Observable<Observable<T>> window(Observable boundary) method, with the exception that the boundary is passed directly and not with a function. Judging by the source code, the latter/simpler method just calls into the former/more complicated one by wrapping the passed boundary into a Func0 which just returns it.
Questions:

It would seem the behavior of RxJava's public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) might be wrong, unless the book is wrong or the newer versions of Rx.NET, with which RxJava is compatible, changed. Is this a deliberate incompatibility between Rx.NET and RxJava?
Should the incompatibility be the correct behavior, why does RxJava have 2 window overloads which actually do pretty much the same? I don't see any clear advantage of having the overload with a function creating the window closing observable if it doesn't take any arguments and is ever going to be called once. Ok, it makes creation of the observable lazy, but I think this could be achieved with the defer method.
What adds to the confusion is the fact that the marble diagrams for the two overloads are slightly different (the arrows are). Maybe I just don't understand the real difference there?

The same two overloads exist for the buffer method.
Here is some code, more or less a port from the mentioned article. Each line of input closes the current and opens a new window, unless it is 'q' (case insensitive), in which case the whole thing finishes.
Observable<Long> source = Observable.interval(1L, TimeUnit.SECONDS);
PublishSubject<Object> closer = PublishSubject.create();

Subscription s = source
        .window(() -> {
            System.out.println("!!! creating window closer");
            return closer;
        })
        .subscribe(new Subscriber<Observable<Long>>() {

            private int idx = 0;

            @Override
            public void onNext(Observable<Long> window) {
                ++idx;
                System.out.printf("+++ starting new window%n");
                String windowName = "window " + idx;
                window.subscribe(new Subscriber<Long>() {

                    @Override
                    public void onNext(Long aLong) {
                        System.out.printf("%s -> %d%n", windowName, aLong);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // nothing
                    }

                    @Override
                    public void onCompleted() {
                        System.out.printf("--- %s completed%n", windowName);
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                // nothing
            }

            @Override
            public void onCompleted() {
                System.out.println("completed");
            }
        });

Scanner scanner = new Scanner(System.in);
String input;
do {
    input = scanner.nextLine();
    closer.onNext(input);
    //closer.onCompleted();
} while (!"q".equalsIgnoreCase(input));
s.unsubscribe();

Replacing the closer.onNext() line with closer.onCompleted() breaks the application - only one window is ever created.
Comment: This looks like a discrepancy between the two implementation. When RxJava window was implemented, the exact behavior of the .NET version was still unclear. You should bring up this issue on the RxJava github page. Regardless, completing the PublishSubject might not be a good idea because it will just complete the main sequence.
Answer: As suggested, I brought the question up at the Github page and it has been fixed: https://github.com/ReactiveX/RxJava/issues/3053.


How to get an Element inside a RadPageView inside a RadMultiPage?

Question: I have html-code like this:
<telerik:RadMultiPage ID="MultiPage" runat="server">
   <telerik:RadPageView ID="TablePage" runat="server">
      <Cx:DataObjectDefinitionTree ID="TableOverview"   runat="server"/>
   </telerik:RadPageView>
</telerik:RadMultiPage>

I can get the Multipage by this: var multiPage = $find('<%= MultiPage.ClientID %>');
But i am not able to get either the PageView or the DataObjectDefinitionTree.
Though i need the DataObjectDefinitionTree.
I tried to get the PageView from the MultiPage and then the DataObjectDefinitionTree from that but that did not work either.
How can i get the DataObjectDefinitionTree into an Variable in Javascript?
Edit:
I just want to call two methods from DataObjectDefinitionTree (it is basicly the same as a RadTreeView).
These methods are _getAllItems() and get_selectedNode().
Answer: Telerik's Client-Side API is pretty complete, see by yourself:
var multiPage = $find('<%= MultiPage.ClientID %>');
var pageView = multiPage.findPageViewByID("TablePage");

As for the DataObjectDefinitionTree, you should be able to get the DOM element for the pageView:
var domElement = pageView.get_element();
dataObjDefTree = domElement.getElementById('<%=TableOverview.ClientID %>');

Or you can try something like this:
var dataObjDefTree = document.getElementById('<%=TableOverview.ClientID %>');

Comment: Yeah, well i tried it that way and came pretty far (i had something wich seemed like the `DataObjectDefinitionTree` but wasnt if i try it exactly like you i get an Error while `var domElement = pageView.get_element();` because pageView is null...
Comment: pageView is null even if you assign the variable using the first 2 lines (`multiPage.findPageViewByID`)?
Comment: Yes, i used all four lines. And when i use the fifth line `dataObjDefTree` is null as well.
Comment: Ok, then I guess it would help if you tell what you want to do with `DataObjectDefinitionTree`.(Edit your question)
Answer: Ok then, the main problem here is How to access your WebUserControl's javascript from the parent page. You'll need to wrap your DataObjectDefinitionTree's content in a div using the same ID as your UserControl. Here is a link explaining this.
Then from the UserControl, declare your own functions accessing RadTreeView's Client-Side API (_getAllItems() and get_selectedNode()).
Comment: Well it does not seem to help. Because since i got my element i have already access to the functions. Now i think i spottet the Error. When i write `$find('<%=TableOverview.ClientID %>')` the ID i get is `CPH_TableOverview` although the ID i need to get is like `ctl00_CPH_TableOverview_TableTree`. Thats the reason the `dataObjDefTree` is null. But why does `$find('<%=TableOverview.ClientID %>')` gives me a wrong ID?
Answer: Ok, i found the Error:
<%=TableOverview.ClientID %> gives the wrong ID.
To get the correct ID i had to add the following to my ASPX-Control DataObjectDefinitionTree:
public override string ClientID {
get { return TableTree.ClientID; }
//TableTree is the base object of DataObjectDefinitionTree
}
Now i get the correct ID when i call <%=TableOverview.ClientID %>.
Thanks for your help, though. :)


Drupal Search API Placeholder && Front Page?

Question: I'm trying to get some placeholder text working for the Search API form, but have a different placeholder on the front page. Here's what I have so far which does work everywhere...
function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext'])) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search Text here...');
  }
}

How can I get this working on only the front page, with a different placeholder text on all other pages? I've tried many things and totally stumped at the moment. Any help would be appreciated.
Answer: Check for drupal_is_front_page()

Return value
Boolean value: TRUE if the current page is the front page; FALSE if
  otherwise.

function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext']) && drupal_is_front_page()) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search Text here...');
  }
}


C# AWS Lambda Function - Could not find the specified handler assembly with the file name 'LambdaTest, Culture=neutral, PublicKeyToken=null'

Question: I am trying to create a "Hello, World" AWS Lambda function, with one minor change: I need to deploy it using a .zip file. In an effort to accomplish this, I've done the following:
From the Terminal Window

Initialized a new AWS Lambda function using dotnet new lambda.EmptyFunction --name myFirstFunction --profile default --region us-east-1

cd into myFirstFunction

Run dotnet publish ./src/myFirstFunction/myFirstFunction.csproj

Navigate into ./src/myFirstFunction/bin/Debug/net6.0/publish

Compress all of the files into a single file named Archive.zip.

From AWS Console in the Browser

Navigate to the myFirstFunction Lambda function.

Click "Upload from -> .zip file" in the "Code Source" section

Choose Archive.zip

Navigate to the "test" tab once successfully uploaded

Click the "Test" button in the "Test event" section

At this point, I receive an error that says:
{
  "errorType": "LambdaValidationException",
  "errorMessage": "Could not find the specified handler assembly with the file name 'LambdaTest, Culture=neutral, PublicKeyToken=null'. The assembly should be located in the root of your uploaded .zip file.",
  "stackTrace": [
    "at Amazon.Lambda.RuntimeSupport.Bootstrap.UserCodeLoader.Init(Action`1 customerLoggingAction) in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/UserCodeLoader.cs:line 95",
    "at Amazon.Lambda.RuntimeSupport.Bootstrap.UserCodeInitializer.InitializeAsync() in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/UserCodeInitializer.cs:line 46",
    "at Amazon.Lambda.RuntimeSupport.LambdaBootstrap.InitializeAsync() in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/LambdaBootstrap.cs:line 155"
  ]
}

I'm unsure how to fix this. I do not see "LambdaTest" in any of the config files. So, I have no idea where that identifier is coming from. What do I need to do to get this based Lambda function working via the "test" tab in the AWS Console?
Answer: What happens is that AWS is not able to indentify where your function handler is.
When you create a Lambda in AWS, by default it assigns a LambdaTest handler.
During the deployment of your Lambda code, you need to ensure you are deploying a correct handler for your function.
I could be more helpful if I knew your code and the solution structure, but lets give a try.
Under /src/myFirstFunction you might have a file called aws-lambda-tools-defaults.json. In that file, there will be a key "function-handler" and the value should point to your function handler, in the format: <project_name>::<namespace>.<class>::<method_name>
Imagine you have:
namespace Farm
{
    public class Banana
    {
        public string Harvest(string season, ILambdaContext context)
        {
            ...
        }
    }
}

Your handler should be myFirstFunction::Farm.Banana::Harvest
More info on: https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/lambda-creating-project-in-visual-studio.html

If you not using Visual Studio:

Access AWS Management Console;
Navigate to your Lambda function myFirstFunction;
Under the Code tab, you will see the Runtime settings. Press Edit;
Change the handler name according to the format I mentioned above (<project_name>::<namespace>.<class>::<method_name>);
Save and test
Comment: @Fabio Absolutely brilliant explanation. Simple, clear, and to the point.
Comment: This helped me a ton! If you are using Visual Studio and the Mock Lambda Test Tools you can look at the serverless.template file and the value will be in there too


Expanding squares and simplification of equations

Question: as i'm reading a paper "An Underdetermined Linear System for GPS" By Dan Kalman
i understand the paper but when i traced the equations there's something i don't understand ,may be my mathematics is not good,the thing is according to the Table 1. Satellite data. in the paper he begins to calculate equations which as is follow:
d = .047(t − 19.9). This same distance can be expressed in terms of (x, y, z) and the satellite's position (1, 2, 0): d = sqrt((x − 1)2 + (y − 2)2 + (z − 0)2). Combining these results leads to the equation (x − 1)2 + (y − 2)2 + z2 = .0472(t − 19.9)2. (1)
Algebraic Solution. Let us focus again on the equation for the first satellite: (x − 1)2 + (y − 2)2 + z2 = .0472(t − 19.9)2. Expanding all the squares and rearranging leads to this version: 2x + 4y − 2(.0472)(19.9)t = 12 + 22 − .0472(19.9)2 + x2 + y2 + z2 − .0472t2. (here's my problem)
the equation which i denoted (here's my problem),i don't understand how it is simplified to this form and how the equation for t appears on both sides of the equation.
here's the link to the paper:http://mathdl.maa.org/images/upload_library/22/Polya/Kalman.pdf
Answer: $$(x-1)^2+(y-2)^2+z^2=0.047^2(t-19.9)^2$$
$$(x^2-2x+1^2)+(y^2-4x+2^2)+z^2=0.047^2t^2-2\cdot 19.9\cdot 0.047^2t+19.9^2\cdot 0.047^2$$
$$-2x-4y+2\cdot 19.9\cdot 0.047^2t=0.047^2t^2-1^2-2^2-x^2-y^2-z^2+19.9^2\cdot 0.047^2$$
$$2x+4y-2\cdot 19.9\cdot 0.047^2t=-0.047^2t^2+1^2+2^2+x^2+y^2+z^2-19.9^2\cdot 0.047^2$$
Comment: thanks very much i was missed


How can Poisson GLM work with non-count data (rate data)?

Question: My question is related, but not the same as the following question:  Fitting a Poisson GLM in R - issues with rates vs. counts
Here's some fake data:
### some fake data
x=c(1:14)
y=c(0,  1,  2,  3,  1,  4,  9, 18, 23, 31, 20, 25, 37, 45)
y_rate <- y / 1000

I'm going to use a Poisson GLM with a log link to predict y_rate:
### model
pois_mdl <- glm(y_rate ~ x, family=poisson(link="log"))
summary(pois_mdl)

Plot the fit:
### plot
plot(x, y_rate)
lines(x, pois_mdl$fitted.values)

I am surprised that Poisson glm() allows for non-integer values in the dependent variable. Draws from a Poisson distribution are always integers (regardless of the value of the mean parameter). Why doesn't glm() blow up?
Comment: http://stats.stackexchange.com/questions/70054/ seems duplicate
Answer: I don't know why glm() doesn't blow up.  To figure that out, you'll have to unpack all of the underlying code.  (In addition, if your only question is how the R code works, this question is off topic here.)
What I can say is that you are not modeling the rates correctly.  If you want to model rates instead of counts, you need to include an offset in the model's formula.  (There is a nice discussion on CV of what an offset is here: When to use an offset in a Poisson regression?)  Using your example the code would be:
pois_mdl2 <- glm(y~x+offset(log(rep(1000,14))), family=poisson(link="log"))

Note that, although the coefficient estimates are the same, the standard errors are quite different:
summary(pois_mdl2)$coefficients
#               Estimate Std. Error   z value      Pr(>|z|)
# (Intercept) -6.5681214 0.25118701 -26.14833 1.029521e-150
# x            0.2565236 0.02203911  11.63947  2.596237e-31
summary(pois_mdl)$coefficients
#               Estimate Std. Error    z value  Pr(>|z|)
# (Intercept) -6.5681214  7.9431516 -0.8268911 0.4082988
# x            0.2565236  0.6969324  0.3680753 0.7128171

Answer: While I don't recommend looking at the source code for glm for those that wish to preserve their mental health, I looked at the source code to glm.  The reason R doesn't blow up seems to be that it just doesn't bother to do the kind of defensive checks it probably should.
The main iteratively re-weighted least squares loop works by using the methods attached to a family object of the appropriate type.  In this case, that is poisson:
> poi <- poisson()
> class(poi)
[1] "family"

This family object has all that glm needs to fit the model, for example:
> poi$linkfun(1)
[1] 0
> poi$linkinv(1)
[1] 2.718282

Another, here's the derivative of the inverse link:
> poi$mu.eta(1)
[1] 2.718282

The y data comes in on line 258:
dev <- sum(dev.resids(y, mu, weights))

Unfortunately, dev.resids could not care at all whether y is positive integer valued:
> poi$dev.resid(1.5, 1, 1)
[1] 0.2163953

So I guess R doesn't blow up because it didn't think to blow up.
Comment: The check, if there was one, would most likely occur in `poisson()$initialize`, which only checks that the `y`s are non-negative.

Compare it to `binomial()$initialize`, which, along with dealing with the possible one- or two-column specification of `y`, also checks that they are integer-valued.
Comment: +1, lol. There was a reason I didn't actually look at the source code myself ;-).
Comment: Nice @Mark, I missed that.


is $f(x)=[x]+(x-[x])^{[x]}$ uniform continuous on $(0,+ \infty )$?

Question: Is $f(x)=[x]+(x-[x])^{[x]}$ uniform continuous on $(0,+ \infty )$ ?
It is clear that $\lim_{x \to +\infty } f(x) $ does not exist. Is this an alternative function ?
Comment: How do you define $[x]$?
Comment: [x] is the largest integer less than or equal to x .
Answer: $$\begin{align}
x\in(0,0.5)\Rightarrow
f(x)
&=0+(x-0)^0
\\
&=1
\\
x\in(0.5,1)\Rightarrow
f(x)
&=1+(x-1)^1
\\
&=x
\end{align}$$
So $f(x)$ is discontinuous at $x=0.5$ since it approaches $1$ from the left and $0.5$ from the right, which implies that $f$ is also not uniformly continuous.
Comment: [x]=0 if 0<x<1 but in your answer for .5<x<1 [x]=1. I define [x] in above.
Comment: @amirbahadory I see. Normally you would define $[x]$ as the closest integer to $x$, and notate your function as $\lfloor x \rfloor$. It'd probably be easier to define your function in the question next time :)


SSH RemoteForward fails with shared Control Socket

Question: My ~/.ssh/config contains:
ControlMaster auto
ControlPath ~/.ssh/socket-%r@%h:%p

Host hostname.example
    # TextMate rmate port
    RemoteForward :52698 localhost:52698

When I make an initial connection to the host, it successfully creates the master socket file at ~/.firstname.lastname@example.com:22.
But when I open a new terminal and attempt to make a second connection, I get this error:
$ ssh hostname.example
mux_client_forward: forwarding request failed: remote port forwarding failed for listen port 52698
muxclient: master forward request failed
ControlSocket /email@example.com:22 already exists, disabling multiplexing
Warning: remote port forwarding failed for listen port 52698

But if I comment out the RemoteForward line in the config, it's able to successfully reuse the connection, making it connect faster.  Is there any way I can configure ssh to support both multiplexed connections and enable the remote port forwarding, such that it only attempts to forward the port if it's the master connection?
My system:

macOS Sierra 10.12.6
OpenSSH_7.4p1, LibreSSL 2.5.0
Answer: I figured out a solution.  I use the Match section with the host and negated exec keywords to test for the hostname and the existence of the control socket file. If the file doesn't exist, then this is the master connection, so setup the port forwarding. Otherwise, this is a slave connection and the forwarding is skipped.
ControlMaster auto
ControlPath ~/.ssh/socket-%r@%h:%p

Match host hostname1.example.com,hostname2.example.com !exec "[ -e ~/.ssh/socket-%r@%h:%p ]"
    # TextMate rmate port
    RemoteForward :52698 localhost:52698

Comment: Good stuff! For people looking to create a LocalForward or DynamicForward, change `!exec "[…]"`into `exec "[ ! -S ~/.ssh/socket-rmate ] && ln -sf ~/.ssh/socket-{%r@%h:%p,rmate}"` so if you're already connected to hostname1, you'll be safe connecting to hostname2 since it's checking a shared socket thanks to the symlink. This uses bash/zsh [Brace Expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) to more concisely create that link (ssh runs it in `$SHELL`). This must use `-S` rather than `-e` so it can operate on an existing-yet-broken symlink.
Answer: Here's another solution that does not depend on ControlMaster:
Match host hostname1.example.com,hostname2.example.com !exec "nc -zw1 %h 52698"
    RemoteForward :52698 localhost:52698

This also works for local port forwarding and SOCKS proxying:
Match host hostname1.example.com,hostname2.example.com !exec "nc -zw1 localhost 52698"
    LocalForward 52698 remotehost:52698

Match host hostname3,hostname4 !exec "nc -zw1 localhost 1050"
    DynamicForward 1050

# Test for multiple ports
Match host hostname5 !exec "nc -zw1 localhost 52698 && nc -zw1 localhost 1050"
    LocalForward 52698 remotehost:52698
    DynamicForward 1050

These work by checking to see if the target port is opened. If not, it creates the desired port forwarding. netcat is a great tool for quick network tests and redirection. The -z option instructs netcat to just scan for whether a daemon is listening on the given port. -w1 says you should wait at most one second in the event your packets are ignored e.g. due to a DROP firewall policy.


How do I get Samba to use a specific domain controller?

Question: Currently, I have Samba on Ubunut Linux 16.04 connecting to a domain controller.  When I joined, I joined to ad-1.example.com; however, after two weeks, it found read-only-adc.example.com on its own subnet and proceeded to completely fail to function anymore.
Samba really, really doesn't like read-only domain controllers.
Thus far, I haven't found any way to force Samba to use the primary domain controller one subnet over, either by modifying /etc/krb.conf or putting false information in /etc/hosts (it finds the IP address without looking in the hosts file).
Does anyone know how to resolve this?
Answer: Sure. Put fully functional controllers to the /etc/krb.conf, add a password server = <name of the fully functional controller> to your smb.conf and rejoin samba to your domain, since samba actually keeps a copy of your krb.conf somewehere inside /var (this differs from distribution to distribution). Also, the step with the password server and actual /etc/krb.conf may be enough for itself.
Comment: I hadn't sufficiently read the documentation, and don't understand AD and LDAP very well.  Reading the `password server` documentation within the context of this answer suddenly makes plenty of sense.  Thanks!
Answer: I'm fairly certain you can just use a hosts entry to accomplish this. Just point example.com to that one domain controller. I'm not sure if you would need to invalidate read-only with a fake IP in the hosts file also, but you could try it if it keeps going back there.
Comment: It ignores /etc/hosts entries because it looks up via `lmhosts` and WINS first.  You can change this around with `name resolve order`.