How to use pointer from other classes in swift

Question: I'm immigrating my old ObjectiveC code to swift. In ObjcC had a separate class to handle my Admob activity.
In this class I've created a pointer in the init func, and when changing scene, I could use this pointer to change the location of the ads banner.
       @implementation MyAdsSupport

    +(id)ShowAds:(My_Ads_Position)posIndex
    {
        if (_adsBannerPointer == nil)
        {
            _adsBannerPointer = [[KTFAdsSupport alloc]initAds:posIndex];
        }
        else
        {
            [_adsBannerPointer setAdsPosition:posIndex];
        }
        return _adsBannerPointer;
    }

In Swift I created the Admob class, and managed to present ads on screen but when I try to call the pointer from another class it returns always nil.
Here is my Swift Code:
   var adsPointer: My_Ads_Support!

func initAds(myView: UIViewController, atPos: My_Ads_Position) -> KTF_Ads_Support {

    if adsPointer == nil {
        adsPointer = self
        adsPointer.ShowAds(myView: myView, atPos: atPos)
    }
    else
    {
        print("adsPointer ALIVE")
        adsPointer.setAdsPos( atPos: atPos)
    }
    return self.adsPointer!
}

How can I set a pointer in Swift to be able to reach the ads banner from any scene?
Answer: In your Objective-C code you have three methods, the instance methods initAds: and setAdsPosition:, and the class method ShowAds:. The latter uses a variable, presumably declared static, called _adsBannerPointer.
Your Swift code is not the same. It has two methods, the instance methods initAds and setAdsPos, and one variable, the instance variable adsPointer.
In Swift class methods are termed type methods (as they can belong to classes, structs and enumerations) and are indicated by the use of the keyword static, type (class) variables are also indicated with static. So to follow your Objective-C model you need something along the lines of:
static var adsPointer: My_Ads_Support!

// instance init
init(startingPos : My_Ads_Position) { ... }

// instance set position
fun setAdsPos(atPos : My_Ads_Position) { ... }

static func showAds(myView: UIViewController, atPos: My_Ads_Position) -> KTF_Ads_Support { ... }

HTH


How is it possible to stop a debounced Rxjs Observable?

Question: I created an observable, which will fire 3 seconds after the last change is made, and calls the publishChange of the service. It works, but I would like to create a doImmediateChange function, which calls publishChange immediately and stops the debounced observable. How is that possible?
My component:
class MyComponent {
    private updateSubject = new Subject<string>();

    ngOnInit() {
        this.updateSubject.pipe(
            debounceTime(3000),
            distinctUntilChanged()
        ).subscribe(val => {
            this.srv.publishChange(val);
        });
    }

    doChange(val: string) {
        this.updateSubject.next(val);
    }

    doImmediateChange(val: string) {

        // Stop the current updateSubject if debounce is in progress and call publish immediately
        // ??
        this.srv.publishChange(val);

    }

}

Answer: You can emulate debounceTime using switchMap and delay. Then cancel the inner Observable with takeUntil to prevent a waiting value from being emitted.
private updateSubject = new Subject<string>();
private interrupt = new Subject();

ngOnInit() {
  this.updateSubject.pipe(
    switchMap(val => of(val).pipe(
      delay(3000),
      takeUntil(this.interrupt)
    ))
  ).subscribe(val => publish(val));
}

doChange(val: string) {
  this.updateSubject.next(val);
}

doImmediateChange(val: string) {
  this.interrupt.next();
  publish(val);
}

https://stackblitz.com/edit/rxjs-ya93fb
Answer: Use the race operator:
The first observable to complete becomes the only observable subscribed to, so this recursive function will complete after one emission take(1), then resubscribe () => this.raceRecursive().
private timed$ = new Subject<string>();
private event$ = new Subject<string>();

ngOnInit() {
  this.raceRecursive()
}

raceRecursive() {
  race(
    this.timed$.pipe(debounceTime(1000)),
    this.event$
  )
    .pipe(take(1)) // force it to complete
    .subscribe(
      val => console.log(val), // srv call here
      err => console.error(err),
      () => this.raceRecursive() // reset it once complete
    )
}

doChange(val: string) {
  this.timed$.next(val)
}

doImmediateChange(val: string) {
  this.event$.next(val)
}

Answer: You could supply a value specific debounce time with every value and use debounce with timer to change the debounce time for values dynamically.
private updateSubject = new Subject<{ value: any, debounceTime: number}>();

ngOnInit() {
  updateSubject.pipe(
    debounce(({ debounceTime }) => timer(debounceTime)),
    pluck('value')
  ).subscribe(val => publish(val));
}

doChange(value: string) {
  updateSubject.next({ value, debounceTime: 3000 });
}

doImmediateChange(value: string) {
  updateSubject.next({ value, debounceTime: 0 });
}

This doesn't directly stop the debounced Observable but let's you "overwrite" a waiting value with a new one being emitted with zero delay.
https://stackblitz.com/edit/rxjs-j15zyq
(user733421 didn't seem to want to add a complete solution so I expanded the approach)
Answer: You can achieve this behavior using debounce and race:
with the code you provided
private destroy$ = new Subject<void>();
private immediate$ = new Subject<void>();
private updateSubject$ = new Subject<string>();

constructor(private srv: PubSubService) {}

ngOnInit() {
  this.updateSubject$.pipe(
      takeUntil(this.destroy$),
      debounce(() => race(timer(3000), this.immediate$))
  ).subscribe(val => {
      this.srv.publishChange(val);
  });
}

doChange(val: string, immediate?: boolean) {
  this.updateSubject$.next(val);
  if (immediate) this.immediate$.next();
}

// don't forget to unsubscribe
ngOnDestroy() {
  this.destroy$.next();
}

emitting an immediate change will replace the previous normal change (that is debounced for 3s) without the delay (thanks to our race observable).
here's a working example
Comment: This approach has the problem that your final Observable will emit the previous value if your source Observable emits its values asynchronously. e.g. if you replace your source Observable `this.updateSubject$` with `this.updateSubject$.pipe(switchMap(v => Promise.resolve(v)))` and do a normal change before you do an immediate change you will see that the value from the normal change will be emitted when instead the immediate value should be emitted. See: https://stackblitz.com/edit/angular-iugnvu
Comment: You're right but The OP hasn't said anything about async data. Your use case is irrelevant to the question and of course will need a different implementation to overcome this
Comment: Maybe, but it's always best to write code or operators that work for any source Observable not just for some specific ones, as people might want to use your solution in different cases than the one from the question. I also first tried to come up with a solution using `debounce` but ran into the same problem you did and couldn't come up with one working in all cases. Other than that it's a nice approach.
Comment: I kinda don't agree with you, there will never be an 'all-in-one' solution for observables and streams as any stream has a different purpose, I think that the solution to your case is to separate the streams: 1 stream that only handles publishing updates and another stream to handle async updates before publishing them:
https://stackblitz.com/edit/angular-kpwpmn
let me know what you think
Comment: But having a function that executes asynchronously in your pipe or somehow delays  a value to emit is quiet common. If you can come up with a solution that'll be nice :)
Comment: @fridoo did you saw the stackblitz i've provided?
Answer: The value for debounceTime is only evaluated once, on observable creation time.
To be able to dynamically update debounceTime, use debounce together with timer, like this :
 debounce(()=>timer(this.debounceTime)),

Comment: You should add an example of how this can be used to solve the problem.


Making a PHP JavaScript Chatroom

Question: I'm trying to make a PHP / JavaScript chat system for my website. How do you do this without refreshing the page?
JavaScript can:
--Dynamically add text to the textbox.
PHP can:
--Save chat to chat log files, and update the chatroom so everyone can see it.
The second part seems to require you to refresh the page. I don't want to refresh the page every time a user says something.
Is there a way to run PHP in the background without needing to do a POST or GET? Do I need to use a different server side language such as Python or Ruby? Any help would be appreciated.
Comment: Welcome to SO! The traditional answer is Ajax (Asynchronous Javascript). There's literally thousands of Ajaxified PHP chatroom tutorials on the interwebs. In the future web sockets will take over, but that day's not here yet.
Comment: Real time chat is a complicated system to engineer and implement, especially if you don't have a good understanding how the underlying technologies work.  Best advice is to search for a third party chat system ready-made to integrate.
Comment: php + js is not the best stack for this task imo, [node.js + js](http://chat.nodejs.org/) is.
Answer: You can retrieve chat messages in your msg.php file and use jQuery for refreshing it and include that to your main file.(Your main page will not take loading but it will refresh).
You can use Prototype for this its same like jQuery but very easy to use.
Comment: And We Hope There Is No More Need To Capitalize Each Word!
Answer: if you want to make a chat room application that uses only one log file, i.e. everyone on your site is logged into the same room, it is not that hard, using php and ajax with some jquery. here's the process: you want a user to type in a message and send it, correct?, you'll need a form for that:
<form name="message" action="">
    <input name="usermsg" type="text" id="usermsg" size="63" />
    <input name="submitmsg" type="submit"  id="submitmsg" value="Send" />
</form>

that's the markup for the form, next, you'll need something that seamlessly takes in the user input, whatever the user typed into the text box and sends it to a script, that's where ajax comes in:

after doing this, we need to see how the script post.php looks like and what it does, basically, it grabs the input sent to it via ajax and writes it into a file, the file is then loaded onto the webpage and all the messages sent between users can then be viewed, ajax is used further to reload the file after a certain amount time so that the user's are always up to speed with whatever messages it contains, here's the php script:
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];

$fp = fopen("log.html", 'a');
fwrite($fp, "
".$_SESSION['name'].": ".stripslashes(htmlspecialchars($text))."

");
fclose($fp);
}
?>

note that i've used a session, this is to get the name of the user that logged in and also output it to the log file.i'm sure you can see how the login system would fit into this, anyways, after writing data to the file, we need to upload it so the users can see:

<?php
if(file_exists("log.html") && filesize("log.html") > 0){
    $handle = fopen("log.html", "r");
    $contents = fread($handle, filesize("log.html"));
    fclose($handle);

    echo $contents;
}
?>

that's the division where the log file will be loaded, now, just one thing left, we need to reload the file after a certain amount of time, and maybe add an auto-scrolling feature:
//Load the file containing the chat log
function loadLog(){
    var oldscrollHeight = $("#inner").attr("scrollHeight") - 20;
    $.ajax({
        url: "log.html",
        cache: false,
        success: function(html){
            $("#inner").html(html); //Insert chat log into the #chatbox div
            var newscrollHeight = $("#inner").attr("scrollHeight") - 20;
            if(newscrollHeight > oldscrollHeight){
                $("#inner").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
            }
        },
    });
}
setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

and that's it, that should work, hope this helps in case you've not yet gotten a useful answer, you would have waited a long time.
Comment: This is for sure HOW NOT TO do chat rooms. You are writing into html file directly? Why not TXT or better yet, use mysql like you should. With AJAX chat room, you are not showing, how to avoid multiple calls to the server issue. Also, what is stopping it to double-call the server?
Comment: Well, it's not the best way to go, but it works. And if you read the question, he implied he wanted to use log-files: "PHP can: --Save chat to chat log files, and update the chatroom so everyone can see it." So I gave an answer that would use that approach. The best way would be to use web sockets, but again, I just gave an answer based on what he was looking for; an approach using files. To save to TXT, just change the extension from html to txt.
Answer: If you don't want the page to refresh you can use Ajax post. Here is an implementation.
http://css-tricks.com/jquery-php-chat/
If it is a small scale site then it's fine. Otherwise I would recommend using Erlang or Go programming to power your chat!
Answer: AJAX should suit your needs; it can send data from JS to be processed by PHP, and receive any returned objects to be processed by JS again.
Tutorial: http://css-tricks.com/jquery-php-chat/ or
http://code.jenseng.com/jenChat/
Answer: There are a few ways to do this with Javascript and PHP. The most basic one is to send your Javascript POST requests through Javascript's XMLHttpRequest function. This lets you send and receive data without reloading the page. Google "AJAX" for info on how to send data that way and handle the results.
PHP takes these as regular POST requests, so you can do whatever you want with them on the backend in terms of returning data. But you're using PHP to return data, not to send a new webpage, so you can just send text over the wire, in the simplest way of doing this.
For the purpose of a chatroom, AJAX would require your javascript code to poll the server every few seconds to see if any new chats had come in. That's not very effective. What you really want is something on the server that can keep a connection open to the client and tell it when something has changed. For that you need to use Websockets in javascript, and create a PHP socket server. How to actually do both of those things is outside the scope of this answer. But it is possible using the technology you're talking about.

Making a PHP JavaScript Chatroom


How do I change pages and call a certain Javascript function with Flask?

Question: I am not sure if I worded my question correctly. I'm not actually sure how to go about this at all.
I have a site load.html. Here I can use a textbox to enter an ID, for example 123, and the page will display some information (retrieved via a Javascript function that calls AJAX from the Flask server).
I also have a site, account.html. Here it displays all the IDs associated with an account.
I want to make it so if you click the ID in account.html, it will go to load.html and show the information required.
Basically, after I press the link, I need to change the URL to load.html, then call the Javascript function to display the information associated with the ID.
My original thoughts were to use variable routes in Flask, like @app.route('/load/<int:id>') instead of simply @app.route('/load')
But all /load does is show load.html, not actually load the information. That is done in the Javascript function I talked about earlier.
I'm not sure how to go about doing this. Any ideas?
If I need to explain more, please let me know. Thanks!
To make this more clear, I can go to load.html and call the Javascript function from the web console and it works fine. I'm just not sure how to do this with variable routes in Flask (is that the right way?) since showing the information depends on some Javascript to parse the data returned by Flask.
Flask code loading load.html
@app.route('/load')
def load():
    return render_template('load.html')

Flask code returning information
@app.route('/retrieve')
def retrieve():
    return jsonify({
        'in':in(),
        'sb':sb(),
        'td':td()
    })

/retrieve just returns a data structure from the database that is then parsed by the Javascript and output into the HTML. Now that I think about it, I suppose the variable route has to be in retrieve? Right now I'm using AJAX to send an ID over, should I change that to /retrieve/<int:id>? But how exactly would I retrieve the information, from, example, /retrieve/5? In AJAX I can just have data under the success method, but not for a simple web address.
Comment: Can you show us your flask app code?
Comment: I added the flask app code.
Comment: My thought right now is that I have to parse the data and render it all in Flask. is this right?
Answer: You can specify param in url like /retrieve/<page>
It can use several ways in flask.
One way is
@app.route('/retrieve/', defaults={'page': 0})
@app.route('/retrieve/<page>')
def retrieve():

    if page:
        #Do page stuff here

    return jsonify({
        'in':in(),
        'sb':sb(),
        'td':td()})

Another way is
@app.route('/retrieve/<page>')
def retrieve(page=0):

    if page:
        #Do your page stuff hear

    return jsonify({
        'in':in(),
        'sb':sb(),
        'td':td()
    })

Note: You can specify converter also like <int:page>
Answer: Suppose if you are passing the data into retrieve from the browser url as
www.example.com/retrieve?Data=5

you can get the data value like
dataValue = request.args.get('Data')


Can I avoid operating DNS on a domain by using only a glue record?

Question: I was thinking that I might be able to get away with simplifying DNS by foregoing the usual delegation setup and not operating DNS for my domain, instead relying only on the glue records in the TLD root.
Of course if I do this, it isn't possible to do things like have many subdomains, a prioritized MX record, delegated subdomains, and such, but will it work at all?

UPDATE
I tested that, and it didn't work (I don't remember where I got this information in the first place).  Why?
Comment: I want some of whatever your on.
Comment: @MounirAhmina The disadvantage is that it's not possible. You're asking about the performance disadvantage of buying a car, but not using the engine.
Comment: If it's working at all, then there is an A record somewhere and you just don't know it. What is the domain name for this website? I'll dig the zone quickly and prove it to you.
Comment: Your question is very confusing but it sounds like you're planning on not having a domain name at all and just telling people your IP address.  I hope it's a simple one like `18.104.22.168`.  Of course, that one's already in use.
Comment: If you think choosing between `example.com` and `www.example.com` is going to make a significant difference in the load times of your website, you're very confused about how DNS works.  Likewise with running your own name servers on the same host as the website.
Comment: Maybe you could elaborate on how you plan on using DNS without a DNS server.
Comment: I said no DNS server, It is like point a domain name directly (The most far to directly) to a IP, Without any DNS records as A, CNAME... It is work great... But did it have any disadvantages?
Comment: DNS doesn't take time if I don't have the record cached. If you set it up now, I will be able to see it immediately, as my resolvers have not cached a previous response for your zone.
Comment: Did you even read what I write?
Comment: I'm talking about using DNS of course, But not a "DNS server".
Comment: @MDMarra I test that before, I'll re set up it... As you know DNS take time... I'll notify you when I set up it...
Answer: You can't create NS/glue records at your registrar, point them to the IP of your web server, and have users on the internet resolve your domain name properly. That's not how it works. You need a DNS server in the mix to host the A records for your domain - whether you self-host it or your registrar hosts it, or you have a third party host it is immaterial, it still needs to exist somewhere.
The end.

I feel the need to update this, because you have some crazy ideas about how DNS works that you've revealed throughout the comments. I'd like to address them here so that it will be useful to future visitors.
First read the Wikipedia DNS article before you do anything else. It's full of good information.
Next, I'll post the content of a comment on Joel's answer:

You have to have an authoritative server for your zone somewhere. When you register NS records for DNS servers, those servers are designated as authoritative for the zone by the registrar. Then, your A records and other records in that zone are what is used by recursive DNS resolvers like Google, your ISP, and others across the Internet. You still need an authoritative source of information for your zone. It is entirely possible to host this whole zone at your registrar instead of on your web server - but that's not how you asked your question

What is likely happening is that your registrar also has a DNS hosting service that they offer for you. This is not required and is not available across all registrars. There is no requirement that your web server should host your DNS, and in fact web servers do not act as DNS servers in large organizations. So, in a sense, you're on the right track by not hosting your DNS zones on your web server. Where you fall off of the rails are statements like this:

The glue DNS that point to my website will be hosted on your internet provider, Google DNS and on every DNS server on the world

That statement betrays your lack of understanding. What happens is addressed in my earlier comment. Most likely, you've created an A record for your domain on your registrar's DNS hosting, which is authoritative for your zone, since you haven't specified alternate DNS servers. There's no magic here. DNS lookups are still happening. They're just happening against your registrar's servers instead of your own.
When I try to resolve example.com what happens is I ask my DNS server for example.com. If it has the record cached, then it will answer immediately. If not, it must locate your authoritative DNS servers or another DNS server on the internet with your records cached. This happens by either root hints or forwarders. These responses are typically only cached for as long as you've set the TTL field on the record being queried. After that period of time, that record's cache is invalidated and my DNS servers have to go through the process of locating your DNS servers again for the record.
So, no, google and my ISP don't "host" your records. They cache copies of it that they retrieve from your authoritative servers - which appear to be configured at your registrar without your knowledge/understanding. There must be a DNS resource record for your domain hosted by authoritative DNS servers somewhere on the Internet, otherwise name resolution for your domain simply will not work
The end, for real this time.
Answer: The obvious disadvantages to what you're planning are that

You're not gaining any advantage here. Seriously, you're not saving on DNS lookups and you're not saving any money either.
You're creating a highly non-standard configuration that will be a nightmare to maintain. Why will it be a nightmare? Precisely because it's not the standard way of doing things. Asking for help with it will be meaningless because no one hosts services this way.
Mail will be extremely problematic. Sending mail and especially receiving mail will be nearly impossible without some serious finangling.
Comment: @MounirAhmina You don't understand. What you're describing **does not work**. There is an A record for your domain, which points at your servers, somewhere. If you're not running a DNS server on your web servers, then it's somewhere else like your registrar. **You cannot resolve domain names on the internet without DNS** it's as simple as that.
Comment: @MounirAhmina that's not how it works. You have to have an **authoritative** server for your zone somewhere. When you register NS records for DNS servers, those servers are designated as authoritative for the zone by the registrar. Then, your A records and other records in that zone are what is used by **recursive** DNS resolvers like Google, your ISP, and others across the Internet. You still need an **authoritative** source of information for your zone. It is entirely possible to host this whole zone at your registrar instead of on your web server - but that's not how you asked your question
Comment: If I read his question correctly, he doesn't even want A records, or anything other than registrar glue for that matter, and he wants that glue to point to his web servers which won't be hosting a DNS server. Wat?
Comment: The advantages: No one will access my server to get something about DNS, Access my server only if you come for a HTTP or HTTPS request, The only thing that will be in my server is HIPHOP for PHP and MySQL... About the non-standard config... It is really a nightmare, I get scared when I thinking on that, I remember use that years ago (In the beginning of internet) with no problem, and I don't need mail...
Comment: That's not without DNS, It's without a DNS server hosted in my server, The glue DNS that point to my website will be hosted on your internet provider, Google DNS and on every DNS server on the world... Anyway, I'll contact you and update the question after set up it... Maybe the you're right and the glue DNS point with a DNS server using a NS, But like that I'll avoid the DNSception ^^


How do different strings (of the same gauge) affect the tone?

Question: Something I've been wondering quite long, but never had the time to really try it out myself: Let's say I buy two sets of strings, both with the same gauge, a cheap one and an expensive one. What are the differences I can expect looking at following:

Durability
Staying in tune
Sound
Loudness
Anything else?

And, as a more general question: How and why (for example because they produce different overtones or whatever) can another type of string affect the sound, if they have the same gauge?
Comment: Gauge is essentially diameter.  Different metals, different windings, different production methods all contribute to the final elasticity as a function of wavelength. (which is what affects the overtone series' amplitudes)
Comment: I've started [a discussion about this question on meta](http://meta.music.stackexchange.com/questions/626/is-this-question-too-broad).
Answer: This reminds me of a very interesting article in Ultimate Guitar a while ago. I'll sum u the details of what it entailed:
The cost and brand of string does affect the tone/durability/volume etc. of your playing but guitar string production has came a long way over the years and we're pretty much out of ideas. There is difference in the quality of strings but - as long as you don't go for very poor quality strings - there is little difference really. Ever noticed how difference guitarists go for different strings? It's all about choice really. Your best bet is just trying out different brands/makes and finding which one best suits your ears and - of course - your wallet.


Any other ways I can stop the  page from being cached by boost?

Question: My drupal 7 site has Boost module (7.1.beta1, the version previous to the current release) installed and I didn't change any settings from the stock install. I saved the settings configuration with the <front> exception, generated the htaccess code, added it to my root htaccess file, turned Drupal core cache for anonymous users off... Everything works, ie, pages get cached to the boost cache directory and anonymous browsing is served from the boost cache. Only problem is that the front page is being cached even when my boost setting exception using the default <front> should be preventing the front page from being cached. I apologize if this is a redundant thread,I searched but mostly people have the opposite problem (ie, they want the front page cached-whereas I don't). I've also cleared the cache via /performance tab after enabling it and made sure there wasn't a boost cache for the front page .
Does anyone know why the boost exception setting isn't working for the front page? Is there perhaps another way to hack boost for this one page to not be 'boosted'? Thanks.
Comment: How does your exception look? Do you use ?
Comment: Yeah its the only thing in the exceptions text area.
Comment: The only thing i can imagine from my experience is that maybe there's still the frontpage-html files in the boost-cache folder. Other than that, i have no more suggestions...
Comment: Yeah, I cleared that boost cache folder and it just keeps regenerating back. Thanks for your suggestions, appreciate your help.
Comment: Just a note, but as the front page is most often hit, it's usually the one you want to ensure is cached / served rapidly.
Comment: Ordinarily we would want the front page cached, but we want content and feeds fresh as soon as possible on the front page, and almost all other pages don't get new content so we make the lifetime high.  We're having performance issues and although the homepage does take the most resources, and with no way to set multiple different Max cache lifetimes for different pages, we decided to not cache the front page.
Answer: What is the actual url of your front page?
If your frontpage is the default ( /node ) then you need to add both 'node' and '' to your exceptions list.
Boost treats them differently and keeps a copy of each page in the cache.
You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.
Comment: Thank you, Mike! The site's url is www.example.com, which is why i thought the default front exception would do it. After looking at site-information it appears that it wasn't that simple.. the url turned out to be www.example.com/3columns#. So I went back to boost, left the front default and added "3columns" to the list and sure enough, it doesn't get cached. Much Appreciated!
Comment: I appreciate that information as well! thx...


dblink does not exist even when the extension already exists?

Question: So I'm new to using dblink, I just created a script that inserts data into a table from another database. I received the error function dblink(unknown,unknown) does not exist.
So I checked online, and used CREATE EXTENSION dblink, ended up getting this message extension "dblink" already exists.
My dblink code is like this:
INSERT INTO tableA
 SELECT tbl.colA,tbl.colB,...
 FROM dblink('dbname=anotherDB', 'SELECT colA,colB,...
                 FROM tableB')
as tbl(colA,colB,...)

Answer: Check out in which schema the extension is installed. In my case this schema is ext:
select nspname as schema
from pg_extension e
join pg_namespace n on n.oid = e.extnamespace
where extname = 'dblink'

 schema
--------
 ext
(1 row)

Add the schema name to the search path, e.g.:
set search_path to public, ext;

or use the qualified name of the function dblink(), e.g.:
INSERT INTO tableA
 SELECT tbl.colA,tbl.colB,...
 FROM ext.dblink('dbname=anotherDB', 'SELECT colA,colB,...
                 FROM tableB')
as tbl(colA,colB,...)

Comment: it was the schema, had to change it from public to my schema


Extension of continuous functions on closed set

Question: Let $F\subset\mathbb{R}$ be a closed set, and $f:F\to\mathbb{R}$ is a continuous function. Show that there is a function $g$ defined and continuous on $(-\infty,\infty)$ such that $f(x)=g(x)$ for each $x\in F$.
The hint is telling that since $F^c$ is open, it's composed of a countable collection of disjoint open intervals, noted as $\bigcup_k (a_k,b_k)$. Then take $g$ to be linear in each of the intervals.
But I'm stuck when I'm try to prove $g$ is continuous considering the fact that a function separately continues on two sets may not continues on their unions. And I don't know how to apply the definition when every intervals like $(a_k-\delta,a_k)$ may contain points both in $F$ and $F^c$. So how should I deal with this problem?
Comment: if you can just show that $F$ is actually a bounded interval, then you can simply "attach" any continuous function at each endpoints so that $g$ is continuous at $(-\infty,\infty)$.
Comment: @EvanWilliamChandra I don't think $F$ is definitely an interval , it may be some single points.
Comment: How about dividing into two cases? First case is something like the characteristic function over rational numbers (possibly infinitely many points over zero measure set) whereas the other case is simply something similar to characteristic function over irrational numbers.

Not sure if this helps... Good luck!
Comment: Check this: https://math.stackexchange.com/q/301773/42969.
Comment: @MartinR Well, thanks for answering. But I've already how to construct $g$ but feel difficult to prove it's continuous, it's really not that obvious for me...
Answer: If $x_0 \in F^c$ then $g$ is linear in a neighborhood of $x_0$ and therefore continuous at $x_0$.
The more interesting case is to prove continuity at a point $x_0 \in F$: Given $\epsilon > 0$ there is a $\delta > 0$ such that $|f(x)-f(x_0)| < \epsilon$ for all $x \in F$ with $|x-x_0 |< \delta$. Now we consider two cases:
Case 1: The open interval $(x_0, x_0 + \epsilon)$ does not contain any point from the set $F$. In that case is $g$  linear on $(x_0, x_0 + \epsilon)$ with $\lim_{x \to x_0} g(x) = f(x_0) = g(x_0)$.
Case 2: There is a $ x_1 \in (x_0, x_0 + \epsilon) \cap F$. For every $x \in (x_0, x_1)$ is $g(x) $ either equal to $f(x)$, or a value between $f(a)$ and $f(b)$ with $x_0 \le a < x < b \le x_1$. In both cases is $|g(x) - f(x_0)| < \epsilon$.
This shows that $g$ is right-continuous at $x_0$. In the same way one can show that $g$ is left-continuous at $x_0$.
Comment: Case 1 needs the result that open intervals are connected in $\mathbb{R}$, imho.
Comment: @RomandadeGore: All intervals are connected, but at which point is that needed here? I currently do not see it, but I might miss something.
Comment: This guarantees that $(x_0,x_0 + \epsilon)$ lies in just one of the $(a_k,b_k)$, which gives a straightforward description of $g$. Of course, you will argue that this is evident, but I don't agree. In fact, showing that any point of $F$ either is interior to $F$ or is one of the $a_k,b_k$ is just the whole (always completely ignored) difficulty of the proof (and I would not know where to start with that).
Comment: @RomandadeGore: What we need (if I remember correctly after 1.5 years): 1) $F^c$ is  the countable union of disjoint open intervals $I_j$. 2) The endpoints of each $I_j$ are in $F$. 3) Every interval in $F^c$ is a subset of one of those intervals $I_j$. The last one is true because intervals are connected.


GdkPixbuf returns "gi._glib.GError: Couldn't recognize the image file format"

Question: I have a problem loading PNG images in Gtk3.
I have broken image symbols in my ToolButtons and after some investigation it appears that it comes from GdkPixbuf not being able to read the PNG files.
I have reproduced the problem with the python console
>>> from gi.repository import GdkPixbuf
>>> print(GdkPixbuf)
<gi.module.DynamicModule 'GdkPixbuf' from '/home/user1/ctcils/dusserm/applications/gobject-introspection/1.40.0/lib/girepository-1.0/GdkPixbuf-2.0.typelib'>
>>> GdkPixbuf.Pixbuf.new_from_file("/home/user1/ctcils/dusserm/applications/pycharm-community-3.4.1/bin/pycharm.png")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
gi._glib.GError: Couldn't recognize the image file format for file '/home/user1/ctcils/dusserm/applications/pycharm-community-3.4.1/bin/pycharm.png'

Many of the problems I faced in the last days were due to the fact we had to compile Gtk3, pygobject and all their dependencies and to install them in non-standard directories.
I suspect a problem with the gobject introspection (the last from a long list).
Comment: How did you go about building and installing these libs to non-standard directories?
Comment: I used the traditional cofigure/make/make install with the option --prefix. By non-standard I just mean that each library is installed in a specific directory on the NFS (some are installed in my home directory for the moment) and not on a common directory like /usr/local.
Comment: It seems that it is recommended to use JHbuild but we don't have a web access on the servers where we are installing.
Answer: I got a similar error with unusual prefix, and solved it by setting XDG_DATA_DIRS, which I didn't have set.
export XDG_DATA_DIRS=.../usr/share

Source: https://bugs.gentoo.org/644136
Answer: Not a full answer but some debugging tips: Check what image loaders gdk-pixbuf is providing (see also What image formats are supported by Gdk-Pixbuf (Gtk-Image?) by Default?). A Python snippet to check this:
from gi.repository import GdkPixbuf
for fmt in GdkPixbuf.Pixbuf.get_formats():
    print(fmt.get_extensions())

If nothing shows up, gdk-pixbuf is not finding any loaders which probably has something to do with the install location (--prefix and/or --libdir configure options). Verify you have loaders installed into the location gdk-pixbuf expects to find them (especially the png loader). This should be something like: <prefix>/lib[64]/gdk-pixbuf-2.0/<version>/loaders
See also: https://developer.gnome.org/gdk-pixbuf/stable/gdk-pixbuf-query-loaders.html
Comment: Looks like everything is in place. Pixbuf.get_formats returns a full list of image formats containing [png]. gdk-pixbuf-query-loaders has an entrey for png that points to libpixbufloader-png.so location. libpixbufloader-png.so is in place in the loaders directory. I checked for its dependencies with ldd and it looks fine. The loader-cache file is in place. I tried to setup GDK_PIXBUF_MODULEDIR and LD_LIBRARY_PATH without success.
Comment: I have 2 libpng installed in my system, libpng12.so.0.49.0 and libpng.so.3.49.0. libpixbufloader-png.so depends on libpng12. Is it normal ? During the configure I saw that it was looking for libpng16 in priority and that libpng12 was just a fallback. Could it be an explanation ?
Comment: Thanks for your help. Do you know if there is a real dependence between pixbuf and a specific version of libpng ?
Answer: It seems that the problem was due to the PNG library itself.
I am quite surprised considering that it comes from a regular CentOS rpm libpng-1.2.49-1.el6_2.x86_64 and that PNG is a stable standard for ages. In addition we did not have the problem with GTK2 that was using the same lib I suppose...
Anyway, I compiled a bright new libpng 1.6.2 from the sources, I re-configured and re-installed gdk-pixbuf and now it works.
Comment: Odd indeed, glad to see you figured it out.


Guest OS loses network connectivity after Host OS connects to VPN

Question: System Configuration:
Virtual Box version: VirtualBox-6.1.6-137129-Win
Host OS: Windows 10
Guest OS: Oracle Linux 8.1 (Virtual Box Guest Additions not installed in it yet)

VPN Software running on Host OS (Windows 10):
Cisco AnyConnect Secure Mobility Client
Version: 4.8.02045
Preferences of VPN Client: Screen Shot Attached

Internet Connectivity on Host OS is through WiFi interface Intel(R) Wireless-AC 9560 160MHz connected to my Home router.

I have configured Guest VM i.e. Oracle Linux with just 1 NAT network interface (with default settings nothing modified), when the host is not connected to VPN my Guest VM i.e. Oracle Linux is able to use hosts network i.e. I am able to browse Internet from Oracle Linux.

IP Configuration screen shot attached of Oracle Linux when VPN not connected in Host.
route print command executed on host machine (i.e. windows 10) output also attached before VPN connection.

Now I thought that I will make a connection to VPN from Host OS (i.e. Windows 10) and my Guest OS (i.e. Oracle Linux) should be also able to access the same VPN connection with the configured NAT interface but instead when Host makes a VPN connection Guest OS is not able to use any of the VPN resources neither the Internet. Nothing seems to be working. I tried taking wireshark dump on Oracle Linux machine after VPN connect but there nothing captured in wireshark at all totally blank.

IP Configuration screen shot attached of Oracle Linux when after VPN is connected in Host.
route print command executed on host machine (i.e. windows 10) output also attached after VPN connection.
VBox.log files also attached
Procedures I tried to troubleshoot the issue:

Tried Using older version of Virtual Box 5.2 but still found same issue there.
Tried using older version of Virtual Box 6.1.4 with and without VBoxGuestAdditions_6.1.7-137622 but still same issue there.
I wanted to install VBoxGuest Additions as mentioned in ticket virtualbox . org / ticket /19336 but link shared to patched VBoxGuestAdditions_6.1.97-136310.iso in the ticked is broken not accessible.
Executed below commands collectively and one-by-one also but still issue persists:
C:\Program Files\Oracle\VirtualBox> VBoxManage modifyvm "VM name" --natdnshostresolver1 on
C:\Program Files\Oracle\VirtualBox> VBoxManage modifyvm "VM name" --natdnsproxy1 on
C:\Program Files\Oracle\VirtualBox> VBoxManage setextradata global VBoxInternal2/HostDNSSuffixesIgnore 1
Tried Installing Cisco AnyConnect Directly in Guest OS(Oracle Linux), it shows that it is connected but still can't access Internet or any VPN sites.

If I configure Oracle Linux VM network adapter as Bridged then atleast I have internet connectivity on Oracle VM, when VPN is connected on windows host, but the goal is to use the same VPN connection to which Host System i.e. Windows 10 is connected.
Any help regarding this issue would be great.
All the logs can be downloaded from this link.
Comment: Have you tried this? https://windowsreport.com/vpn-not-working-on-virtualbox/
Comment: @pmdba Yes tried but not luck with this.
Answer: I was able to fix the issue by using proxy settings in my Guest OS same as my host OS:
Steps to resolve:

In Host OS (Windows 10), Go to control panel and type in search bar "proxy"
Click Configure Proxy server option, this will open Connections Tab in Internet Properties dialog.
Click LAN Settings Button and copy the link in the Address text box.
Now go to Guest OS that is Oracle Linux here, and open Network Settings.
Click configure Network Proxy Button and select radio button named "Automatic"
Finally paste the URL link copied on step 3 in the given text box.
Disable and Enable the connection and voila Guest OS now able to use host VPN connection.
Comment: Seems like sometimes organisations make use of proxy's which need to be taken care in guest OS
Answer: I was able to obtain connectivity to the internet from inside my virtual box machine with the following setup:

Host: Mac OS Catalina 10.15.7
Guest: Linux debian 4.19.0-12
In my host machine I have the Mullvad VPN app installed and activated.
I'm using a ethernet connection on my mac.
Virtual box network type is: Nat, with the Adapter type of Intel PRO/1000 MT Desktop

This is the configuration you need on your Debian/Linux machine:
In the network manager applet (top right corner) click the connection settings.
You need everything there in "automatic". I had a custom Open DNS setting before and that was causing the guest machine to not be able to resolve anything.
IPv4 tab
Turn off and back on the network connection so the changes take effect.
Turn off and back on the network connection
With this setup applied, when you check the first tab ("details"), you will see that, smartly, the DNS gets autopopulated for you with mullvad's SOCKS5 proxy and also the default route gets populated for you.
Details tab
Open a terminal window and you should now be able to:

Ping 22.214.171.124: This means your default gateway route is working
Ping google.com: This means your DNS setting is working
Answer: For me the alternate way to have at least internet connectivity on guest VM (VMware or VirtualBox with NAT adapter in my case) is to use on host OpenConnect GUI VPN client instead of Cisco Anyconnect client, because OpenConnect client doesn't perform such an aggressive traffic forwarding as Anyconnect does.
FYI OpenConnect supports the same protocol as Anyconnect. Also when running OpenConnect on host, I can also successfully run OpenConnect on guest VM to connect to VPN, thus I will have VPN on both (host and guest). List of GUI tools for OpenConnect for all platforms hosted here.


Galois Extension and Galois Group for $Q(\sqrt{2+\sqrt{2}})$

Question: I just need a little bit of help verifying and finishing this problem off:
Show that $\mathbb{Q}(\sqrt{2+\sqrt{2}})/\mathbb{Q}$ is a Galois Extension, and determine the structure of the Galois group.
proof:   Note that char$(\mathbb{Q})=0$, thus $\mathbb{Q}$ is perfect, that is, all irreducible polynomials in $\mathbb{Q}[x]$ are separable. Consider the polynomial $$p(x)=x^4-4x^2+2 \in \mathbb{Q}[x]$$ This is the minimal polynomial of $\sqrt{2+\sqrt{2}}$   over $\sqrt{2+\sqrt{2}}$. We also know that $$p(x)= \bigg(x-\sqrt{2+\sqrt{2}}\bigg)\bigg(x+\sqrt{2+\sqrt{2}}\bigg )\bigg(x+\sqrt{2-\sqrt{2}}\bigg)\bigg(x-\sqrt{2-\sqrt{2}}\bigg)$$ over $\mathbb{R}[x]$. So $p(x)$ is irredcible and has no repeated roots, i.e., $p(x)$ is separable. Now we show that $\mathbb{Q}(\sqrt{2+\sqrt{2}})$ is a splitting field over $\mathbb{R}$ for $p(x)\in \mathbb{Q}[x]$ in order to show that $\mathbb{Q}(\sqrt{2+\sqrt{2}})/\mathbb{Q}$ is a Galois Extension. Again for $$p(x)= \bigg(x-\sqrt{2+\sqrt{2}}\bigg)\bigg(x+\sqrt{2+\sqrt{2}}\bigg )\bigg(x+\sqrt{2-\sqrt{2}}\bigg)\bigg(x-\sqrt{2-\sqrt{2}}\bigg)$$ let $\alpha_1= \sqrt{2+\sqrt{2}}$, $\alpha_2=-\alpha_1$,  $\alpha_3=\sqrt{2-\sqrt{2}}$  and  $\alpha_4=-\alpha_3$. It is obvious that $\alpha_1,\alpha_2 \in \mathbb{Q}(\sqrt{2+\sqrt{2}})$. To show that $\alpha_3 \in \mathbb{Q}(\sqrt{2+\sqrt{2}})$, first consider $\alpha_3$ to be a element of $R$. Observe that $$\sqrt{2-\sqrt{2}}=\frac{\sqrt{2}\sqrt{2-\sqrt{2}}}{\sqrt{2}}=\frac{\sqrt{2}\sqrt{2-\sqrt{2}}}{\sqrt{2-\sqrt{2}}\sqrt{2+\sqrt{2}}}=\frac{\sqrt{2}}{\sqrt{2+\sqrt{2}}}$$ That is $\sqrt{2-\sqrt{2}}=\sqrt{2}(\sqrt{2+\sqrt{2}})^{-1}$. Since $\mathbb{Q}(\sqrt{2+\sqrt{2}})$ is a field, so we have that $\big((\sqrt{2+\sqrt{2}})^2-2\big)\in \mathbb{Q}(\sqrt{2+\sqrt{2}})$. However $$(\sqrt{2+\sqrt{2}})^2-2=\sqrt{2}$$ which means $\sqrt{2}\in \mathbb{Q}(\sqrt{2+\sqrt{2}})$. So $\sqrt{2-\sqrt{2}}=\sqrt{2}(\sqrt{2+\sqrt{2}})^{-1}\in \mathbb{Q}(\sqrt{2+\sqrt{2}})$ and $\alpha_i\in \mathbb{Q}(\sqrt{2+\sqrt{2}})$ for $i=1,..,4$. So $$\mathbb{Q}(\sqrt{2+\sqrt{2}})=\mathbb{Q}(\alpha_1, \alpha_2, \alpha_3, \alpha_4)$$ and so $\mathbb{Q}(\sqrt{2+\sqrt{2}})$ is a splitting field over $\mathbb{Q}$ for $p(x)$, hence $\mathbb{Q}(\sqrt{2+\sqrt{2}})/\mathbb{Q}$ is a Galois Extension.
For the seconed part Let $G=Gal(\mathbb{Q}(\sqrt{2+\sqrt{2}})/\mathbb{Q})$. We have that $|G|=[\mathbb{Q}(\sqrt{2+\sqrt{2}}):\mathbb{Q}]=4$.
This is everything I have up to now. I am very new to Galois Theory so guidance and help will be very beneficial to me. Also if you can let me know if my proof of the Galois Extension holds.
Comment: Compare with [this post](https://math.stackexchange.com/questions/575171/galois-group-of-sqrt2-sqrt2-over-mathbbq?rq=1).
Answer: This is mainly correct. You didn't show that the polynomial is irreducible(rigorously). Use Eisenstein to show the polynomial is irreducible. So the Galois group is of order 4. There are two groups of order 4, up to isomorphism. They are $\mathbb{Z}_4$ and $\mathbb{Z}_2 \times \mathbb{Z}_2$. To see which one, see if this Galois group is cyclic.
Answer: Write $\alpha$ and $\beta$ for square roots of $2+\sqrt2$ and $2-\sqrt2$. Then
$\alpha^2\beta^2=2$. Let's choose $\beta$ to make $\alpha\beta=2$ (if you like real
numbers you can assume $\alpha$ and $\beta$ are positive). There is a Galois group element
with $\sigma(\alpha)=\beta$. Then $\sigma(\alpha^2-2)=\beta^2-2$, that
is $\sigma(\sqrt2)=-\sqrt2$. Then $\sigma(\alpha\beta)=\sigma(\alpha)\sigma(\beta)=\beta
\sigma(\beta)$. But also $\sigma(\alpha\beta)=\sigma(\sqrt2)=-\sqrt2=-\alpha\beta$
so that $\sigma(\beta)=-\alpha$. So $\sigma^2(\alpha)=-\alpha$ and
$\sigma^2(\beta)=-\beta$. It follows that $\sigma^2$ is not the identity, but
$\sigma^4$ is. So $\sigma$ has order $4$ in the Galois group, which also has order $4$.
The Galois group must be cyclic of order $4$.


Ordenar por número com DataTables

Question: Estou com um problema com o plugin DataTables na ordem de números. Tenho uma lista de números:
1
2
3
4
...
10
11
12

O Problema acontece por causa dos digitos. Ele ordena tipo
1
10
11
12
2
3
4
...

A ordem correta seria do 1 ao 12, mas por causa que não tem o 0 na frente dos números com 1 dígito ele ordena errado. Tem alguma forma de arrumar isso nesse plugin ?
Script
var table = $('#sample_1');

        /* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */

        /* Set tabletools buttons and button container */

        $.extend(true, $.fn.DataTable.TableTools.classes, {
            "container": "btn-group tabletools-dropdown-on-portlet",
            "buttons": {
                "normal": "btn btn-sm default",
                "disabled": "btn btn-sm default disabled"
            },
            "collection": {
                "container": "DTTT_dropdown dropdown-menu tabletools-dropdown-menu"
            }
        });

        var oTable = table.dataTable({

            // Internationalisation. For more info refer to http://datatables.net/manual/i18n
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "Nenhum registro encontrado",
                "info": "Mostrando _START_ de _END_ de um total de _TOTAL_ registros",
                "infoEmpty": "Nenhum registro encontrado",
                "infoFiltered": "Nenhum registro encontrado (pesquisado em _MAX_ registros)",
                "lengthMenu": "Mostrar _MENU_ registros",
                "search": "Pesquisar:",
                "zeroRecords": "Nenhum registro encontrado com os termos digitados"
            },

            "order": [
                [0, 'desc']
            ],

            "lengthMenu": [
                [5, 15, 20, -1],
                [5, 15, 20, "Todos"] // change per page values here
            ],

            // set the initial value
            "pageLength": 10,

            "dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable

            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "tableTools": {
                "sSwfPath": "../../assets/global/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
                "aButtons": [{
                    "sExtends": "print",
                    "sButtonText": "Imprimir",
                    "sInfo": 'Pressione "CTR+P" para imprimir ou "ESC" para sair',
                    "sMessage": "Gerado por DataTables"
                }]
            }
        });

        var tableWrapper = $('#sample_1_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper

        tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown

Comment: Como está o código do seu datatables? Adicione ele ai na pergunta.
Comment: @DiegoFelipe editado
Answer: Tente adicionar isso ao seu dataTable
aoColumns: [{
    sSortDataType: 'dom-text',
    sType: 'numeric'
},
null]

Mas antes dele coloque isto:
$.fn.dataTableExt.afnSortData['dom-text'] = function (oSettings, iColumn) {
        var aData = [];
        oSettings.oApi._fnGetTrNodes(oSettings).forEach(function (nRow) {
        var oElem = $('td:eq(' + iColumn + ') input', nRow);
        aData.push(oElem.val());
     });
    return aData;
};

Não trabalho muito com dataTables, mas já tive um problema parecido com o seu e isso resolveu.

Ordenar por número com DataTables


Understanding the use of compactness in getting a variation of an admissible curve from a vector field

Question: I came across the following result in the book "Riemannian Manifolds: An Introduction to Curvature" by John Lee.

Theorem: Let $\gamma: \left[ a, b \right] \rightarrow M$ be an admissible curve and $V$ be a vector field along $\gamma$. Then, $V$ is the variation field of some variation of $\gamma$. Moreover, if $V$ is proper then the variation can be chosen to be proper.

The proof of this result uses the fact that $\left[ a, b \right]$ is compact. Particularly, this is used to define the variation of $\gamma$ as $\Gamma \left( s, t \right) = \exp \left( s V(t) \right)$. I am  not sure if I understand this properly. Here are my thoughts on how it is used.
We know that $\exp$ is defined on an open set containing the zero section. That is, there is an open set $\mathscr{E} \subseteq TM$ (the tangent bundle) such that for all $p \in M$, $\left( p, 0 \right) \in \mathscr{E}$. Therefore, for each $p \in M$, there are balls $B^{\left( p \right)} \left( 0, \delta_p \right) \subseteq \mathscr{E} \cap T_pM$. Now, we see that $V(t) \in \frac{2 \| V(t) \|}{\delta_p} B \left( 0, \delta_p \right)$ so that these (scaled) balls form an open cover for $V \left( \left[ a, b \right] \right)$ (am I right here?). Once this is done, we get a finite subcover and hence there is some $\epsilon > 0$ such that for $\left| s \right| < \epsilon$, we have $s V(t) \in \mathscr{E} \cap T_{\gamma \left( t \right)} M$.
Is this reasoning correct? It seems to me that there will be some disjoint unions involved and we may not be able to use the scaled balls to conclude what we want. Any thoughts about this are appreciated!
Answer: The reasoning here is awkward; the following statement does not logically follow from the covering you construct without further spelling how you choose $\epsilon$.

hence there is some $\epsilon > 0$ such that for $|s|< \epsilon$, we have $sV(t) \in \mathscr{C} \cap T_{\gamma(t)}M$.

It's not clear why you decide to scale each of these balls. Your argument could be fixed in a couple of ways with more careful consideration (you are essentially trying to reprove a common lemma), but I think it is most helpful to illustrate what Lee is likely thinking here.

There exists an open set $\mathscr{C} \subseteq TM$ containing the zero-section on which the exponential function $\exp \colon \mathscr{C} \to M$ is defined. Consider the map $g \colon \mathbb{R} \times \mathbb{R} \to TM$ given by $g(s,t) = sV(t)$. Then the preimage $g^{-1}(\mathscr{C})$ is an open set containing the compact set $I = \{0\} \times [a,b]$.
By the tube lemma, there exists $\epsilon > 0$ such that $(-\epsilon, \epsilon) \times [a,b] \subseteq g^{-1}(\mathscr{C})$. Then on this set one may define $\exp \circ \, g$.


Problem in understanding pointer to an Object set to NULL

Question: Can any one explain what does it mean by making an pointer to an object to NULL?
When we assign ptr to an object to NULL, how can we still access the member function?
class A
{
public:
    void print()
    {
        cout<<"Hello";
    }
}

int main()
{
    A * a;
    A* b = NULL;

    a->print();
    b->print();
}

EDIT:
Will the program crash?
http://ideone.com/DudZ6
Answer: The pointer is used for accessing the members of that object. If your function(s) don't need to access any members and are not virtual, they actually don't use the object. The code is still strictly speaking invalid, but it won't crash.
If you replace the contents with printing the "this" pointer, it'll still work as you're not dereferencing it.
struct X {
    void print() {
        cout << "this pointer is " << this << endl;
    }
};

int main() {
    X *x;
    x->print(); // will print whatever was on the stack, ie, random garbage
    X *t = NULL;
    t->print(); // will print a null pointer
}

If you add one member variable and print that, or make the function virtual (so it will have to be looked up through the object itself) it will crash.
struct X {
    virtual void print() {
        cout << "Hello World" << endl;
    }
};

struct X2 {
    int y;
    void print() {
        cout << "y is " << y << endl;
    }
};

int main() {
    X *x = NULL;
    x->print(); // will crash on null pointer dereference
    X2 *x2 = NULL;
    x2->print(); // will crash on null pointer dereference
}

Comment: Actually, it's not.  This answer just describes what happens in one particular implementation.  The behavior is undefined, and other implementations may do something different.
Comment: @dascandy can you please add an example for your second point regarding this pointer. Thank you for you reply. Will mark it accepted as soon as time limit finishes.
Comment: @James, agree, adding one of "usually", "very often", "almost always", "couldn't imagine anything else" should be more precise.
Comment: From the question "how can we still access the member function?" implies empirical observation on some particular platform... this answer does explain how it's possible for the code to execute *if* the compiler basically ignores the value of the pointer until accessing member data or the virtual dispatch pointer. But, "strictly speaking invalid, but it won't crash" is promising too much... even if the non-crashing behaviour has been observed on that particular platform, there's nothing in the Standard guaranteeing it will do the same even if the same executable is reexecuted.
Comment: @Als It was a long time ago, so it could have changed, but the
GreenHills compiler used to crash on it.  And you're not really claiming
that dereferencing a null pointer is not undefined behavior, are you?
It's the very example of undefined behavior used in §1.9.
Comment: @Tony: My bad, I added the quote from the standard to James's, answer for more completeness.
Answer: You can't.  Any attempt to dereference the pointer (any application of
the * or -> operator to it) is undefined behavior, and may do
anything.  Most of the time, of course, you'll only crash if the
code actually needs data from the object (including internal data like a
vptr); otherwise, the code will seem to work.  But that's just one of
the possible undefined behaviors; I've actually used a compiler where
your small program would crash.

As per C++ Standard:
1.9 Program execution
4:
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer). [Note: this International Standard imposes no requirements on the behavior of programs that contain undefined behavior. ]
So strictly, speaking the behavior is undefined, As many have pointed out in comments section just because it works on a particular platform does not make it legal.
So the as per the C++ standard the behavior of the code snippet is Undefined Behavior.
Comment: I've worked in an environment where I had an object at address 0x0. Null pointers definitely wouldn't crash there.
Comment: @James Kanze: +1, I took the liberty to add the Standard quote to your answer for completeness, I hope that is fine, if not feel free to revert it back.
Comment: @dascandy As has already been pointed out, it's undefined behavior.  I've worked in several environments where writing through a null pointer would modify critical data in the OS.  But no C or C++ object can be at the same address; if the system uses the physical address 0 for a C or C++, it must use some other bit pattern for the null pointer.
Answer: You can't,
   A* b = NULL;
 b->print();

this is undefined bahvior and could make your program crash with a segmentation fault (depending on the definition of your print method).
Generally speaking, assigning NULL to a pointer is used to give the pointer a value that means "this pointer is not set, do not use it". Take this code:
void function() {
   int* p;
   int* q = NULL:
   ...
}

when the function is called, p and q are allocated on the stack; due to the way compiler works, p is left unassigned, that means that it gets the value that it is found on the stack at the moment of calling the function; this is a random value that usually has not much to do with your program.
Now, the fact that p has got a value could lead you into thinking that this value is "correct", so you use it; but, it is not (because it is random, due to not initializing the pointer), so you also get a crash or some kind of unexpected behavior.
In the case of q, the fact of assigning NULL to it allows you to tell that it has no usable value. So, you don't reference it:
 if (q != NULL) {
     q->....
 }

The idiom above does not work for p, so you have no way to tell whether it is ok.
In the end: always initialize your variable; in the case of pointers, if you do not have a vlaue to assign, assign NULL, so you know that pointer should not be dereferenced.
Comment: @Als It depends on the implementation.  It's undefined behavior, and I've used compilers where it would crash.  The fact that some compilers let you get away with it doesn't make it legal.


Evaluate $\int_{\mathcal{C}}\frac{\sin z}{z-\pi/2}\,\mathrm{d}z$

Question:
Problem.1) Evaluate $\displaystyle \int_{\mathcal{C}}\frac{\sin z}{z-\pi/2}\,\mathrm{d}z$, given that $\mathcal{C} : |z| = \pi/2$
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Please take moment to give [this posting](https://math.meta.stackexchange.com/q/9959/9340) a read to learn how to ask a good question.
Comment: Also, please use MathJax to format your question. It greatly helps the question visible to various search engines and hence is crucial for maintaining this community as a repository of mathematical knowledge. For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Answer: Use Cauchy's integral formula.
$$\int_{|z|=a} \frac{f(z)}{z-a}dz = 2\pi i f(a) $$
For your question $f(z) = sin(z)$
So answer to your question is $2\pi i sin(\frac{\pi}{2}) = 2\pi i$
Comment: But the contour $C$ contains a discontinuous point $\frac{\pi}{2}$.
Comment: The Cauchy's integral formula https://en.wikipedia.org/wiki/Cauchy%27s_integral_formula requires $a$ to be inside of the contour, not on the contour. Here the integrand is unbounded, so it is not integrable.
Comment: Yes, didn't noticed that. @J.D the answer is probably wrong.


Como faço o button ficar sobreposto à imagem de fundo?

Question: Estou tentando colocar um botão (button) em cima de uma imagem e não estou conseguindo. Já tentei mexer com a propriedade position (relative e absolute) na imagem e no botão, e mesmo assim não consegui.
Será que alguém pode me ajudar?
Segue o código:

#AHEUA {
 background-color: rgb(249,189,251);
 border: 5px solid;
 border-radius: 15px;
 border-color: rgb(215,40,231);
 margin: 20px;
 font: 16px Microsoft New Tai Lue;
 font-weight: 700;
}

#botao {
 background-color: rgb(195, 88, 246);
 border: 1px solid;
 border-radius: 5px;
 border-color: rgb(195, 88, 246);
    padding: 3px 5px;
 top: 10px;
 position: relative;
}

.modal-dialog {
 width: 30%;
    min-width: 270px;
}

.modal-body {
 height: 10%;
 padding: 0px;
}

div#top {
 margin-bottom: 20px;
}

div#bot {
}

div#bot > img {
 position: relative;
}

div#mid {
    width: auto;
    height: auto;
 padding: 0px 5%;
}

    <form method="">

       LOGIN:
       <input type="text" class="form-control borda" id="login" value="" required>

       SENHA:
       <input type="password" class="form-control borda" id="senha" value="" required>

     <button id="botao" type="submit">ENTRAR</button>

    </form>

Answer: Tente usar a propriedade z-index:
#botao {
    background-color: rgb(195, 88, 246);
    border: 1px solid;
    border-radius: 5px;
    border-color: rgb(195, 88, 246);
    padding: 3px 5px;
    top: 10px;
    position: relative;
    z-index: 9999;
}

Comment: Sem o z-index e com o #botao {... position: absolute;...} eu já consigo posicionar o botão em qualquer lugar, mas ele perde a responsividade


Use the convolution formula to find the pdf

Question: Let $X$ and $Y$ be two independent uniform random variables such that $X\sim unif(0,1)$ and $Y\sim unif(0,1)$.
A) Using the convolution formula, find the pdf $f_Z(z)$ of the random variable $Z = X + Y$, and graph it.
B) What is the moment generating function of $Z$?
So far I got to $$f_Z(z) = \int_{-\infty}^{\infty} f_Y(y)f_X(z-y)dy = \int_0^1 f_X(z-y)dy.$$ Where do I go from here?
Comment: I've tried to edit your post using mathjax to improve readability. Please check whether these edits did not unintentionally change the meaning of your post.
Comment: That improved it, thanks @B.Mehta
Comment: [Here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a guide on how to use mathjax. It is pretty simple to learn!
Comment: Did you mean to say that $X$ and $Y$ are **uniformly** distributed?
Comment: Do you know anything more about the distribution of $X$ and $Y$ other than that they are independent random variables that take values on $(0,1)?$ Currently, this does not seem tractable.
Comment: @JohnBarber Yes, thanks for pointing that out
Comment: @Dylan_Carlo_Beck I don't know anything more, I'm completely lost
Answer: By assumption that $X$ and $Y$ are Uniform$(0,1)$ random variables, it follows that $f_X(x) = \mathbf{1}_{(0,1)}(x)$ and $f_Y(y) = \mathbf{1}_{(0,1)}(y)$ so that $$f_Z(z) = \int_{-\infty}^{\infty} f_Y(y) f_X(z-y) \, dy = \int_0^1 f_X(z-y) \, dy = \int_0^1 \mathbf{1}_{(0,1)}(z-y) \, dy.$$ Consider the following two cases.
1.) Given that $0 < z < 1,$ we have that $\mathbf{1}_{(0,1)}(z-y) = 1$ if and only if $0 < y < z,$ hence we have that $f_Z(z) = \int_0^z dy = z$ in this case.
2.) Given that $1 \leq z < 2,$ we have that $\mathbf{1}_{(0,1)}(z-y) = 1$ if and only if $z-1 < y < 1,$ hence we have that $f_Z(z) = \int_{z-1}^1 dy = 2-z$ in this case.
We conclude that $f_Z(z) = z \cdot \mathbf{1}_{(0,1)}(z) + (2-z) \cdot \mathbf{1}_{(1,2)}(z).$ Furthermore, we have that the moment generating function of $Z$ is given by
\begin{align*}
\psi_Z(t) = \mathbb{E} e^{tZ} &= \int_0^1 z e^{tz} \, dz + \int_1^2 (2-z) e^{tz} \, dz \\ \\
&= \frac{e^t(t-1) + 1}{t^2} + \frac{e^t(-t + e^t - 1)}{t^2} \\ \\
&= \frac{e^{2t}}{t^2} - \frac{2e^t}{t^2} + \frac{1}{t^2}.
\end{align*}
Comment: @ Dylan_Carlo_Beck when $0<z<1$, why then $y$ is constraint in $(0,z)$?
Comment: Our $y$ must be between 0 and 1 by assumption but no more than $z.$ For if $y \geq z,$ we have that $z - y \leq 0.$


Convergent or divergent series: $\sum_{n=1}^{\infty} \sqrt{a_n \cdot a_{n+1}}$?

Question: suppose that $\sum_{n=1}^{\infty}a_n$ is a convergent series of positive terms. Prove that $\sum_{n=1}^{\infty} \sqrt{a_n \cdot a_{n+1}}$ is also convergent. Demonstrate that the converse is false.
Answer: Note that $2\sqrt{a_n a_{n+1}}\le a_n+a_{n+1}$. (This is a disguised version of $(x-y)^2\ge 0$.) Then use Comparison.
For the falsity of the converse, let $a_n=1$ if $n$ is odd, and let $a_n$ be a fairly rapidly convergent series when $n$ is even. For example, $\frac{1}{n^4}$ will work.
Answer: By the arithmeticg-geometric inequality $\sqrt{xy}\le \frac{x+y}2$ for $x,y\ge0$. Therefore the second series is dominated as
$$\sum_{n=1}^\infty\sqrt{a_na_{n+1}}\le\sum_{n=1}^\infty\frac{a_n+a_{n+1}}2=\frac12\left(\sum_{n=1}^\infty a_n+\sum_{n=2}^\infty a_{n+1}\right)=-\frac{a_1}2+\sum_{n=1}^\infty a_n.$$
The converse is false as can be seen from $a_{2n}=n^{-4}$, $a_{2n+1}=1$.


Mounted disk disappears after reboot

Question: I've got a Centos 7 dedicated server with a SSD + a nvme ssd with 400gb. I followed a tutorial to mount + format (as xfs filesystem) the nvme disk so that I could setup my NoSQL databases on that drive. However every time I reboot my server the disk disappears and the mounted folder is empty again.
What commands I ran to mount the disk:
fdisk -l

Returned:

Disk /dev/nvme0n1: 400.1 GB, 400088457216 bytes, 781422768 sectors
  Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical):
  512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512
  bytes
Disk /dev/sda: 275.1 GB, 275064201216 bytes, 537234768 sectors Units =
  sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512
  bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disk label type: dos Disk identifier: 0x000b09ac
Device Boot      Start         End      Blocks   Id  System
  /dev/sda1   *        2048     2050047     1024000   83  Linux
  /dev/sda2         2050048   528844799   263397376   83  Linux
  /dev/sda3       528844800   537233407     4194304   82  Linux swap /
  Solaris

mkfs.xfs /dev/nvme0n1 -f (-f was required after the first time)
mkdir /database
mount /dev/nvme0n1 /database

Afterwards it lists the drive when I run df -h, but once I restart it also disappears from that list. What am I doing wrong?
Answer: Try adding this to /etc/fstab:
/dev/nvme0n1 /database xfs defaults 0 0

That should do the trick.
Comment: When you mount a device on the command line, it is only persistent for that session, the nature of it is not stored anywhere.  By placing the entry in /etc/fstab, this file is read at boot time, and ensures your device(s) are mounted on system start-up.  For this reason, be VERY careful when editing this file, don't touch any of the existing content.
Comment: Can you explain why that's needed? I don't understand what the command does
Answer: Steps to mount a disk permanently.
Doing this will mount your disk during boot time.

Attach your disk manually once.
Goto /proc/mounts and /etc/mtab and look for your mount entry.
Copy the entry that you want to be mounted on boot.
Paste it at the end of /etc/fstab. /etc/fstab Contains entries that are mounted during boot.

You can even manually add your entry in /etc/fstab, but copying it from /proc/mounts or /etc/mtab makes sure that you not make any error or mistake in listing your mount point
more helpful links link 1 link 2
Comment: However when using `systemd` everything might be different ("mount units"). Maybe also read about option `-a` in "man 8 mount".

Mounted disk disappears after reboot


std::is_same_v with unspecialized template

Question: I have the following code:
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T, int N>
class A {
public:
    static constexpr int n = N;
};

template<typename T, typename X, int N>
class B {
public:
    static constexpr int x = N;
};

template<typename T>
void test(T) {
    if constexpr (std::is_same_v<T, A>) {
        int a = T::n;
    } else if constexpr (std::is_same_v<T, B>) {
        int a = T::x;
    }
    cout << "a";
};

int main()
{
    A<int, 2> a;
    test(a);
    return 0;
}

Compiling it produces the following error:
error: type/value mismatch at argument 2 in template parameter list for 'template<class _Tp, class _Up> constexpr const bool std::is_same_v<_Tp, _Up>'
   20 |     if constexpr (std::is_same_v<T, A>) {
      |                   ~~~~~^~~~~~~~~~~~~~~
note:   expected a type, got 'A'

The Problem is that I cannot use a correct type here (like A), since I don't know what the template parameters are or how many there are. Basically I want to match any type of class A with any template arguments.
Comment: `A` is no class, but a class template. If you can't use the full template, then how should the compiler determine if they are the same or not?
Comment: I only want to know whether T is a specialization of the template. I don't care for the exact type.
Answer: You need to write your own trait for that:
template<typename>
struct is_specialization_of_A : std::false_type {};

template<typename T, int N>
struct is_specialization_of_A<A<T,N>> : std::true_type {};

template<typename T>
inline constexpr auto is_specialization_of_A_v = is_specialization_of_A<T>::value;

and analogously for B.
You could take the template as template template parameter of the trait as well, so that you only need one trait definition, but that only works as long as the template parameter categories of the templates match. This is not the case here (A has <type, non-type>, while B has <type, type, non-type>).
template<typename, template<typename, auto> class>
struct is_specialization_of : std::false_type {};

template<template<typename, auto> class Tmpl, typename T, auto N>
struct is_specialization_of<Tmpl<T, N>, Tmpl> : std::true_type {};

template<typename T, template<typename, auto> class Tmpl>
inline constexpr auto is_specialization_of_v = is_specialization_of<Tmpl, T>::value;

This can be used as is_specialization_of_v, but not is_specialization_of_v.
Comment: http://open-std.org/JTC1/SC22/WG21/docs/papers/2020/p2098r1.pdf
Answer: If you have many class templates like A and B, you can define a single type trait that would return a "tag":
struct tag_A {};
struct tag_B {};

template<class>
struct get_tag {
    using type = void;
};

template<typename T, int N>
struct get_tag<A<T, N>> {
    using type = tag_A;
};

template<typename T, typename X, int N>
struct get_tag<B<T, X, N>> {
    using type = tag_B;
};

template<typename T>
void test(T) {
    using tag = typename get_tag<T>::type;
    if constexpr (std::is_same_v<tag, tag_A>) {
        // ...
    } else if constexpr (std::is_same_v<tag, tag_B>) {
        // ...
    }
}

Comment: Nice solution for many classes, however I don't expect them to get more than a few, so I chose the other one.


Compilar código c++ com o make

Question: Estou tentando compilar um projeto em c++ utilizando o seguinte código makefile:
OBJS        = main.o src.o
SDIR        = ./src
IDIR        = ./include
BDIR        = ./bin/
ODIR        = $(BDIR)/obj

all: main

%.o: $(SDIR)/%.cpp $(IDIR)/%.h
    g++ -c -o $(ODIR)/$@ $(SDIR)/$<  -I $(IDIR)

main: $(OBJS)
    g++ -o $@ $^ -I $(IDIR)

Quando tento compilar o programa aparece o seguinte erro no terminal:
xxxx@zzz:$ make
g++    -c -o main.o main.cpp
main.cpp:2:17: fatal error: src.h: Arquivo ou diretório não encontrado
 #include "src.h"
                 ^
compilation terminated.
<builtin>: recipe for target 'main.o' failed
make: *** [main.o] Error 1

Mas o arquivo 'src.h' existe e está dentro da basta include. Então gostaria de saber qual o motivo do erro.
Answer: Como os seus .obj ficam em um subdiretório você precisa adicionar esse subdiretório como um prefixo:
OBJS        = $(addprefix $(ODIR)/, main.o src.o)

A regra também precisa usar o subdiretório:
$(ODIR)/%.o: $(SDIR)/%.cpp $(IDIR)/%.h

No final o makefile fica assim:
SDIR        = ./src
IDIR        = ./include
BDIR        = ./bin
ODIR        = $(BDIR)/obj
OBJS        = $(addprefix $(ODIR)/, main.o src.o)

all: main

$(ODIR)/%.o: $(SDIR)/%.cpp $(IDIR)/%.h
    g++ -c -o $@ $<  -I $(IDIR)

main: $(OBJS)
    g++ -o $@ $^ -I $(IDIR)

Answer: O erro esta indicando que o erro esta acontecendo durante a compilação do arquivo main.cpp. Por agora não tem nenhuma evidência que o problema esteja no makefile criado.
O main.cpp está tentando incluir o arquivo src.h na compilação, mas esse não está sendo encontrado. Considerando a declaração:
#include "src.h"

O compilador vai tentar buscar esse arquivo na mesma pasta em que o main.cpp esta salvo.
Não sei em que pasta o main.cpp está salvo, assumo que seja na pasta /src. Acredito também que o src.h esteja salvo na pasta /include.
É necessário alterar o #include com o caminho exato do arquivo src.h.
Algo do tipo:
#include "../include/src.h"

Note que essa é a resposta levando em considereção as coisas que assumi antes.
O importante é que o dentro do teu main.cpp (e qualquer outro arquivo .cpp que inclua algo do /include) o caminho completo esteja definido.

Compilar código c++ com o make


Values of x for which series can converge

Question: I'm given a function $sin(nx)/(n^2)$ and I'm trying to find for which values of x the infinite series for this function would converge. It's easy to see that $sin(nx)$ is always between (-1,1), so then:
$-1/n^{-2} \le sin(nx)/n \le 1/n^{-2}$, so I could use the comparison test. But comparision test states that $a_n$ and $b_n$ must be positive, so would this series converge just for:
$0 \le x \le$ $\pi/(2n)$ ?
Answer: Hint: consider series $|\sin nx|/n^2$; do they converge? Why does it imply convergence of original series?
Comment: @user180708 the series I wrote are positive (notice the absolute value there)
Comment: @user180708: this is indeed the case. If you want to check whether $\sum a_n$ converges, it is *sufficient* to check whether it converges absolutely, i.e. $\sum |a_n|<\infty$
Comment: Yes that series converges by the comparison test as it is always less than $1/n^{2}$ but to use the comparison test, I have to indicate that $a_n$ is positive, right? So wouldn't that only be for [0, $\pi/2n$] ?
Comment: Okay, so then I could simply say that this series converges for all |x| ? This is what I also thought as an alternative answer.


Update ou insert com dados de outra tabela

Question: Tenho esse comando SQL para atualizar a tabelaREQUISICOES com os dados da tabelaREQUISICOES_ATUALIZA.
Uso como chave para atualizar o campo numero_requisicao, mas preciso que caso não encontre correspondencia na tabela REQUISICOES, insira um novo registro vindo da tabela REQUISICOES_ATUALIZA;
Esse funciona para atualizar:
UPDATE requisicoes a
JOIN requisicoes_atualiza b
SET a.projeto = b.projeto
WHERE a.numero_requisicao = b.numero_requisicao

E como seria o SQL para os que não existem?
Comment: Estou usando MYSQL!
Comment: Qual seria o novo registro caso não exista?
Comment: Se você entender sobre, vai conseguir resolver seu problema: [Not IN ou Not EXISTS qual usar?](https://pt.stackoverflow.com/questions/62925/not-in-ou-not-exists-qual-usar)
Comment: Caso não exista um numero de requisição correspondente na tabela Requisicoes, quero inserir os dados da tabela requisicoes_atualiza... Marconi
Answer: Usando o NOT EXISTS. Se o campo numero_requisição for uma unique declarada, você pode usar o INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO requisicoes (numero_requisicao, projeto)
SELECT numero_requisicao, projeto
FROM requisicoes_atualiza ra
ON DUPLICATE KEY UPDATE projeto = ra.projeto

Comment: Onde vc faz o update nesse sql??
Comment: @AndreMaia. Não estou fazendo `update`. Estou fazendo somente a inserção dos itens que ainda não existem, que é o que está na pergunta, correto? Teoricamente o 'update' foi feito com a outra instrução de `update` que já consta na pergunta.
Comment: Quero fazer no mesmo comando, seria possível?
Comment: @AndreMaia, Editei a resposta. Veja se lhe atende
Comment: não atende porque o campo não é chave, e se eu colocar tenho outras chaves na tabela.
Comment: Não precisa ser `primary key`, precisa ser `unique`. Se não for desse jeito, então não dá para fazer `insert...update`, faça as duas instruções separadas.
Answer: Para fazer o insert do que não está na sua tabela de requisições pode usar o SQL abaixo
INSERT INTO requisicoes (numero_requisicao, projeto)
SELECT b.numero_requisicao, b.projeto
FROM requisicoes a
LEFT JOIN requisicoes_atualiza b on a.numero_requisicao = b.numero_requisicao
WHERE a.numero_requisicao is null

Eu uso bastante essa tabela quando tenho esse tipo de duvida:


An inequality involving vectors

Question: Let $n$ be a positive integer number. If $S$ is a finite set of vectors in the plane, let $N(S)$ denote the number of two-element subsets $\{\mathbf{v}, \mathbf{v'}\}$ of $S$ such that
$$4\,(\mathbf{v} \cdot \mathbf{v'}) + (|\mathbf{v}|^2 - 1)(|\mathbf{v'}|^2 - 1) < 0. $$
Determine the maximum of $N(S)$ when $S$ runs through all $n$-element sets of vectors in the plane.
Can someone help? This is from Romanian Olympiad. I have no idea about it.
Answer: First of all, for simplicity let us normalize the set $ S $ of $n$ vectors by setting $v_i=\frac{u_i}{\|u_i\|}$ for all $1\le i\le n $, which gives $\|v_i\|=1$. Therefore, the inequality reduces to be $$ v_i \cdot v_j <0$$
Now, let us observe that it is impossible to have two element subsets of the form $\{v_i, v_i\}$ for all $ i $. Since
\begin{align}
v_i\cdot v_i &=\|v_i\|\|v_i\| \cos (\theta) \,\,\,\,\, \text {when} \theta=0
\\
&=1
\end{align}
which is not less than zero for all $ v_i $.
Recall that, in general if $v $ is nonzero vector then every vector $ v'$ can be written in a unique manner as the sum of a vector $ v'_{||} $ parallel $ v $ and a vector $ v'_{\perp}$ perpendicular to $ v $:
$$ v'=v'_{\parallel}+v'_{\perp}.$$
If $ v_i $ is perpendicular to $ v_j $ then $ v_i\cdot v_j=0$ which does not satisfies the inequality ($0 <0$).
When both vectors are parallel : if the angle is zero  (or the angle belong to $(3\pi/2,2\pi]\cup [0,\pi/2]$) then the dot product would be $> 0$  and the thus the inequality does not holds. If the  vectors are parallel in opposite direction (the angle $\pi $) then the dot product is less than $0$. Moreover, if the angle $\theta\in (\pi/2,3\pi/2) $ then $ v_i \cdot v_j <0$ and the inequality holds. Therefore,  since  the vectors are unit and $\cos\theta <0$ then $$ \text{proj}_{v_j} v_i =(v_i \cdot v_j) v_j= -v_j<0 $$
We recall that $v_i, v_j$ are members of $ S$ that satisfies the inequality. When $S$ run over $n$-element vectors we have to consider all two element subsets of $S$ which are listed below.
The number of all possible two element subset of $ S $ (it may not satisfy the inequality):
\begin{align}
 {S_1} &= \left\{ {{v_1},{v_2}} \right\}\,\,\,\, \text{gives one subset} \,\,\,\left\{ {{v_1},{v_2}} \right\}\\
 {S_2} &= \left\{ {{v_1},{v_2},{v_3}} \right\} \,\,\,\, \text{could give two subsets of two elements}
 \left\{ {\left\{ {{v_1},{v_2}} \right\},\left\{ {{v_1},{v_3}} \right\},\left\{ {{v_2},{v_3}} \right\}} \right\} \\
 {S_3} &= \left\{ {{v_1},{v_2},{v_3},{v_4}} \right\} \,\,\,\, \text{gives 6 subsets of two elements}
\left\{ {\left\{ {{v_1},{v_2}} \right\},\left\{ {{v_1},{v_3}} \right\},\left\{ {{v_1},{v_4}} \right\},\left\{ {{v_2},{v_3}} \right\},\left\{ {{v_2},{v_4}} \right\},\left\{ {{v_3},{v_4}} \right\}} \right\} \\
 {S_4} &= \left\{ {{v_1},{v_2},{v_3},{v_4},{v_5}} \right\}\,\,\,\, \text{gives} \\
 &\left\{ {\left\{ {{v_1},{v_2}} \right\},\left\{ {{v_1},{v_3}} \right\},\left\{ {{v_1},{v_4}} \right\},\left\{ {{v_1},{v_5}} \right\},\left\{ {{v_2},{v_3}} \right\},\left\{ {{v_2},{v_4}} \right\},\left\{ {{v_2},{v_5}} \right\},\left\{ {{v_3},{v_4}} \right\},\left\{ {{v_3},{v_5}} \right\},\left\{ {{v_4},{v_5}} \right\}} \right\} \\
&\vdots \\ \text{and so on}
\end{align}
Therefore, we deduce that the number of all two element subsets of $S$, given in the sequence $$1,2,3,6,10,15,21,28,36,45,55,66,78,91,...$$ and it has the form
$$a_1=1, a_2=2, a_3=3, a_{n}=n-1 + a_{n-1}, n\ge 4$$
Now the answer ($ N(S) $) depends on which two element subset $ S_j $ their vectors satisfy the inequality. The answer it may be one subset, or two, or three, or . . .   and so on.  Here I leave the final answer after more discussion.
Comment: could you please tell me how is this conclusion coming?? I don't see the recursion in any way. Also you are just counting doubletons I think, not those which satisfy this inequality, please clarify. @mwomath
Comment: I will edit my solution!
Comment: How do you conclude this? I mean I don't see you using the given expression anywhere. What told you that $S_2$ gives $3$ such pairs? And that $2$ in your sequence seems to be a typo. And note your recursion evaluates to $\dbinom{n}{2}$. Which counts all doubletons. Not the doubletons satisfying the given inequality. Thanks.
Comment: I update my idea

An inequality involving vectors


How to use Monte Carlo simulation to get the conditional mean

Question: Given the following assumptions:

$Z,Z'\in\mathbb{R}^4$ where $(Z,Z')\sim N(0,\Sigma)$, for some known $\Sigma\in\mathbb{R}^{8\times 8}$.
$Y=f(Z,u,\epsilon)=Z_1\boldsymbol{1}\Big[u<\frac{\exp(Z_3)}{\exp(Z_3)+\exp(Z_4)}\Big]+Z_2\boldsymbol{1}\Big[\frac{\exp(Z_3)}{\exp(Z_3)+\exp(Z_4)}<u\leq 1\Big]+\epsilon$, where $Y\in\mathbb{R}$, $Z=(Z_1,Z_2,Z_3,Z_4)$, $u\sim\text{Uniform}[0,1]$, $\epsilon\sim N(0,\sigma^2)$ for some known $\sigma$, and $\boldsymbol{1}[\cdot]$ is the indicator function. We can think of $Y$ as just some complicated function that depends on $Z$.

Question: Given that we have access to $Z^k$, $Y$, $\Sigma$, and $\sigma$, can we use Monte Carlo to get an approximation for $\mathbb{E}[Z|Z',Y]$? If so, then how can we do it? In other words, given $Z'$ and $Y$, how can we sample $Z$? I've tried thinking about this but wasn't able to come up with a solution.
Some thoughts: If $Y$ is a Gaussian (e.g., $Y=Z_1+Z_2+\epsilon$) then we can get $\mathbb{E}[Z|Z',Y]$ explicitly. But the problem now is that $Y$ is not a Gaussian, requiring me to resort to some form of Monte Carlo simulation. Essentially, I just want to obtain some form of approximation of $\mathbb{E}[Z|Z',Y]$ so any suggestion (even if it has nothing to do with Monte Carlo) is welcomed.
Idea: The best I can think of is this very naive method:

Sample $z$ from the distribution of $Z$, sample $u$ from $\text{Uniform}[0,1]$, and sample $\epsilon$ from $N(0,\sigma^2)$.
Set $\zeta=0.1$ and select $z$ iff $|f(Z,u,\epsilon)-Y|<\zeta$.
Take the average of all the selected $z$'s and return it as an approximate of $\mathbb{E}[Z|Z',Y]$.

Can we do any better?
Answer: Since
$$\mathbb E[Z|Z'=z',Y=y]=\int_{\mathbb R^4} z f(z|z',y)\,\text dz$$
a Monte Carlo approach requires simulating from the conditional distribution of $Z$ given $Z',Y$. Since
$$f(z|z',y)\propto f(z,z',y)=\underbrace{f(z,z'|\Sigma)}_\text{Gaussian} \times f(y|z,\sigma)\tag{1}$$
simulation is feasible (via, e.g., MCMC) if the rhs of (1) is available in closed form. Now,
$$y|z,\sigma\sim p(z)\mathcal N(z_1,\sigma^2)+(1-p(z))\mathcal N(z_2,\sigma^2)$$
with
$$p(z)=\dfrac{e^{z_3}}{e^{z_3}+e^{z_4}}$$
therefore $f(y|z,\sigma)$ is clearly available.
This development leads to
$$f(z|z',y)\propto p(z)f(z|z',\Sigma)\varphi(\{y-z_1\}\sigma^{-1})+(1-p(z)) f(z|z',\Sigma)\varphi(\{y-z_2\}\sigma^{-1})$$


Taxonomy Term for a sports team

Question: I have taxonomy terms for teams ( say team one , team two , etc ) and content types of teams that have team pictures of your team.
Im trying to figure out how to create a view that will show a player that selects team one as their team, and then show them on team one.
I have the view created and its a table, I just can't figure out how to get each player on each team.
Comment: Do you want to display all content associated with a given taxonomny term (team) on the taxonomy term page?
Answer: If I understood right, you want a view to display players of each team. For that, you could:
1) Create a taxonomy vocabulary for each team (which you have already done)
2) Add an image field to the taxonomy term, as you would do to a CCK (admin/structure/taxonomy/[your_vocabulary]/fields
3) Create a CCK for "Player"
4) Add a field to the "Player" CCK of type "Term reference" (choose your Team vocabulary in the settings), so every time you create a new player you can select which team they belong to
5) Add the fields you need into your view, add a filter for the taxonomy term and expose it, so it will come out as a select list
I hope this helps a bit :)

Taxonomy Term for a sports team


How to calculate a combined effect size?

Question: I have got several significant variables in multiple regression analysis. Standardized coefficients of two of the significant variables are:
Education of Son: -.487
Education of Daughter: .428
I also got few more variables. Now I would like to group these variables such as: children education, economic condition etc. and compare the effect size of those in graph.
Can I add the effect size of the variables within the same group. For example, can I say children education effect size is: (-.487+.428)= -.059?
Comment: I read this too fast (deleted my last comment). That's not quite right.
Answer: Easiest way would be to create a new variable that is the education of the children, ignoring their gender, and add that new variable to your model instead of son's and daughter's education. You will need to decide what to do when there are multiple children, e.g. constrain all their effects to be equal.
However, that would be a bad idea in your case. What strikes me is that the effects of sons and daughters are fairly similar except that they have the opposite sign. So ignoring the childrens gender would mean that the effects would more or less cancel each other out, and a very small effect would be left. This would hide the quite substantial effect you found.

Edit:
Alternatively, if you want to combine the effects of multiple variables you could look into sheaf coefficients.
Comment: Your are right. I have also discussed the effects of education level by gender. But now I would like to show in a radar diagram how human, social, financial and built capitals influence the decision. Of course there may counter effects within the variables. However, they technically balance each other to make the total effect of a , say, human capital of a family. Isn't it a net effect of all the respective variables of category?
Comment: radar diagrams look pretty, but I find simple (horizontal) bar or dot graphs much more efficient in conveying such information. Anyhow, I edited my answer to give you an alterantive way of combining the different effects.
Comment: Do you know how to calculate Sheaf Coefficients by SPSS?
Comment: No, I haven't used SPSS in a very long time. In Stata you would use the [sheafcoef](http://maartenbuis.nl/software/sheafcoef.html) package.
Answer: That's not quite right....  The effect of having a single kid would be a weighted average of the two (depending on the probabilities of each event occurring).
Let $y$ be some outcome variable. Let $x_1$ be an indicator variable for category 1 and $x_2$ be an indicator variable for category 2. So the linear regression gives you a conditional expectation function:
$$ E[y  \mid  x_1, x_2] = \beta_0 + \beta_1 x_1 + \beta_2 x_2 $$
Let $p_1 = P(x_1 = 1, x_2 = 0)$ and $p_2 = P(x_1 = 0, x_2 = 1)$. We can alway condition down:
$$ \begin{align*}
E[y  \mid  x_1 + x_2 = 1] &= E[E[y  \mid  x_1, x_2] \mid \ x_1 + x_2 = 1] \quad \quad \text{by law of iterated expectations}\\
&=\beta_0 + \frac{p_1}{p_1 + p_2} \beta_1 + \frac{p_2}{p_1 + p_2} \beta_2
\end{align*}$$
Comment: Ya..you are right


When fitting Tweedie GLM in SAS, should I use the scale option?

Question: In SAS proc genmod with dist=tweedie, when would you use scale=pearson or scale=deviance?
In either case we get a message
The Tweedie dispersion parameter was held fixed.

but without scale option it says
The Tweedie dispersion parameter was estimated by maximum likelihood.

Wouldn't it be better to estimate the dispersion parameter, i.e. not use the scale option? And why are standard errors smaller in that case?
Answer: The SCALE= option is designed for distributions that do not contain a parameter that scales the variance (for example, Poisson).  For those distributions, you can use the SCALE= option to account for overdispersion.
In contrast, the Tweedie distribution contains a scaling/dispersion parameter as part of the three-parameter distribution. So, yes, it would be better to estimate this parameter by MLE.  There is no need to use the SCALE= option for Tweedie.


Function satisfying $f(2x^2-1)=(x^3+x)f(x)$

Question: If  $f : [-1,1]\rightarrow R$ be a continuous function satisfying $f(2x^2-1)=(x^3+x)f(x)$, then find the value of  $\lim\limits_{x \to 0}\dfrac{f(\cos x)}{\sin x}$
My approach is as follow, as the domain is $[-1,1]$, we check the value at $x=-1$, then $f(1)=-2f(-1)$, at $x=1$, then $f(1)=2f(1)$, then $f(1)=0$, hence $f(-1)=0$, putting $x=0$ we get $f(0)=0$.
Now  on differentiating we get $4xf'(2x^2-1)=(3x^2+1)f(x)+(x^3+x)f'(x)$ after this I am not able to solve as it is getting complicated
Comment: How do you know $f(x)$ is differentiable?
Comment: Define $g(t) = f(\cos(t))$ and take $x = \cos(t)$ in the functional equation and use trig identities to simplify.
Answer: Assuming $f$ is differentiable and plugging in $x=1$ in the differential equation yields $$4f'(1) =2f'(1) \implies f'(1)=0$$ Now, note the limit is of form $\frac 00$, so applying L'Hôpital's rule we get$$\lim_{x\to 0} \frac{f(\cos x)}{\sin x} =\lim_{x\to 0} \frac{f'(\cos x)\cdot (-\sin x) }{\cos x} = \frac{(\to 0) \cdot (\to 0)}{1} =0$$
Comment: How do you know $f(x)$ is differentiable?
Comment: @QC_QAOA Good point.


php pdo mssql driver on centos

Question: How do I install PHP PDO Mssql Driver on Centos?
Answer: yum install php-pdo
there is also a php 5.3 version, if you have that version of php installed php53-pdo, but don't install that otherwise as the upgrade breaks loads of stuff.
there is a php-mssql module as well which might be handy.
Answer: php has a sybase driver that can connect mssql server, also you can use odbc to connect.
modules are php5-sybase and php5-odbc
in ubuntu I can install them using
 sudo apt-get install php5-odbc php5-sybase

in red-hat it should alike, using yum.

php pdo mssql driver on centos


Freshdesk email command

Question: I have created a freshdesk account and support also. If I send an email to create a new ticket it won't create a ticket with this code:
<code>Mt delemeter is
@Simonsays
</code>
My email body is
<code>@Simonsays "status":"pending", "priority":"medium", "agent":"Test Agent" @Simonsays
</code>
I am receiving a ticket but It is not change  the values assigned there in Ticket Properties. If I do have any errors in Email Command, please sort it out
Comment: Can you please describe more about your environment. I know freshdesk, but I don't understand what you are asking.
Answer: Commands on tickets where you are the requester do not work.

Freshdesk email command