How do I install xen hypervisor + linux onto a usb memory stick

Question: I'm wanting to create a bootable Linux + Xen Hypervisor on a USB stick.
I have it working how I want on a hard drive but for cloud deployment I'd like it to boot xen to a ram disk and mount the internal hard drive to /xen
The idea being that I can deploy new xen servers by just plugging in a USB stick.
How would I go about getting linux and xen onto a USB stick?  I'm looking for some good tutorials but haven't found that many that suit. Apart from ones that convert ISO boot CD images to USB.
Note: I am not interested in answers that show me how to put xenserver on a usb stick.  Xenserver is not linux + xen hypervisor.
Comment: What have you tried so far?  Most usb sticks just show up as a regular /dev/sdx, so you should be able to pick that as a drive and install onto it.  If the installer does not want to work with a non-hdd, you can always make a ext{2,3,4} partition on the USB stick and make it boot with EXTLINUX, point it at the hypervisor, and let it boot.
Comment: I haven't tried it yet, just been researching on common methods.  I think I will attempt to do it as you state.
Answer: Perhaps the Apline Linux Live XEN iso is what you are looking for
Alpine Linux Downloads
Comment: just tried, the boot fails somewhere after the first steps with xen.gz things..
Answer: As i can see this thread is still alive, so, maybe, my answer will help someone. I recently stucked with similar problem and it was hard to me to create a bootable USB. Boot hanged or USB wasn't properly identified. I haven't found the reason of problem, but i suppose it's related with UEFI, because OS images i used started properly from VMs... I have managed to create a bootable USB with latest Alpine Xen iso image using Easy 2 Boot tool. E2B i installed on flash using Windows7 VM. On XP VM i got some errors while installing it. On Ubuntu 12.04 i tryied a lot of startup disk creator tools and none of them worked for 100% sure.
Comment: In the end I managed to create a netbootable version of xen.  Then the images were stored on ceph.


Problema em implementar a edição em Angular

Question: Observem a imagem a baixo;

Ao clicar em editar além de ser direcionado para a página de edição era para carregar o formulário, porém o formulário não está sendo carregado, e veja como está.

Era para ficar assim;

Não sei o que está acontecendo de errado, preciso de ajuda.
Esse é o método na classe de serviços.
<code> editEvento(token, id, evento){
      let params = JSON.stringify(evento);
      let headers = new Headers({
        'Content-Type':'application/json',
        'Authorization': token
      });

      return this._http.put(this.url+'evento/'+id, params, {headers: headers})
               .map(res => res.json());
    }
</code>
Esse é minha classe do componente.
<code>import { desaparecer } from './../../animation';
import { environment } from './../../../environments/environment';

import { Evento } from './../../models/evento';
import { UploadService } from './../../core/upload.service';
import { EventoService } from './../../core/evento.service';
import { UserService } from './../../core/user.service';
import { Component, DoCheck, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  public title: string;
  public evento: Evento;
  public identity;
  public token;
  public url: string;
  public status;
  public is_edit;

  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _userService: UserService,
    private _eventoService: EventoService,
    private _uploadService: UploadService
  ) {
      this.is_edit = true;
      this.title = 'Atualizar Evento';
      this.evento = new Evento('','','',2018,'', '');
      this.identity = this._userService.getIdentity();
      this.token = this._userService.getToken();
      this.url = environment.url;
  }

  ngOnInit() {
    this.getEvento();
  }

  getEvento() {
    this._route.params.forEach((params: Params) => {
      let id = params['id'];

      this._eventoService.getEvento(id).subscribe(
        response => {
          if (!response.evento) {
            this._router.navigate(['/home']);
          } else {
            this.evento = response.evento;
          }
        },
        error => {
          console.log(<any>error);
          this._router.navigate(['/home']);
        }
      );

    });
  }

  onSubmit(){
    var id = this.evento._id;
    this._eventoService.editEvento(this.token, id, this.evento).subscribe(
        response => {
          if (!response.evento) {
            this.status = 'error';
          } else {
            this.status = 'success';
            this.evento = response.evento;

            // Subir imagen do evento
            if (!this.filesToUpload) {
            this._router.navigate(['/evento', this.evento._id ]);
            } else {
            // Subida de la imagen
            this._uploadService.makeFileRequest(this.url+'upload-image-evento/'+ this.evento._id, [], this.filesToUpload, this.token, 'image')
                .then((result: any) => {
                    this.evento.image = result.image;
                    this._router.navigate(['/evento', this.evento._id ]);
                  });
              }
            }
      },
      error => {
        var errorMessage = <any>error;

        if(errorMessage != null){
          this.status = 'error';
        }
      }
      );
    }

  public filesToUpload: Array<File>;
    fileChangeEvent(fileInput: any){
      this.filesToUpload = <Array<File>>fileInput.target.files;
    }

}
</code>
E clique aqui para ter acesso ao meu repositório.
Answer: De acordo com a imagem fornecida, parece que seu html (edit.component.html) está com o html padrão que o angular criou.
Comment: Exatamente, o autor da pergunta esqueceu de escrever o código HTML da página.
Comment: @Arnaldo R. Portela isso já sabia, não tinha como colocar todo o código do projeto.
eu não esqueci de colocar a pagina padrão do edit é que ao clicar no botão editar e para ele carregar a pagina de salvar como tivesse editando. O projeto do curso funciona perfeitamente, mas o meu não funciona, deve ser uma bolbagem.
Comment: eu coloquei o link do repositório na minha postagem.
Comment: Então, no repositório, seu html está com o conteúdo padrão, não tem o html da página em questão


hiding guiText behind game object

Question: I have this HUD on the top of my app which shows the score (top left corner), an about button (top right corner) and a timeline in the middle. The timeline "scrolls" as time passes.
I want to draw some numbers over the timeline to show the years that it is representing. Im currently using GuiText to do it. Unfortunately I have noticed that, while the timeline bar goes behind the top left object in the scene. The GUIText remains over this object.
Is GUIText always drawn on top of everything else or is there a way to hide it behind a game object?
Update:
After some testing/research I have come to the conclusion that there is probably only one way to get GUIText to not appear in front of certain objects.
If one wishes for their Text (or for that matter any type of GUI stuff) to go behind certain objects, one must use at least one extra camera.
The second camera should be set as "depth only" and have a depth value lower than the main camera. This way, everything that is drawn by the main camera will be on top everything drawn by the second camera.
Use the Culling mask and set the objects you wish to appear/hide in different layers.
Comment: You won't be able to render guiText under other gameObjects, not without using another camera, at least. If you want the GUI to be 3d elements of your scene, you'll have to look at alternative GUI solutions like NGUI.
Comment: I think the problem is the order in which you draw your items. The text on the timeline is drawn over a button? This is because the text is rendered after the button. Try putting that code before the button.
Comment: I think the issue has to do with the text being GUI and the button/icon a gameobject (cube). I believe that GUI stuff is always drawn last. Is this correct?
Comment: any other way I can draw text other than GUIText?
Answer: You should be able to do this using shaders.
Simply pass the value of the object's depth from the vertex shader on to the pixel shader of the gui. Use this value determining the alpha value of the pixel.
There are numerous ways to do this when using your own game engine and can access the code but Unity is going to restrict you a bit here. I'm not sure if Unity allows you to apply pixel shaders to the GUI. If it doesn't, consider using billboards for this particular part of the gui and doing similar.
Comment: That's a very elegant solution, didn't think of it. Could you describe it in a little more detail for those of us who are not very familiar with shaders?
Answer: After some testing/research I have come to the conclusion that there is probably only one way to get GUIText to not appear in front of certain objects.
If one wishes for their Text (or for that matter any type of GUI stuff) to go behind certain objects, one must use at least one extra camera.
The second camera should be set as "depth only" and have a depth value lower than the main camera. This way, everything that is drawn by the main camera will be on top everything drawn by the second camera.
Use the Culling mask and set the objects you wish to appear/hide in different layers.
Comment: Just out of curiosity, why not use 3D Text?  If you want to mimic guitext, make it a child of your camera object so that the text always stays in view.  I would think this would be computationally cheaper than creating a second camera.  Plus there is already a [community shader](http://wiki.unity3d.com/index.php?title=3DText) for adding depth to text.
Comment: you should edit/update your original post instead of writing your answer here.
Comment: I just forgot about 3D Text :) and I even knew that shader -_- Good solution also!

hiding guiText behind game object


SQL SERVER - Select next row value upto 5 characters and then replace first character with new one

Question: I have a situation where i want to read next value of the same column and concat it upto five characters and store it in different column but i am not able to do so
Please see below for better visualization.
Here's the input
------------------------------
|      ID      |   word      |
------------------------------
|       1      |      M      |
|       2      |      V      |
|       3      |      V      |
|       4      |      M      |
|       5      |      V      |
|       6      |      M      |
|       7      |      V      |
|       8      |      M      |
|       9      |      V      |
|       10     |      V      |
------------------------------

Desired output:
--------------------------------------------
|      ID      |   word      |  expected   |
--------------------------------------------
|       1      |      M      |      M      |
|       2      |      V      |      MV     |
|       3      |      V      |      MVV    |
|       4      |      M      |      MVVM   |
|       5      |      V      |      MVVMV  |
|       6      |      M      |      VVMVM  |
|       7      |      V      |      VMVMV  |
|       8      |      M      |      MVMVM  |
|       9      |      V      |      VMVMV  |
|       10     |      V      |      MVMVV  |
--------------------------------------------

In this expected column after appending the 5th character when it goes to 6th row and tries to append, it will first remove first character 'M' from 'MVVMV' (5th row) and then append 'M' from 6th row at the end of 'MVVMV' which will be 'VVMVM'
i hope you get this logic as i have tried many ways to achieve this but no luck
Thank you
Answer: You can use lag() and concat():
select t.*,
       concat(lag(word, 4) over (order by id),
              lag(word, 3) over (order by id),
              lag(word, 2) over (order by id),
              lag(word, 1) over (order by id),
              word
             ) as concat_5
from t;

Unfortunately, SQL Server does not (yet) support STRING_AGG() as a window function.  If it did, you could use:
select t.*,
       string_agg(word) within group (order by id) over
            (order by id rows between 4 preceding and current row) as concat_5
from t;

Comment: i tried this but it gets the value in next row it should get me on the same row http://sqlfiddle.com/#!18/3743fb/1
Comment: @abhishek . . . I fixed it.


Is there a real point to using "Run as" local admin accounts instead of logging in as a local administrator?

Question: Let's start by setting the scene -- I'm a junior systems administrator tasked with conducting a transition of the company towards a "Least-Privilege" model. This includes removing admin rights from our users, who mostly work with Windows 10.
Now at this point in time, users are (for the most part) using accounts with local admin rights. This is obviously pretty bad, and we're working on changing that. The idea that was put forward by my n+1, following a security audit they've had last year, is to have two types of users:

The first type will lose admin privileges and, in the event of needing them, will receive a temporary password to an account with admin rights on their computer (which will expire after a bit of time, using LAPS)
The second type (and most relevant to my issue) is made up of developers -- some on web technologies, but others on some very low level languages, and needing to interact with the registries on a semi-regular basis among other things.
These guys will have a regular account, with no privileges, and an admin account (or "Run as" account) they will use when they need to run stuff as a local admin. This means entering a login and password everytime the UAC comes up to confirm admin privilege usage. This "Run as" account will not be able to open a regular session, for obvious reasons.

The problem comes with these old-school developers. I'm afraid this will be turned into an office politics issue, since the loss of admin rights might come with a bit of productivity loss (especially for those who use privileges more often) and, more importantly, some frustration.
I can understand where they're coming from. Having worked for the same company as a dev, I get that being local admin is comfortable. However, I'm also familiar with security issues, and know that being an admin on a workstation is a big no-no.
Recently, I've had to present to this second type of user our plans for the future. Needless to say the lead dev of the "old-school" group was not happy about it, and he asked a pretty good question (though maybe coming from a close-minded point of view on the situation) to which I haven't managed to come up with a satisfying answer.
If the purpose of not being a local admin is to avoid the spread of malware or the capabilities of an intruder to exploit vulnerabilities, is there a real difference between a user running privilege-needing programs as this "Run as" admin account and just executing it outright with an admin account in the cas of an infected file?
The lead dev argued that such a policy would be nothing more than a waste of their times, since it would result in the exact same security vulnerabilities as just being a local admin in the first place.
Is this accurate? I'm aware of the claims that "92% of critical Microsoft vulnerabilities
disclosed in 2013 can be mitigated by removing admin rights"(SANS, 2016, citing an Avecto study) and other such assertions, and I really feel like being local admin is indeed not a good idea, but is our solution really better?
We're planning on doing a test drive of the new solution in the near future, to assess the potential loss of productivity and determine whether or not we need to find another solution, and I'm afraid the lead dev and others who are annoyed by the idea will purposefully overstate its setbacks.
Comment: IMO this question is better suited for [security.se]
Answer:
The problem comes with these old-school developers. I'm afraid this
will be turned into an office politics issue, since the loss of admin
rights might come with a bit of productivity loss (especially for
those who use privileges more often) and, more importantly, some
frustration.

This isn't your battle to fight, so don't fight it. If people aren't happy about the change then tell them to speak to management.
Is the proposed change more secure? Yes. Does risk still exist in the new model? Yes. Is there less risk with the new model? Yes.
As an aside, I'd hate to be the person who quashed this and then find the company data and intellectual property ransomwared. And heaven forbid it makes it's way to client systems through your software. Ask the developers if they want that responsibility and accountability.
Comment: Those policies actually are truly a waste of time given the number of time you need admin permissions in a typical day doing software development (barring web perhaps). And they completely miss the point: what needs to be protected on a developer system is not the system, it's the code… which is perfectly writable as regular user. — in other words, it does nothing to protect client systems, but hey, at least our developer's workstation is slightly better protected, that was worth the decrease in productivity.
Answer: Depends on your risk spectrum.
As a prevention of a targeted attack, the measure is pretty much pointless.
As a prevention of an insider attack, the measure is pointless as well.
As a prevention of devs installing pirated software and failing to uninstall it before an unexpected audit - sorry.
As a prevention of an off-the-mill malware that infects the sales and accounting departments' computers - well, it works, to an extent - and those should not need admin access anyway.
As a prevention of a gross sysadmin negligentce - well, somewhat, because those develop the habit of writting the password quickly and without really reading what it is asked for.
Other than that, getting dev machines where the most IP resides or the backup infrastructure where everything resides to join the AD is bad in the first place.
It creates a single point of failure. Messing with the policies just makes the devs angry and inventive at bypassing the security theater.
p.s.
I am yet to see an AD deployment that is not pwned at domain admin level in 5 years, no matter if the legitimate admins know it or not.


Error 69 82 when doing APDU verify instruction with biometric

Question: I want to implemente match on card verification on my device.
The first two steps (parameter with Threshold and Rotation ) proceed successfully with a 9000 response, but during the verification step, I receive a failure with the 6982 error code (SW_SECURITY_STATUS_NOT_SATISFIED) by using the exact same fingerprint.
I'm seeking guidance on the security requirements and necessary steps to resolve this issue during biometric verification.
I'm Using iso standard 7816;
First step :
Send=>8024008724B0007F6075800100830100A1178101088201058702010188020005B10786020EC987011E
Get<=9000

Seconde step :
Send=>8024008758B0007F2E538151500F9C26109B15199C341C9A15239D2D2B9C4F2BBB5C2B5B1F31BB5B379A193D9D46419B34459C09479F286EBB2F759C0778411E7D5F597DB80980A32783BB0B90A62D935A279A9C24A79E1BADA73AB995
Get<=9000

verification step :
Send=>0020008758B0007F2E538151500F9C26109B15199C341C9A15239D2D2B9C4F2BBB5C2B5B1F31BB5B379A193D9D46419B34459C09479F286EBB2F759C0778411E7D5F597DB80980A32783BB0B90A62D935A279A9C24A79E1BADA73AB995
Get<=6982

I am having a 6982 error that means : 6982 SW_SECURITY_STATUS_NOT_SATISFIED Access condition for verification not met  OR Attempt to present PIN without SM.
And I dont know how to fix that.
Answer: I finally found the solution to the problem.
Error 6982 means SW_SECURITY_STATUS_NOT_SATISFIED: Access condition for verification not met. Attempt to present PIN without SM.
I had to change my command and also finish pre-personalization of the chip. Here is the result I obtained: Finger enrollment:
8024008725B0017F6081B9800100830100A1178101088201098702010188020005B10786020EC987011E

Send=>8024008725B0017F6081B9800100830100A1178101088201098702010188020005B10786020EC987011E
Get<=9000

802400879CB0017F2E8196818193160D5F2A0F5E55155D4417BE25219F59229C192D7F442F9D1636A233369E0844A50C5BA56C64B90F6BA6306B62196D43396DBD1A7267447A5D217E683C81616E8BB70F8EAC3E8F6137966A0F9A4C589D562A9E6F389E7830A0493CA3B735A5721BABB12BAF9061B05611B2AE0ABB4E72C45616C87464CF5970D69B7DD6571BDD5579DE9B7DE55E5FED9E12EF9750F39C1CF698
Send=>802400879CB0017F2E8196818193160D5F2A0F5E55155D4417BE25219F59229C192D7F442F9D1636A233369E0844A50C5BA56C64B90F6BA6306B62196D43396DBD1A7267447A5D217E683C81616E8BB70F8EAC3E8F6137966A0F9A4C589D562A9E6F389E7830A0493CA3B735A5721BABB12BAF9061B05611B2AE0ABB4E72C45616C87464CF5970D69B7DD6571BDD5579DE9B7DE55E5FED9E12EF9750F39C1CF698
Get<=9000

Verification with the same finger:
00200F879A7F2E8196818193160D5F2A0F5E55155D4417BE25219F59229C192D7F442F9D1636A233369E0844A50C5BA56C64B90F6BA6306B62196D43396DBD1A7267447A5D217E683C81616E8BB70F8EAC3E8F6137966A0F9A4C589D562A9E6F389E7830A0493CA3B735A5721BABB12BAF9061B05611B2AE0ABB4E72C45616C87464CF5970D69B7DD6571BDD5579DE9B7DE55E5FED9E12EF9750F39C1CF698
Send=>00200F879A7F2E8196818193160D5F2A0F5E55155D4417BE25219F59229C192D7F442F9D1636A233369E0844A50C5BA56C64B90F6BA6306B62196D43396DBD1A7267447A5D217E683C81616E8BB70F8EAC3E8F6137966A0F9A4C589D562A9E6F389E7830A0493CA3B735A5721BABB12BAF9061B05611B2AE0ABB4E72C45616C87464CF5970D69B7DD6571BDD5579DE9B7DE55E5FED9E12EF9750F39C1CF698
Get<=9000

Verification with another finger:
00200F87627F2E5F815D190987240FA8281E460F1F4A2E2169352F6A2433493A35863B3BAB1D3DAD40416C4844AC5D4CA66D4FB908514D19518D2D538D26546E615B75695CB76261754162705263B367677614704F2B7C7142827263A4B773B3585EBA5755C358
Get<=63CE

63CE means that the number of remaining attempts is (E) 14


2 arrays no foreach

Question: existe como colocar 2 arrays em um mesmo foreach?
Deixa eu explicar o que eu preciso, estou usando a class WideImage para redimensionar as imagens, preciso pegar a extensão da imagem para salva-la posteriormente.
Meu problema esta ai, como eu posso fazer para pegar a extensao de cada imagem do array?
Eu até consigo fazer com um foreach tipo esse:
foreach ($image as $imagem) {
    foreach ($imagemExtensao as $extensao) {
        $extensaoDaImagem = pathinfo($extensao, PATHINFO_EXTENSION);
        $imagemFinal = $imagem->resize(400, 300);
        $geraNome = md5(time().rand());
        $imagemFinal->saveToFile('imagens/usuarios/' . $geraNome .'.'.$extensaoDaImagem);
        $nomeCompleto = $geraNome.'.'.$extensaoDaImagem;
    }
}

Só que ai ele duplica as imagens, os nomes, tudo. Por isso eu preciso fazer uma vez só, ou se tiverem outra ideia.
Comment: Forneça um exemplo da estrutura das `array`s retornada pela classe, para assim entendermos se é bidimensional ou duas isoladas, se é do tipo `assoc` ou `index`. Detalhes como este farão você obter respostas mais rápidas :)
Comment: Uso a função do WideImage para trazer o array de imagens segue função, $image = WideImage::loadFromUpload('imagem', 'imagem.php'); Ai eu preciso usar outra variável para trazer o array com os nomes, para posteriormente pegar a extensão das imagens, $imagemExtensao = $_FILES['imagem']['name']; Por isso preciso do foreach, para conseguir varrer os 2 arrays no mesmo instante.
Comment: Não use os comentários, edite a questão, formule a pergunta e forneça o formato das `arrays` (você pode capturar tal formato usando `print_r`).
Comment: Então você já tem uma array com as extensões, é isso? E ela tem o mesmo tamanho da array de imagens? Os índices das duas arrays são correspondentes? Por exemplo, a imagem em `$image[5]` é a dona da extensão em `$imagemExtensao[5]`?
Comment: Sim, isso mesmo.
Answer: Se são duas arrays "paralelas", numericamente indexadas, e com indexação correspondente, basta fazer um loop em uma delas, e usar o mesmo índice na outra. Por exemplo:
foreach ($image as $indice => $imagem) {
    $extensao = $imagemExtensao[$indice];
    $extensaoDaImagem = pathinfo($extensao, PATHINFO_EXTENSION);
    $imagemFinal = $imagem->resize(400, 300);
    $geraNome = md5(time().rand());
    $imagemFinal->saveToFile('imagens/usuarios/' . $geraNome .'.'.$extensaoDaImagem);
    $nomeCompleto = $geraNome.'.'.$extensaoDaImagem;
}

Comment: Tu é o cara, funcionou certinho, Muitoooo Obrigado!!!
Comment: Mais uma ajuda, como eu posso enviar esses nomes das imagens pro banco? hehe estou começando agora, desculpa a ignorância
Comment: @user13840 Aí já é uma pergunta totalmente nova, você pode postar separado. Na nova pergunta, você precisa situar as pessoas sobre o que você já sabe/tentou, qual é o seu banco e como é sua tabela, se você já sabe conectar ao banco, etc.

2 arrays no foreach


how to add a form to a build array

Question: I am creating a custom module that has the following as the build:
$build = array(

          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );

    return $build;

I have a Form that I get with the following line :
$form=\Drupal::formBuilder()->getForm(pup_viewfiles\pager),

The question is how can I incorporate this form into the build ?
Answer: getForm() returns a render array, and a render array can have other render arrays as children, so:
$build = [
    'form' => $form,
    ...
];

how to add a form to a build array


Is it possible to open for example facebook.com page in browsersync?

Question: I need to open one page on multiple devices, but I'm not developer (I don't have project of the site) and I want use existing page like facebook.com. Is it possible with browsersync?
Answer: You are able to open any webadress on the web.
You have to have installed 2 main things though.

You have to have installed Node. Here is a good working guide. How
to install npm and node
You have to install browser-sync on your
machine like so:
npm install -g browser-sync

After you have everything installed you can run this command in terminal like so:
browser-sync start -p "https://facebook.com"

After running you should get a result like this one:
[BS] Proxying: https://facebook.com
[BS] Access URLs:
--------------------------------------
Local: https://localhost:3000
External: https://192.168.1.143:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://192.168.1.143:3001


Change ubercart default path

Question: My clients really really insist that the path of the cart pages will be store/* instead of cart/*
Also, an alias is not good enough. They want a totally unrelated page to appear in the path: cart
Crazy? yes. Challenging? you bet.
Comment: This will be a fair amount of work. You can change the paths with a simple menu alter, but that won't change any of the internal links Ubercart uses to get to those pages. For example, `grep -nr cart/checkout ubercart` will show you a bunch of forms and page callbacks that need to be overridden for the checkout page, just to make sure the checkout process doesn't break completely. Same thing goes for all the other cart/* pages. Not to mention any ubercart contrib modules you have installed that might rely on those paths
Answer: Rewrite all needed paths by hook_menu_alter. It is invoked  by menu_router_build().
Comment: It's really not that simple...
Comment: :) So I do not know another way. If you look here http://drupalcontrib.org/api/drupal/contributions!ubercart!uc_cart!uc_cart.module/function/uc_cart_menu/7 It is fixed by code. So you can alter it by another code using hook_men_alter. I do not know If a such module exists.

Change ubercart default path


what's the best solution for privilege separation in Apache for content manager in PHP

Question: I have several VirtualHost, and several web in the same VirtualHost:

web1.example.org
web2.example.org
www.example.org/web3
www.example.org/web4

I tried use mod_proxy, mod_proxy_fcgi + PHP-FPM:
Alias /myfoo /web/other/myfoo
  ProxyPassMatch ^/myfoo/(..php(/.)?)$ fcgi://127.0.0.1:9001/web/other/myfoo/$1
  Alias /2myfoo /web/other/2myfoo
  ProxyPassMatch ^/2myfoo/(..php(/.)?)$ fcgi://127.0.0.1:9002/web/other/2myfoo/$1
but this not read .htaccess files of my users.
If I use suEXEC, I don't set in:

www.example.org/web3
www.example.org/web4
...

because all they are in the same virtualhost.
The only solution is use container or diferents instances of httpd? or i can fix it (mod_proxy + php-fpm).
Thanks you.
Answer: I am not sure what good alias doing for you there. And you don't need to specify $1 here,
ProxyPassMatch   ^/myfoo/(.*\.php(/.*))?$   fcgi://127.0.0.1:9001/web/other/myfoo/
ProxyPassMatch ^/2myfoo/(.*\.php(/.*))?$    fcgi://127.0.0.1:9002/web/other/2myfoo/


Converse of Equal Area Theorem for Medians

Question: I'm stuck on this bonus problem on a take home test in my math class:
Let G be a point in the interior of the triangle ABC, and let D, E, and F be points on
sides BC, AC, AB, respectively, such that AD, BE, and CF all intersect at G. Given that triangles AFG, AGE, and BDG all have the same area, show that D,E and F are the midpoints of the sides BC,AC, and AB, respectively.
Any ideas?
Answer: Let $[AFG] = [AGE] = [BDG] = x$, $[GDC] = y$, $[GEC] = z$, and $[BFG] = w$.
Then, because $\frac{BD}{DC} = \frac{x}{y} = \frac{2x+w}{x+y+z}$,  and $\frac{AE}{EC} = \frac{x}{z} =\frac{2x+w}{x+y+z}$,$\frac{x}{y} = \frac{x}{z}$, so $y = z$.
Now, $\frac{AF}{FB} = \frac{x}{w} = \frac{2x+y}{w+x+y}$. Therefore, $x^2 + xy = wx+wy \implies x(x+y) = w(x+y) \implies x = w$.
Also, $\frac{BD}{DC} = \frac{x}{y} = \frac{3x}{x+2y}$, we can find that $x^2 + 2xy = 3xy \implies x^2 = xy \implies x = y$.
To finish, $\frac{AE}{EC} = \frac{CD}{DB} = \frac{BF}{FA} = \frac{x}{x} = 1$, so we are done.


How to change rest export views field alias programmatically

Question: When using REST export view, and Fields format, under Settings I can change alias for each field.
How can I do the same with code?
Answer: You can create a ViewsField Plugin with the custom module and name whatever you want.


Finite order In a non-abelian group

Question: Can someone make an example to show that the product of two elements of
finite order In a non-abelian group is not necessarily of finite order.
My goal of asking this question, is introducing a nice counterexample from matrix space and I know there are so many example about this question. thanks for referencing of these examples.
Comment: http://math.stackexchange.com/questions/41303/examples-and-further-results-about-the-order-of-the-product-of-two-elements-in-a, http://math.stackexchange.com/questions/59791/do-there-exist-groups-whose-elements-of-finite-order-do-not-form-a-subgroup, http://math.stackexchange.com/questions/1497991/give-an-example-of-a-nonabelian-group-in-which-a-product-of-elements-of-finite-o, ...and so many links can be found duplicate to this.
Comment: What is an "Annabelle group"? Do you mean _abelian_?
Comment: I suspect this is yet another installment of "Damn you, Autocorrect!"
Answer: Take the group of all rigid motions of the plane, and let $p$ and $q$ be rotations by $180^\circ$ about two different points.
Then $pq$ is a nontrivial translation, which cannot have finite order.
Answer: In the group of invertible linear maps from reals to reals under composition, let $f(x)=-x$ and $g(x)=1-x,$ each of order $2.$ Then $g(f(x))=1+x$ which has infinite order (it is translation by $1$).
Since this group can be made into a matrix group by taking $f(x)=mx+b$ to be the matrix with first row $[m,b]$ and second row $[0,1]$ it gives a matrix example of your requirement. (Then $m \neq 0$ is the nonzero determinant condition for the matrix group, and one needs $m$ nonzero for considering $mx+b$ as an invertible linear map.)
Answer: You can consider $\mathbb{Z}_2*\mathbb{Z}_2$ as $\langle a,b| a^2=b^2=1\rangle$. Clearly $a,b$ have finite order, but $ab$ hasn't finite order.
Answer: It is a counterexample from an article called (A General Q-Matrix) by (JOHN IVIE):
http://www.fq.math.ca/Scanned/10-3/ivie-a.pdf
Define a matrix $Q_r$ by:
$$
Q_r=\left({\begin{array}{ccccccc}
1&1&0&0&\cdots&0&0\\
1&0&1&0&\ddots&\ddots&\vdots\\
\vdots&\vdots&\ddots&1&\ddots&\ddots&\vdots\\
\vdots&\vdots&\ddots&\ddots&\ddots&\ddots&\vdots\\
\vdots&\vdots&\ddots&\ddots&\ddots&1&0\\
1&\vdots&\ddots&\ddots&\ddots&\ddots&1\\
1&0&\cdots&\cdots&\cdots&\cdots&0\end{array}}\right)_{(r)\times (r)}\, .
$$
Now let us define the generalized Fibonacci sequence $(f_{n,r})$ for $(r\geq 2)$ by:
$$f_{n,r}=f_{n-1,r}+f_{n-2,r}+\cdots+f_{n-r,r}.$$
with $(f_{0,r}=f_{1,r}=\cdots=f_{r-2,r}=0 \, , \, f_{r-1,r}=1)$ . Note that $r = 2$ gives the Fibonacci number. we can
see that $(Q_r^n)$ has a closed form based on $(f_{n,r})$.
We now use the matrix $Q_r$ to show that the product of two elements of finite order In a non-abellan group
is not necessarily of finite order. Let:
$$
R_{r}=\left({\begin{array}{ccccccc}
-1&0&0&\cdots&0&0\\
0&1&0&\ddots&\ddots&\vdots\\
\vdots&\ddots&1&\ddots&\ddots&\vdots\\
\vdots&\ddots&\ddots&\ddots&\ddots&\vdots\\
\vdots&\ddots&\ddots&\ddots&1&0\\
0&0&0&\cdots&0&1\end{array}}\right)$$
$$
S_{r}=\left({\begin{array}{ccccccc}
-1&-1&0&\cdots&\cdots&0\\
1&0&1&\ddots&\ddots&\vdots\\
\vdots&\vdots&\ddots&\ddots&\ddots&\vdots\\
\vdots&\vdots&\ddots&\ddots&\ddots&0\\
\vdots&\vdots&\ddots&\ddots&\ddots&1\\
1&0&0&\cdots&\cdots&0\end{array}}\right)
$$
be elements of the group of Invertible square matrices, then:
$$R_r^2=S_r^{r+1}=I_r\, .$$
so $(R_r)$ and $(S_r)$ are of finite order, but ${(R_rS_r)}^n=Q_r^n \neq I_r$ for all n,
so that $(R_rS_r)$ Is not  of finite order.

Finite order In a non-abelian group


How can I find the X/Y coordinates of a parallel line

Question: Disclaimer - I am in no way a mathematician so please cater to my ignorance and explain everything as clearly as you can, if you are able to explain using code rather than notation, please do - If this question would be better suited to another StackExchange site please do tell me and I will move it
I currently have two sets of X/Y coordinates which describe the beginning and end of a line, what I hope to achieve is to plot two parallel lines of equal length either side of the line I have. I would need to be able to vary the distance between the lines. Please see my crude diagram below.

In the above image, I have X/Y 1 and 2, but need 3,4,5,6 where i is variable.
This is to solve a programming problem, so if you have Python code to hand, that would be ideal, however just an explanation will do the trick.
Comment: This can be done with translation vectors. A vector can be expressed with an $x$ component and a $y$ component. Say you have a line between the points ($X_1$, $Y_1$) and ($X_2$, $Y_2$). Now, if you have a vector $(u,v)$, one of the lines is a line between the points $(X_1+u, Y_1+v)$ and $(X_2+u, Y_2+v)$. The other line will be between the points $(X_1-u, Y_1-v)$ and $(X_2-u, Y_2-v)$. If the two "red" lines need to form a rectangle, not just a generic parallelogram, a restriction is needed on the vector, it must be perpendicular to the line.
Comment: Thank you for your time Cristhian, I will read up on this and hopefully it will lead me to an answer. Apologies this must seem like "Maths for Kids" :)
Answer: Suppose your reference (green) line $L_1$ is described by the equation $ax + by + c = 0$.
(We'll see how to find $a, b$ and $c$ later.) Note that there are many tuples $(a,b,c)$ that describe the same line; they're all multiples of each other.
Let $P_1 = (x_1,y_1)$ and $P_2=(x_2,y_2)$ be the two given points on this line.
You need to translate $L_1$ along with $P_1$ and $P_2$ along the direction of a vector normal/orthogonal/perpendicular to $L_1$. One such vector is $(a, b)$. Normalizing this vector to have length one, we have the vector
$$
  (u, v) = \frac{1}{\sqrt{a^2 + b^2}}(a, b)
$$
So $(u, v)$ is a unit vector orthogonal to $L_1$.
Translate $P_1$ and $P_2$ by distance $d$:
$$
P_3 = P_1 + d(u, v) = (x_1 + du, y_1+dv)\\
P_4 = P_2 + d(u, v) = (x_2 + du, y_2+dv)\\
P_5 = P_1 - d(u, v) = (x_1 - du, y_1-dv)\\
P_6 = P_2 - d(u, v) = (x_2 - du, y_2-dv)
$$
Note that $(P_3, P_4)$ and $(P_5, P_6)$ are interchangeable depending on which direction $(u,v)$ points.
Here's how to find $a, b$ and $c$. The defining equation for a line through 2 distinct points $(x_1,y_1)$ and $(x_2, y_2)$ is
$$
  (y_1-y_2)(x-x_1) - (x_1-x_2)(y - y_1) = 0
$$
i.e.
$$
  (y_1-y_2)x - (x_1-x_2)y - (y_1-y_2)x_1 + (x_1-x_2)y_1 = 0
$$
So you can take
$$
a = y_1-y_2\\
b = x_2 - x_1\\
c = - (y_1-y_2)x_1 + (x_1-x_2)y_1
$$
Comment: Myath, thank you very much for taking the time to write this up, it's appreciated. I will be picking this up in the morning after a large cup of coffee.
Answer: There are many possible approaches but I would probably use an algorithm like this:
Calculate the change in $x$ and the change in $y$ for the original line. Call these $\Delta x$ and $\Delta y$. (For clarity - these are single values and in code you could call them something like "delta_x" and "delta_y".)
$$\Delta x = x_2 - x_1$$
$$\Delta y = y_2 - y_1$$
Now consider the parallel line that is below the original line. To find the coordinates of the ends of this line, you would need to add certain values to the old $x$ and $y$ coordinates. Let's call these $\delta x$ and $\delta y$. (Make up some new names for them in your code!) Now suppose the distance $i$ between the lines was the same as the length of the original line. Then we would be creating a square and the relevant values would be:
$$\delta x = \Delta y$$
$$\delta y = -\Delta x$$
(Note the switch in $x$ and $y$ and the negative sign for $\delta y$. To convince yourself of this, draw a diagram of the square.)
But since $i$ is not in general the same as the length of the original line we need to adjust. First let's calculate the length of the original line, call it $L$. By Pythagoras:
$$L=\sqrt {\Delta x^2 + \Delta y^2}$$
And the relevant adjustment factor is $i / L$, giving:
$$\delta x = \Delta y \times i / L$$
$$\delta y = -\Delta x \times i / L$$
Now you can simply add $\delta x$ and $\delta y$ to each of your original pairs of coordinates for the lower line, and subtract them for the upper line.


Shortcut to add files into local sql database

Question: I would like to be able to right click on a file(s) and "send-to" a local MSSQL database. The details are that I would like to store the file contents in "contents" column and the file name in the "filename" column ... how novel :)
*In most cases the file contents is HTML.
It seems like it should be possible through windows shell/SQL Shell using a shortcut to a command in the "shell:sendto" folder.
Answer: <code>[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null

$Server1 = New-Object ("Microsoft.SqlServer.Management.Smo.Server") 'SQLSERVER'
$Server1.databases["DB"].tables["Table"].rowcount
$RowCount = $server1.databases["DB"].tables["Table"].rowcount.ToString()

$TotalRecords = [int]$RowCount

$wc = New-Object system.net.WebClient
$url = ""

$files = @(Get-ChildItem c:\test\*.*)

"Number of files $($files.length)"
# Errors out when no files are found
if($files.length -lt 1) { return }

foreach($file1 in $files) {
    # $txt = Get-Content($file1)
    # $txt = $txt.Replace("'", "''")
    # Write-Host $file1.name + "  - - " + $Txt

    $url1 =  $url + $file1
    Write-Host("URL is " + $url1)

    $webpage = $wc.DownloadData($url1)
    $string = [System.Text.Encoding]::ASCII.GetString($webpage)
    $string = $string.Replace("'", "''")

Invoke-SqlCmd -ServerInstance SERVER -Query "Insert into DATABASE.dbo.Table(text,filename) Values ('$string','$file1')"}
</code>


I require assistance with a SQL syntax error

Question: I am writing code for my register and login system, and when I was testing I receiving some errors, there is this one:

"You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near 'WHERE username = ''' at line 1"

Could you please tell me what this means and what to do to solve it.
Here is the code in my update-profile.php
<?php session_start();
ini_set("display_errors",1);
$temp=$_SESSION['username'];
if(isset($_POST)){
    require 'database1.php';
    $Destination = 'background-images';
    if(!isset($_FILES['BackgroundImageFile']) || !is_uploaded_file($_FILES['BackgroundImageFile']['tmp_name'])){
        $BackgroundNewImageName= 'background.jpg';
        move_uploaded_file($_FILES['BackgroundImageFile']['tmp_name'], "$Destination/$BackgroundNewImageName");
    }
    else{
        $RandomNum = rand(0, 9999999999);
        $ImageName = str_replace(' ','-',strtolower($_FILES['BackgroundImageFile']['name']));
        $ImageType = $_FILES['BackgroundImageFile']['type'];
        $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
        $ImageExt = str_replace('.','',$ImageExt);
        $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
        $BackgroundNewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
        move_uploaded_file($_FILES['BackgroundImageFile']['tmp_name'], "$Destination/$BackgroundNewImageName");
    }
    $sql1="UPDATE users SET backgroundpicture='$BackgroundNewImageName' WHERE username = '$temp'";
    $sql2="INSERT INTO users (backgroundpicture) VALUES ('$BackgroundNewImageName') WHERE username = '$temp'";
    $result = mysqli_query($database,"SELECT * FROM users WHERE username = '$temp'");
    if( mysqli_num_rows($result) > 0) {
        if(!empty($_FILES['BackgroundImageFile']['name'])){
            mysqli_query($database,$sql1)or die(mysqli_error($database));
            header("edit-profile.php?username=$temp");
        }
    }
    else {
        mysqli_query($database,$sql2)or die(mysqli_error($database));
        header("edit-profile.php?username=$temp");
    }
    $Destination = 'avatars';
    if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])){
        $NewImageName= 'default.png';
        move_uploaded_file($_FILES['ImageFile']['tmp_name'], "$Destination/$NewImageName");
    }
    else{
        $RandomNum   = rand(0, 9999999999);
        $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
        $ImageType = $_FILES['ImageFile']['type'];
        $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
        $ImageExt = str_replace('.','',$ImageExt);
        $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
        $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
        move_uploaded_file($_FILES['ImageFile']['tmp_name'], "$Destination/$NewImageName");
    }
    $sql5="UPDATE users SET avatar='$NewImageName' WHERE username = '$temp'";
    $sql6="INSERT INTO users (avatar) VALUES ('$NewImageName') WHERE username = '$temp'";
    $result = mysqli_query($database,"SELECT * FROM users WHERE username = '$temp'");
    if( mysqli_num_rows($result) > 0) {
        if(!empty($_FILES['ImageFile']['name'])){
            mysqli_query($database,$sql5)or die(mysqli_error($database));
            header("location:edit-profile.php?username=$temp");
        }
    }
    else {
        mysqli_query($database,$sql6)or die(mysqli_error($database));
        header("location:edit-profile.php?username=$temp");
    }
    $user_firstname=$_REQUEST['firstname'];
    $user_lastname=$_REQUEST['lastname'];
    $user_email=$_REQUEST['email'];
    $user_password=$_REQUEST['password'];
    $user_shortbio=$_REQUEST['bio'];
    $user_dob=$_REQUEST['dob'];
    $user_gender=$_REQUEST['gender'];
    $sql3="UPDATE user SETs firstname='$firstname',lastname='$lastname',email='$email',password='$password',bio='$bio',dob='$dob',gender='$gender', WHERE username = '$temp'";
        mysqli_query($database,$sql3)or die(mysqli_error($database));
        header("edit-profile.php?username=$temp&request=profile-update&status=success");
}

Comment: Your script is vulnerable to SQL injection. You should be using prepared statements. I hope this won't be used in a production environment.
Comment: Since you are using mysqli,  kindly start by implementing prepared statements before you take this into production. Also you have another flaw, do not store passwords in plain text.  Use php's password hash and password verify
Comment: You have several issues with your code. The second `if`-statement is: `if(!isset($_FILES['BackgroundImageFile']) || ...` and _inside_ that if block, you have `move_uploaded_file($_FILES['BackgroundImageFile']['tmp_name'],...`. That will obviously fail, since that block runs if `$_FILES['BackgroundImageFile']` _doesn't_ exist. You're doing the same thing further down with `$_FILES['ImageFile']`
Answer: In the below line you have error:
 $sql3="UPDATE user SETs firstname='$firstname',lastname='$lastname',
         email='$email',password='$password',bio='$bio',dob='$dob',
          gender='$gender', WHERE username = '$temp'";
                         ^^^here you have extra comma

Remove the last , from the query.
Your query should be this:
$sql3="UPDATE user SETs firstname='$firstname',lastname='$lastname',
     email='$email',password='$password',bio='$bio',dob='$dob',
       gender='$gender' WHERE username = '$temp'";

And where clause is not used with Insert query.
Answer: In insert syntax, you have used where
$sql6="INSERT INTO users (avatar) VALUES ('$NewImageName') WHERE username = '$temp'";

should be
$sql6="INSERT INTO users (avatar) VALUES ('$NewImageName')";
$sql2="INSERT INTO users (backgroundpicture) VALUES ('$BackgroundNewImageName')";

also with
 $sql3="UPDATE user SETs firstname='$firstname',lastname='$lastname',email='$email',password='$password',bio='$bio',dob='$dob',gender='$gender', WHERE username = '$temp'";

should be as below, remove , before WHERE
$sql3="UPDATE user SET firstname='$firstname',lastname='$lastname',email='$email',password='$password',bio='$bio',dob='$dob',gender='$gender' WHERE username = '$temp'";

and I would also suggest to read basic document


How can I evaluate $\lim_{x\to \infty }\left( x^2 - \frac x2 - (x^3 + x+1 ) \ln \left(1+ \frac 1x \right) \right)$ using L'Hospital's rule?

Question: How can I find the following limit using the L'Hospital's rule?

$$\lim_{x\rightarrow \infty }\left( x^2 - \frac x2 - (x^3 + x+1 ) \ln \left(1+ \frac 1x \right) \right)$$

I have already tried to replace $1/x$ with $t \,\,(t\rightarrow 0)$, but the only result I get is infinity, which is incorrect.
Comment: Can you write down in your post with details what you got after replacing $1/x$ with $t$?
Answer: By Taylor expansion, we see that for $x>1$,
\begin{align*}
\dfrac{1}{x}-\dfrac{1}{2}\dfrac{1}{x^{2}}+\dfrac{1}{3}\dfrac{1}{x^{3}}-\dfrac{1}{4}\dfrac{1}{x^{4}}\leq\log\left(1+\dfrac{1}{x}\right)\leq \dfrac{1}{x}-\dfrac{1}{2}\dfrac{1}{x^{2}}+\dfrac{1}{3}\dfrac{1}{x^{3}},
\end{align*}
so
\begin{align*}
x^{2}-\dfrac{1}{2}x+\dfrac{1}{3}+1+p\left(\dfrac{1}{x}\right)\leq(x^{3}+x+1)\log\left(1+\dfrac{1}{x}\right)\leq x^{2}-\dfrac{1}{2}x+\dfrac{1}{3}+1+q\left(\dfrac{1}{x}\right),
\end{align*}
where $p$ and $q$ are polynomials.
By Squeeze Theorem, the limit goes to $-4/3$.
With L'Hospital:
\begin{align*}
&\lim_{x\rightarrow\infty}x^{2}-\dfrac{x}{2}+(x^{3}+x+1)\log\left(1+\dfrac{1}{x}\right)\\
&=\lim_{x\rightarrow\infty}\dfrac{\dfrac{1}{x}-\dfrac{1}{2x^{2}}+\left(1+\dfrac{1}{x^{2}}+\dfrac{1}{x^{3}}\right)\log\left(1+\dfrac{1}{x}\right)}{\dfrac{1}{x^{3}}}\\
&=\lim_{t\rightarrow 0}\dfrac{t-\dfrac{1}{2}\cdot t^{2}+(1+t^{2}+t^{3})\log(1+t)}{t^{3}}\\
&=\lim_{t\rightarrow 0}\dfrac{1-t-(2t+3t^{2})\log(1+t)-(1+t^{2}+t^{3})\cdot\dfrac{1}{1+t}}{3t^{2}}\\
&=\lim_{t\rightarrow 0}\dfrac{1-t^{2}-(3t^{3}+5t^{2}+2t)\log(1+t)-(1+t^{2}+t^{3})}{3(t^{3}+t^{2})}\\
&=\lim_{t\rightarrow 0}\dfrac{-2t-t^{2}-(3t^{2}+5t+2)\log(1+t)}{3(t^{2}+t)}\\
&=\lim_{t\rightarrow 0}\dfrac{-2-2t-(6t+5)\log(1+t)-\dfrac{3t^{2}+5t+2}{1+t}}{3(2t+1)}\\
&=-\dfrac{4}{3}.
\end{align*}
Comment: Thank you so much!
Answer: Using Taylor series you get $\log(1+1/x)=\frac{1}{x}-\frac{1}{2x^2}+\frac{1}{3x^3}+\ldots$, thus $$(x^3+x+1)\log(1+1/x)=(x^3+x+1)(\frac{1}{x}-\frac{1}{2x^2}+\frac{1}{3x^3}+\ldots)=$$
$$x^2-\frac{x}{2}+\frac{1}{3}+1+\text{other terms that goes to 0 for }x\rightarrow\infty.$$
Hence
$$\lim x^2-\frac{x}{2}-(x^3+x+1)\log(1+1/x)=\lim x^2-\frac{x}{2}-[x^2-\frac{x}{2}+\frac{1}{3}+1+\ldots]=-4/3.$$
Comment: Using Taylor series, everything goes alright, but I need to get the same answer with L'Hospital's :<
Comment: @MariaWhite, you may look at my edited answer.
Answer: We can prove by L'Hospital that
$$\lim_{x\to \infty}\frac{\ln\left(1+\frac1x\right)-\left(\frac1x-\frac1{2x^2}+\frac1{3x^3}\right)}{-\frac1{4x^4}}=\lim_{x\to \infty}\frac{\frac1{x^5+x^4}}{\frac1{x^5}}=\lim_{x\to \infty}\frac{x^5}{x^5+x^4}=1 \\\iff \ln\left(1+\frac1x\right)=\frac1x-\frac1{2x^2}+\frac1{3x^3}+O\left(\frac1{x^4}\right)$$
therefore
$$x^2-\frac12 x-(x^3+x+1)\ln\left(1+\frac1x\right)=$$
$$=x^2-\frac12 x-(x^3+x+1)\left(\frac1x-\frac1{2x^2}+\frac1{3x^3}+O\left(\frac1{x^4}\right)\right)=$$
$$=x^2-\frac12 x--x^2+\frac12x-\frac13-1+O\left(\frac1{x}\right)=-\frac43+O\left(\frac1{x}\right) \to -\frac43$$
Comment: What is O? And do you differentiate something?
Comment: This is the Big-O notation, it simply means that we have other negligeble terms equal or smaller than $1/x^4$. Thus is the more efficient way to use L'Hospital in this case (see the first limit). Note also that we don't need to guess the approximation for the log but we can obtain it using l'Hospital.


Como faço para dar um refresh na página após fazer upload de imagens?

Question: Estou utilizando os seguintes códigos para fazer um upload de imagens e exibí-las em seguida:
Aqui, o HTML:
<form id="formImage" style="display:none">
<input type="file" id="fileUpload" name="fileUpload[]" multiple onchange="saveImages()">
</form>

Aqui, o multiple-upload-ajax.php:
    <?php

if(isset($_FILES['fileUpload']))
{
require 'WideImage/WideImage.php';
date_default_timezone_set("Brazil/East");

$name = $_FILES['fileUpload']['name'];
$tmp_name = $_FILES['fileUpload']['tmp_name'];

$allowedExts = array(".gif", ".jpeg", ".jpg", ".png", ".bmp");

$dir = '../img/empreendimentos/1/galeria/';
    echo "";

for($i = 0; $i < count($tmp_name); $i++)
{
$ext = strtolower(substr($name[$i],-4));

if(in_array($ext, $allowedExts))
{
$new_name = date("Y.m.d-H.i.s") ."-". $i . $ext;

$image = WideImage::load($tmp_name[$i]);

$image = $image->resize(170, 180, 'outside');
$image = $image->crop('center', 'center', 170, 180);

$image->saveToFile($dir.$new_name);

}
}
}

?>

Depois, eu exibo as imagens que estão na pasta, como neste exemplo:
<?php
                $idEmpreendimento = "1";
                $stringTratada = "Fotos Album";
                $image_name = "Nome da imagem";
                $stringAlbum  = '../img/empreendimentos/' . $idEmpreendimento . '/galeria' .'/*.*';
                $files = glob($stringAlbum);
                //$files = glob("img/empreendimentos/1/*.*");
                for ($i=0; $i<count($files); $i++) {
                    $num = $files[$i]; echo '';
                }
            ?>

Já tentei de várias formas possíveis, mas ainda não consegui dar um refresh na página assim que eu envio uma nova imagem. Alugém tem alguma sugestão de php ou javascript e ONDE exatamente eu colocaria este código?
Comment: tente usar echo
Answer: No jQuery também tem o callback complete, ele será executado mesmo na presença de erros, ao contrário do success que será executado só se tudo der certo.
$('#formImage').ajaxSubmit({
   url : 'multiple-upload-ajax.php',
   type : 'POST',
   complete : function(){
      location.reload();
   }
});

Answer: Tente adicionar um success no final de sua chamada
Exemplo:
$('#formImage').ajaxSubmit({
   url : 'multiple-upload-ajax.php',
   type : 'POST',
   success : function(){
      location.reload();
   }
});


Best estimate of conditional probability P(C|A and B) from P(C|A) and P(C|B)?

Question: Assume I have three events A, B, and C, and I know the following probabilities:
Scenario 1:

$P(A)$ and $P(B)$
$P(C|A)$ and $P(C|B)$

Scenario 2:

I additionally know $P(C)$.

I am looking for $P(C|A\cap B)$.
I think it is clear that I cannot calculate this conditional probability in both scenarios because no information is available about the three-fold interaction of A, B, and C; in particular, $P(A\cap B \cap C)$ is unknown.
But what would be the best approximation for $P(C|A\cap B)$?
$P(C|A)$ and $P(C|B)$, and even $P(C)$ might be candidates, but it is clear that none of them can generally be the best approximation because each of them "ignores" available information (about B, A, and both, resp.).
Maybe someone could also tell me terms or even sources where I should lookup this kind of question in literature; "information fusion" seems to be related, but I could not find the answer there, and it seems to be a basic question actually.

Edit: Changed "estimate" by "approximate" as suggested in the comments.
Comment: Hi: I don't know the answer to your question but you already know P(C) in scenario 1 because P(C) = P(C|A)P(A) = P(C|B) P(B). So, you can just stick to scenario 1. Also, do you happen to know if A and B are independent ? It is an interesting question. I thought it would be easy but it doesn't seem to be. I don't know if there's a "field" associated with this problem. It seems more like a "it can be done or it can't be done" type of question.
Comment: @mlofton: I don't think this is true because $P(C|A) \cdot P(A) = P(C \cap A)$, not $P(C)$. In general, A and B are not independent, but that is of course an interesting special case. Estimation can surely be done ($P(C|B)$, e.g., is an example of an estimator), but the question is, what is the best one?
Comment: Do you have any further information? For example, is it possible that C occurs but none of A or B is true? Does this question have a practical background?
Comment: @Ute: No further information in the general case. Yes, I think the question has large practical background, but not a specific one. A common usecase should be that you have data about C in two different datasets, where one dataset additionally contains data about A but not B and vice versa for the other dataset.
Comment: Ah, you got an answer: insufficient information. That is why I was asking ;-)
Comment: The statistical term "estimate" is improper here since you do not have data to "estimate" from. Use instead "approximate" or "interpolate".
Comment: @Xi'an: Agreed, I have changed it.
Comment: @Remirror:  Thanks. My mistake.
Answer: It can't be done, you have insufficient information. What you need to know is
$$
P(C|A \cap B) = \frac{P(A \cap B \cap C)}{P(A \cap B)}
$$
As you can see, for this you need to know the joint probabilities for $A \cap B$, which you don't. You said that you know that it cannot be calculated and you are looking for the "best estimator", but there is really nothing good. You would need to know the relation between $A$ and $B$. It is a completely different story if $A$ happens always when $B$ happens, then if $A$ happens never when $B$ happens, or if they are independent.
For a simple example, imagine that you are trying to guess if a patient will get cured $C$ using the medicine $A$ or $B$. You know that both medicines are highly effective, hence $P(C|A)$ and $P(C|B)$ are high, what you don't know is what is going to happen if the patient uses both drugs. It may be the case that using the two drugs together would be not better than any of the drugs alone, it also might be the case that they together are twice as good, on another hand, there is a risk that the drugs used together come into a chemical reaction that not only makes them not successful, but they lead to possibly deadly side effects. As you can see, it can be anything, and the individual probabilities don't tell you much about the joint probability.
You could assume that $C$ is independent of $A$ and $B$, then $P(C|A\cap B) = P(C)$, or assume conditional independence and use one of the conditional probabilities as a replacement, but I doubt that this is the answer you were looking for. Neither of the solutions can be considered "best" unless you know something about their joint distribution, but if you knew it, you would not have the problem in the first place.
Comment: @Remirror to convince yourself, create a simple $8 \times 3$ table in Excel for states (yes/no) of $A$, $B$, $C$, and with the fourth column for counts, then you can calculate probabilities like $P(A \cap B \cap \neg C)$ by summing appropriate counts and dividing by total. You would easily see that by manipulating the counts you can make the conditional and marginal probabilities whatever you want and the conditionals can easily be made very different from each other.
Comment: True, but I just do not believe that there is no approach that, at the very least, is "on average" (i.e. accross all possible cases) better than others. For instance, I assume that using $P(C|A)$ as estimator should be better on average than using $P(C)$.
Comment: @Remirror why? By the law of total probability $P(C) = \sum_i \sum_j P(A_i \cap B_j \cap C)$, so $P(C)$ *is* the "on average" answer itself. No reason why it would be better or worse than the conditional probabilities.
Comment: For my understanding, $P(C|A)$ should be a better estimator than $P(C)$ iff C is not independent of A. In other words, your sum averages accross all potential values of A, but that is inefficient if we know the true value of A.
Comment: @Remirror Yes, if you assume conditional independence on $B$. Imagine a trivial counterexample where $P(A \cap B \cap C) = 0$ and all the other probabilities are non-zero. Then, $P(C | A \cap B) = 0$, and the other probabilities (marginal and conditional) are some values that are non-zero. The other probabilities tell you nothing about this case.
Comment: Not sure. About your counterexample: Is it really one? I agree, it is a case where the other probabilities tell me nothing, so they have zero value here, but that does not mean that they also tell me nothing in other cases (positive explainative value).
Comment: And similar for the table you suggest. I see the point, but what does it mean? Still, there surely is one best "strategy" (putting it that way) to approximate $P(C|A\cap B)$.
Comment: @Remirror both examples show that $P(C|A)$ and $P(C|A\cap B)$ are the same only if you assume conditional independence. Otherwise, you have no guarantee whatsoever that they would be close to each other. So in this sense, there is no best strategy.
Comment: There may be upper and lower limits depending on the relationships. For example, if P(A)>0.5 and P(B) >0.5, we can infer that mutual exclusivity of the events is impossible. If P(A), P(B), and P(C) are all close to 1, we can infer that P(C|A and B) must also be quite likely. There's too much missing information to properly approximate, but it is possible to infer upper and lower bounds - we don't always have *zero* information on the joint probability, we may be able to infer something about it from the marginals.
Comment: @NuclearHoagie sure, but those would be very wide bounds that would tell more on what the probability isn't rather than what it is.
Comment: @Tim The bounds depend on the probabilities, they can be quite wide, but also narrow down to an estimate with zero uncertainty. It's a contrived example, but if P(A)=P(B)=P(C)=1, then we can infer P(C|A and B)=1 with no uncertainty whatsoever. Relaxing a bit to P(A)=P(B)=P(C)=0.9, we still find P(C|A and B) must be between 0.875 and 1.


How do you customize the title of an RSS feed created by Views RSS?

Question: I have an RSS feed for each user provided by the Views RSS module. The view uses

users/$uid/feed

as the display path. The feed is titled "All articles by 34 on example.com". The "34" is the userid being viewed. I want the title to be "All articles by username on example.com". I can't set this to use a variable/data in the views title field, which does change the RSS title.

I can't use hook_preprocess_html() or _page(), as these  are not called for feeds
I don't see a hook in the Views RSS module, but I may have missed something
I don't want to do this in the theme templates for display, as this feels like the wrong place to put the logic

How do I change this? Is there another preprocess function I can use?
Answer: Not sure how much this will help as its not exactly what you're asking (i think):
I was using views_rss to show comment threads to a question_answer module question. But I wanted the question to show up as the 1st time in the RSS feed (as RSS feeds) may only show 1 piece of data by their nature (eg, comments or new posts or blog posts) ...
I didn't muck with the title of the Feed because I saw issues with Firefox Sage vs. Google Reader as what the "title" of the RSS feed is -- so I stuffed the "FAQ question" to the comment thread at the top of the RSS feed ....
/**
 * Implementation of hook_views_pre_render().
 *
 * For the comment rss feed we want the description to contain something such
 * as "topic #N: topic text". These values are excluded in the view already.
 * The RSS feed supports a description field but cannot have PHP code in it,
 * it's just static text.
 *
 * This is a means to theme the RSS description field for valid RSS feeds. The
 * view enforces that the parent node is published, and that comments are
 * published as well.
 *
 * http://stackoverflow.com/questions/4011505/how-can-i-add-a-summary-row-to-a-drupal-view
 */
function MYMODULE_discussion_views_pre_render(&$view) {

  if ($view->name == 'MYVIEW_discussion_comment_rss' &&
        $view->current_display == 'feed_1') {
    # Insert the question as a leading comment for this feed.
    $question = node_load(array('nid' => ARG(3)));
    $qrow = new stdClass();
    $qrow->comments_subject = htmlentities('Question Was:');
    $qrow->comments_comment = htmlentities($question->field_topic_text[0]['value']);
    array_unshift($view->result, $qrow);
  }
}

EDIT: My answer was coded for a D6 site, but the exact same principal applies to D7 (and I think the code as well).
Answer: Many thanks to the answer from @tenken which led me to the answer. After parsing the depth of the views array in his hook, I found where I could set the title:
function mymodue_views_pre_render(&$view) {
  if($view->name == 'user_rss' && arg(0) == 'users' && is_numeric(arg(1))) {
    $account = user_load(arg(1));
    $view->build_info['title'] = t('All articles by !username on Example.com', array(
      '!username' => $account->name,
    ));
  }
}

Answer: Maybe you can use this:
/**
 * Implements template_preprocess_views_view_rss().
 */
function module_preprocess_views_view_rss(&$vars) {
  if ($vars['view']->name == 'view_machine_name') {
    $vars['title']       = $new_title;
  }
}


Entries in an infinite series

Question: The series $\sum_{n=1}^\infty a_n $ such that its sum is bounded. Given that $a_n\geq 0$ for each $n$, can we prove that $a_n=0$ for infinitely many n?
Given that the sum is bounded, I think that each element must be very small. However, I am not sure if we can say that all $a_n=0$ after some large $n$.
Comment: Counter example : $a_n = (1/n^2)$ which is known to be a convergent series.
Answer: A necessary condition is that the limit of $a_n$ is $0$ as $n\to\infty$. It's not needed that the terms themselves are $0$ after some point. Because that would not be a series, but a finite sum.
Necessary means that it is not enough. There are series where $a_n\to 0$ but are not convergent, like $a_n=\frac{1}{n}$, the harmonic series.
Consider the series
$$\frac{1}{1\cdot 2}+\frac{1}{2\cdot 3}+\frac{1}{3\cdot 4}+\ldots+\frac{1}{n(n+1)}+\ldots$$
The terms are never zero, nevertheless the series converges. The sum is $1$, by the way.
Hope this helps
Answer: This is not in general true.
Consider the series
$ \sum_{k\geq 1} \frac1{k^2} $.

Entries in an infinite series


restrict windows remote desktop

Question: Is there any way to prevent users from launching and using remote desktop and to restrict it to only local admins or domain admins?
The reason being is that we do not want users to remote desktop home, but at the same time we want it to be available to certain users like administrators or power users.
Ideally there is a group policy that can be set to groups or users who have access to the remote desktop application from their machine.
Clarifications:
I need the machine to be able to still have remote desktop work, just only with a specific user or group. The point is that we allow certain users to use remote desktop and others to not have access to it. There are machines where there are multiple users, so we cant just block a whole machine or by IP.
This needs to be done per a user account or login.
Answer: Why are you singling out Remote Desktop?  Why not include VNC, GoToMyPC and so on?
There is no fool-proof way to do this really.  If you make the effort to block as much as possible you are going to have to do a lot of work.
You can setup your firewall to block everything except what you explicatively permit and then allow only the things you control.  Give your administrators some way to temporarily open holes or vpn around the firewall.  You cannot simply block the common port for your users since users could simply setup a VPN/Tunnel of some sort.
Or you can use a tool to build a whitelist of all the allowed application on your machines and block everything else.
Answer: Remote Desktop uses a specific port or protocol, I believe. You could restrict this port on the firewall or network level -- all it only for specific IP addresses.
Comment: And if you are blocking SSH i will run an ssh server on port 443 at home
Comment: And if you aren't blocking SSH, I will simply build a tunnel to get around your firewall.
Answer: Change the GPO Permissions on MSTSC.exe to have Permissions for only the administrators Group to "execute"
Comment: What happens if a user has a copy of mstsc on a flash drive, or if they have an alternate client?
Answer: You want the "Software Restrictions" section of group policy.  There is a good overview here http://technet.microsoft.com/en-us/library/bb457006.aspx.  I haven't worked with it much so I don't know the specifics very well, but you can block applications by a number of different criteria and the "skip administrators" option allows administrators to do whatever they want.
Answer: The easiest way to deal with this situation is through group policy, as stated above.  This will allow administrators to still use Remote desktop from the local machine.  As for VNC/Logmein/Gotomypc, again, use group policy to disallow users from installing software on their machines.  It may be a bit of an IT hassle, but if you're looking for lockdown, it is the easiest way.
If you're not using a domain or group policy, just make the users regular users or power users as opposed to administrators.
Comment: Many tools these days can be used without any installation whatsoever, including VNC.  If is necessary to lock things down hard, then you would have to use a whitelist approach and block everything except the few applications you want to allow your users to use.
Answer: Clarifying question: Is this driven by IT security or performance (bandwidth, etc.) concerns, or concerns about employees 'stealing' company time by using home machines?
If the first issue, then as other posters have already mentioned there are a number of workarounds -- GoToMyPC for example uses HTTP protocol. This assumes that your users are educated enough to implement these changes.
If the second, then you should consider some business-level solutions. If you are able to monitor your employees' computers or network activity, your company simply needs to enforce some form of punishment on offenders - threaten fines, pay cuts, or worse.
Answer: From http://community.spiceworks.com/topic/104009:

If you need to add Domain users to the
  Remote Desktop Users group on an XP
  machine then you need to use
  restricted groups in GPO...
it is under Computer
  configuration/Windows
  settings/Security settings/restricted
  groups. Right click, add group, click
  browse to find domain users. Click ok
  and click add under This group is a
  member of... Type in Remote Desktop
  Users.

Worked fine for me (in a Windows Server 2008 R2 domain, of course).
Update: Right, this would only give access rights to domain users on local computer

Set "Allow users to connect using
Remote Desktop Services" under
"Computer
Configuration/Policies/Administrative
Templates/Windows Components/Remote
Desktop Services/Remote Desktop Session Host/Connections" to true.
Add users/group to "Remote Desktop Users" in "Active Directory Users and Computers"

This would work. Sorry for my misinterpretation of the question.
Comment: That's not quite the information the OP is looking for. That method grants users permission to access machines via RDP. It cannot be used to prevent users from using an RDP client.
Comment: @John Gardeniers, recheck my answer. Hope it helps.

restrict windows remote desktop


AADDC SLDAP Implementation

Question: I am new to Azure's Active Directory Service and it's abstraction is a little bit of a puzzle for me at the moment. What I am trying to do is to have all my AWS EC2 Servers (Linux) be authenticated via LDAP (for SSH Connection).
I have successfully setup the SLDAP, the Public IP Address is already generated and I have bind it to a FQDN (dc.mydomain.com). On my AWS EC2 Linux server, I installed sssd and realmd to be able to accomplish SSH AD Authentication.
Here is the ldap string I use that confirms sldap is working properly:
ldapsearch -H ldaps://directory.mydomain.com:636 -Z -d 5 -x -b "dc=mydomain,dc=com" -D "email@example.com" -W

The command above gives all the info about the DN,CN,OU,DC listed on the Azure AD.
As I try to use PAM on CENTOS7, it seems like the binddn doesn't resolve to any results() -- for sure the dn I'm using exist as it's the one showing on the ldapsearch results.
Does MS Azure have restriction/limitation on this?
Answer: There is no documentation states that there are limits for Azure AD DS with secure LDAP.
From the documentation, it only said that you can access the managed domain with secure LDAP over Internet. Also, it doesn't state that it can be used by application for authenticating against Azure AD.
As an alternative, instead of Azure AD DS with LDAPS, you may look into using Azure AD for Linux logins from link below. You even can find sample code from here.
https://channel9.msdn.com/Blogs/Open/Using-Azure-AD-for-Linux-logins
UPDATE
It works by using Azure AD for SSH login on my RHEL 7.3. Followings are the step by step guide to make Azure AD work for Linux logins.
Prerequisites

An Azure AD directory has been created, and some users exist
Node.js and npm are installed in the Linux VM
A directory application has been created (native client type) and you have the Client ID
Your PAM distribution has pam_exec.so

User provisioning
You need to use the following command to add the Azure AD account, this ensures the user you'll be logging in with is visible by NSS.
sudo useradd -m <user>

Installing
You can download the tarfile  from https://github.com/bureado/aad-login and:
sudo tar xzf aad-login_0.1.tar.gz -C /
cd /opt/aad-login
sudo npm install

Configuring

Open /opt/aad-login/aad-login.js, and change the following items

var directory = '********.onmicrosoft.com';    // The domain name of directory
var clientid  = '****-****-*****-*****-**********';    //The Client ID of the application registered in Azure AD
authorityHostUrl : 'https://login.microsoftonline.com'  //The latest URL of the endpoint

Open /etc/pam.d/sshd and add following rule

auth  sufficient pam_exec.so  expose_authtok /usr/local/bin/aad-login

Note: For Utuntu, you need to add the rule in /etc/pam.d/common-auth

In CentOS 7.x (and other SELinux-enabled distros) you need to disable the policy by running following command:
sudo setenforce 0
Comment: I tried using this. But it is giving me an error which I believe pertaining to the module itself. On that sample codes, I tried to manually login, based on the link on `aad-login.js` and it doesn't go through. I wonder if the endpoint is changed to something else (`login.windows.net`).
Comment: I can get it to work on my RHEL 7.3. You need to update the URL of endpoint to https://login.microsoftonline.com, also, the SELinux should be disabled. I have updated the previous reply, you can check it for more details.
Comment: When I run `node aad-login.js  ` via root, it gives me the AADDC details. However, trying to login via ssh, it gives me error.

---

`Jan 24 12:49:34 ip-172-30-0-184 sshd[17195]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=223-222-222-210.static.imsbiz.com  user=ldap-user`
`Jan 24 12:49:36 ip-172-30-0-184 sshd[17195]: Failed password for ldap-user from 18.104.22.168 port 54248 ssh2`
Comment: Did you add the following rule in /etc/pam.d/sshd correctly.`auth sufficient pam_exec.so expose_authtok /usr/local/bin/aad-login`. Is there any log messages same as below. `pam_exec(sshd:auth): /usr/local/bin/aad-login failed: exit code 139`. Also, please make sure the SELinux is disabled.
Comment: on the `/var/log/secure` it doesn't show any, that's why I tested the script if it work by manually triggering it as root and running the raw commands. On my box, before doing it manually, I can confirm that *SELinux is disabled*. The only thing that's different from your `env` from mine is that I am trying to run it  on Amazon Linux (which is a varient of CentOs). If you can confirm that it's working on your RHEL7, then, something on the OS level (specifically for Amazon Linux) is causing the issue.
Comment: You can try to add the rule to /etc/pam.d/system-auth, instead of /etc/pam.d/sshd. Also, I'll try AAD on CentOS7, and give you feedback later.
Comment: Yes, I did. Did it on both `sshd` and `system-auth` isolating the issue and it still doesn't do it. It keeps on flagging a *password* error -- which doesn't make sense to me.
Comment: I tried what is stated [here](http://superuser.com/questions/900417/pam-exec-so-doesnt-write-password-to-script-when-expose-authtok-is-enabled) and still not to get it running on Amazon Linux
Comment: I test it on CentOS7.3, and it works. I can get the related log message from /var/log/secure. By the way, have you ever run the command  `sudo npm install`?
Comment: Yes I have, made sure the module is there. I haven't gone back to this as I got sidetracks to other projects. But I'll keep you posted once I've get my hands on it once again. If it's working on CENTOS, it should be working on Amazon Linux (maybe needs some tweakings).
Comment: Still no lack for me on this. Though I can confirm that the login works as running the command in raw format gives all the details about the account. Command is `node aad-login.js  `
Comment: Ok, I got it working! Amazon Linux has this default settings on everything inside `/etc/pam.d`. So from someone who's ain't that have much experience on PAM Auth, I have to read some of the docs to recognize the problem. Thanks Andy for the help.
Comment: You are welcome. Glad to hear that you find out the root cause.

AADDC SLDAP Implementation


Show that a multivariable function is bounded and she admits a global maximum

Question: $f(x,y)= \frac{|a + bx + cy|}{1+x^2+y^2}$
$(a,b,c) \in R^3$
I want to show that f is bounded on $R^2$ and that she admits a global maximum.
I tried  to use this theorem  :
For $S$ a compact of $R^n$, for $f : S \to R^n$ $f$ a continuous function on $S$ and $C^1$ then $f$ is bounded on $S$ and admits a global maximum on $S$
But its look wrong because i have to show that she is bounded on $R^2$ and not on $S$
Actually i can say that $f$ is continuous on $R^2$
Comment: It looks like the numerator grows linearly in $x$ and $y$, whereas the denominator grows quadratically. You could try showing that $f$ is sufficiently small outside some closed ball $B$ around the origin (say, less than $|a|$). Then apply your theorem to B and combine it with the upper bound over the complement.
Answer: Here's my approach. You can write
$$\frac{|a+bx+cy|}{1+x^2+y^2} \le \frac{|a|+|bx|+|cy|} {1+x^2+y^2} \text{(triangle inequality)}$$
If each part of the sum is bounded, we can add them up to get the overall bound. So let's look at each part.  The first part is straightforward. It relies on the fact that each summand in the denominator is positive so that the sum is greater than each summand alone (and the reciprocal of the sum is less than the reciprocal of each summand).
$$\frac{|a|} {1+x^2+y^2} \le \frac{|a|}{1}$$
The next two parts use the same argument. We'll work just the $|bx|$ term. There are two cases.
For $|x| \ge 1$:
$$\frac{|bx|} {1+x^2+y^2} \le \frac{|bx^2|}{x^2}=|b|$$
For $|x|<1$:
$$\frac{|bx|}{1+x^2+y^2}<\frac{|b|}{1}$$
A similar argument for the third term let's us conclude that
$$\frac{|cy|}{1+x^2+y^2}\le|c|$$
Adding the parts together, we find an upper bound as desired:
$$\frac{|a+bx+cy|}{1+x^2+y^2} \le |a|+|b|+|c|$$


How to change new to malloc?

Question: I am changing my language from c++ to c and want to use new, however, c doesn't allow the use of new, so i have to use malloc.
malloc(sizeof(*ThreadNum))

the line above does not work when i tried to do it myself and have run out of options. This is the line that i wish to switch. Any tips would be lovely:)
for(i=0; i <NUM_THREADS; i++){

ThreadS [i] = new struct ThreadNum; //allocating memory in heap
(*ThreadS[i]).num = num;
(*ThreadS[i]).NumThreads = i;
pthread_t ID;

printf("Creating thread %d\n", i); //prints out when the threads are created

rc = pthread_create(&ID, NULL, print, (void *) ThreadS[i]); //creates the threads

Comment: @Swordfish It's the opposite, right? This question wants to go from c++ to c.
Comment: Style note: `ThreadS[i]->num = num;` is easier to read.
Comment: `malloc(sizeof(struct ThreadNum))`
Comment: @Jake, don't cast it. In c you don't neet to cast `void *`. It's the most famous question and answer on SO for the [tag:c] tag.
Comment: Wrong question. Right question would be how to change owning raw pointers to smart pointers.
Comment: Do i have to edit this line now?  NewData = (ThreadNum *)threadid; in a separate void  function?
Comment: @IharobAlAsimi Oh. A ... unique ... decision.
Comment: @Swordfish It's a matter of taste. C++ is becoming both, horrible and popular. Like every other popular language, it's ugly. I personally prefer to write c code a lot. It's simpler and programs are elegant. It's also less to remember and more to create.
Comment: @IharobAlAsimi I've got the impression that C++ becomes more and more \*un\*popular. But gains beautifulness with every revision of the standard.
Answer: First thing you need to consider is that new and malloc() are not equivalents. Second thing is that ThreadNum is a struct so you may want to write sizeof(struct ThreadNum) but usually a better choice is like this
ThreadNum *thread_num = malloc(sizeof(*thread_num));

note that above thread_num is not a type or struct, it's a variable and has pointer type. Using * before it means that you want the size of the type with one less level of indirection.
Getting back to my first comment, new does not only allocate memory but it also invokes the object constructor, which is something that does not exist in c.
In c you have to do all the initialization by hand and after checking that malloc() did return a valid pointer.

How to change new to malloc?


Sum distances with units in date range

Question: Given a table with dates in one row and corresponding values in another row (with units), is there a way to automatically sum the values for a specified dynamic date range? For example, given the following table, say I wanted to sum the distances for the last 3 days up to the present day. In this case B2:D2 = 10.

A
B
C
D
...

1
2021-08-27
2021-08-28
2021-08-29
2021-08-30
...

2
3 mi
4 mi
0 mi
6 mi
...

3

I have experimented with numerous combinations of SUM, SUMIF, SUMPRODUCT/COUNTIF, ARRAYFORMULA, and SUBSTITUTE/REGEXEXTRACT, but can't find the right combination.
Answer: Try:
<code>=arrayformula(sum(value(filter(regexreplace(A2:D2,"\ .*",),A1:D1>today()-3))))
</code>

Alternatively:
<code>=arrayformula(sum(value(filter(regexreplace(A2:D2,"\ .*",),A1:D1>max(A1:D1)-3))))
</code>

Sum distances with units in date range


PHP - how to get image from numeric array

Question: I have two pages cloth.php and second one is pickup.php
On cloth.php i can select multiple product (coming from DB) using checkbox which has image, price and title and after submit it redirect to pickup.php page with holding product details.
So i am getting an array (combination of text and images) on pickup.php
i can get using values using
foreach ($dada as $value) {
     echo "
$value

";
}

i am getting demo product (product name), 455 (product price), image.jpg (product image).
I am getting image name here but i want to display image, how can i do this ?
NOTE : number of rows in array vary every time based on selection of products.
Please help
Thanks in advance
Comment: Get the Image name from $_FILES array and Put it in your  Front with Hooks1.png
          [1] => 8
          [2] => Back with Hooks
          [3] => bls 2.png
          [4] => Dart/Regular Blouse
          [5] => 0
          [6] => 5 Days deli.jpg
          [7] => Delivery in 5 days
          [8] => 100
          [9] => Task-106-Add-Ons1.jpg
         [10] => Premium Cotton Lining
         [11] => 150 )
Comment: Please tell me how can i achieve this from this array ?
Comment: Have you stored the images in Server? So that we can give path to it and show?
Comment: Image name is stored in DB and image is saved in a folder
Answer: Filter your master Array of Images and put it in to one array and get the path from server and display it using img tag

$DisplayImages[0] =  "Front with Hooks1.png";
$DisplayImages[1] =  8;
$DisplayImages[2] =  "Back with Hooks";
$DisplayImages[3] =  "bls 2.png";
$DisplayImages[4] =  "Dart/Regular Blouse";
$DisplayImages[5] =  0;
$DisplayImages[6] =  "5 Days deli.jpg";
$DisplayImages[7] =  "Delivery in 5 days";
$DisplayImages[8] =  100;
$DisplayImages[9] =  "Task-106-Add-Ons1.jpg";
$DisplayImages[10] =  "Premium Cotton Lining";
$DisplayImages[11] =  150;

$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);

echo ('<!DOCTYPE html>');
echo ('');
echo ('');
echo ('<title></title>');
echo ('');
echo ('');

 foreach ($DisplayImages as $key => $value)
 {
    $ext = strtolower(pathinfo($value, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
    if (in_array($ext, $supported_image))
    {
    //Give your server path of image here and  Display it.
        $ImgPath = "../I/Profiles".$value;  // In this case I have image in my I folder profiles
        echo ( '');
    }
    else
    {
        echo $value;  // Not an Image
    }
}

echo ('');
echo ('');
// echo "
";print_r($ImagePath);
// exit();

Comment: Thank you so much sir for your efforts, code looks nice but the issue is -> in array i have both text and image not only images.
And i want show result in proper way means , first product name after image and in last price
Comment: sir even is it possible or not ?
otherwise i will change my concept of getting data on other page.


jquery validation plugin does not validate when input comes with values from server

Question: the jsbin
the problem:
<input id="cname" name="name" minlength="2" type="text" required value="test">
comes with given value test. Now when removing the value, the validation plugin does not get triggered.
html
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Name comes with value, when value removed, no error shows!</legend>

      Name (required, at least 2 characters)
      <input id="cname" name="name" minlength="2" type="text" required value="test">

      E-Mail (required)
      <input id="cemail" type="email" name="email" value="" required>

      URL (optional)
      <input id="curl" type="url" name="url">

      <input class="submit" type="submit" value="Submit">

  </fieldset>
</form>

JS
$(function(){
  $("#commentForm").validate();
});

Answer: As per documentation, by default, validation is "Lazy".

Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value

This means that simply loading a form and deleting a value will do nothing.  You would have to wipe out the value and click the submit button to trigger validation.  Then all subsequent interactions are validated on the keyup and focusout events.
DEMO:  http://jsfiddle.net/yo4y9s64/

Refer to this answer to implement "Eager" validation...
onkeyup: function (element, event) {
    if (event.which === 9 && this.elementValue(element) === "") {
        return;
    } else {
        this.element(element);
    }
}

DEMO 2:  http://jsfiddle.net/yo4y9s64/1/
Comment: hm ok. But you know, that doesn't make sense. He gets a valid form, makes it invalid manually by pressing buttons on the keyboard, but gets no feedback. So I have to write a listener for keyup myself that triggers a valid on the form ? that's silly
Comment: @Toskan, I did not say that.  I simply explained how it works by default and quoted the documentation to that effect.  If you want "Eager" validation, it's a simple modification that's been answered before:  http://stackoverflow.com/a/15104059/594235


react to laravel csrf token mismatch error not working even after trying lot

Question: i have tried following things . but still csrf issue persists when sedning post request from react to laravel
i have used barryvh middleware cors to fixed cors issue
in cors.php
'supportsCredentials' => false,
   'allowedOrigins' => ['*'],
   'allowedHeaders' => ['Content-Type', 'X-Requested-With','token','user_token','_token','X-CSRF-TOKEN'],
   'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
   'exposedHeaders' => [],
   'maxAge' => 0,

meta tags in page
   return (

        <input type="hidden" name="_token" value="{{ csrf_token() }}"></input>
        <meta name="csrf-token" content="{{ csrf_token() }}"/>
        {/* { csrf_token() } */}
        {/* { @csrf } */}
        {/* { csrf_field() }*/}

meta tag in root (index.html)

tried following commented code  in post
  return fetch("www.campaignserver.com:3001/test",
        {
            method: 'post',
            credentials: "same-origin",
            headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    //"_token": "{{ csrf_token() }}",
                    "X-Requested-With": "XMLHttpRequest",
                    'X-CSRF-TOKEN': document.querySelector("[name~=csrf-token]
           [content]").content
                },

laravel side -- route.api.php
   // Route::middleware('auth:api')->post('/test', function (Request $request) {
   //     return response()->json(['message' =>'corstest'], 200);
   // });
   // Route::post('test', 'HomeController@test');
  // Route::get('test', 'HomeController@test');

how can i identity the root cause .?please suggest
Answer: Since you are using laravel as an api, using CSRF token doesn't make sense.
By default, when you use the route file routes/api.php there is no CSRF token verification in place. You can verify that in app/Http/Kernel.php:
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class, //<-- HERE IS THE CSRF VERIFICATION
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [ //<--- AS you can see there is no VerifyCsrfToken middleware in API
        \Barryvdh\Cors\HandleCors::class,
        'throttle:300,1',
        'bindings',
    ],
];

For The route you're calling, routes declared in routes/api.php have a prefix by default, you can check that in app\Providers\RouteServiceProvider.php @ mapApiRoutes:
/**
 * Define the "api" routes for the application.
 *
 * These routes are typically stateless.
 *
 * @return void
 */
protected function mapApiRoutes()
{
    Route::prefix('api') //<-- here is the prefix
         ->middleware('api') //<-- this is the kernel middleware used for this route group
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php')); //<-- and here is the related file
}

Comment: web array contains csrf already , in api array i added what you said , stll same issue . i also tried to remmove token param in header array , still issue is sam ,with or without
Comment: @NeerajVerma the POST route you're using is in `api.php` route file ?
Comment: is your base url in `Const.URL.SERVER_BASE_URL + "/test"` equal to `domain.com/api` ? or just the domain ?
Comment: just domain .. full url is www.campaignserver.com:3001
Comment: by default all routes declared in `routes/api.php` have a prefix "api", so you should call for `domain.com/api/test`
Comment: do i also need to declare custom route in route.api
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202550/discussion-between-neeraj-verma-and-n69s).
Comment: i tried return fetch("http://api.campaignserver.com:3001/test",
   {, ... still same issue
Answer: in my case I was using sanctum and this line in the app/kernel.php was causing the issue

EnsureFrontendRequestsAreStateful::class

I just removed it and it is working now
api clause should look like this:
'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

Comment: This is the solution! Thank you so much and I think this answer should be accepted.


Scarlett Solo Gen 3 headphone out noise

Question: As the title suggests, I've recently bought a Scarlett Solo Gen 3 as an interface for a podmic and decided to use the built-in dac to drive a pair of 8-ohm final audio heaphones I use.
The issue is that when I plug the headphones into the headphone out, I get a very annoying noise floor/ faint buzzing sound. Gets worse as I turn the volume knob up, but even at the low setting I use for these headphones (about 10%) I still get headaches from this sound.
I've tried ferrite chokes, and they don't help alleviate the problem. The only thing that seems promising is the back quarter-inch outputs (R&L) that are line-out and meant for speakers. When I plug the heaphones into that I don't get the buzzing sound; however I'm only hearing mono audio and I've got a feeling that there's something wrong about using that output to listen to headphones even with a double male to female adapter. I've read up online and it seems like they're also unbalanced outputs? I don't really know what that means in my case, but might as well add it in.
Would anyone here know what I'm doing wrong, or how I could fix this?
Comment: Is the computer powered or running battery? Did you try a ground lift on the computer power?
Answer: It is possible that you have a bad unit, but you should do some testing before you exchange it.
I have pair of USB powered speakers that get a buzzing sound when they are plugged into the computer's USB ports.  I fixed the problem by using a phone charger for the power, so it was something in the computer's USB that was causing the problem.
Things to test:
Different headphones.
Try different USB ports or going indirectly through a USB hub.
Fans, liquid cooling pumps or other motors can cause electrical noise, so make sure your cable isn't running next to or over anything like that and that the Scarlett isn't sitting on top of something with a fan or motor.
Test with a different USB cable.
Test with nothing connected to the unit (no mic) and all the gains down and phantom power (48v) and "air" off. The can help determine if it is a problem with the headphone amp or something else internal.
The unbalanced line outs in the back are tip/sleeve outputs (balanced outputs use two signals so tip/ring/sleeve). You could send out of the line outs into a headphone amp/splitter and bypass the internal headphone amp as a temporary fix.
Comment: Thanks, I tried with laptop/pc and usb hubs, different ports and cables to no avail. I just settled for a double male TS to TRS splitter without an amp because the headphones are just that easy to drive.

Scarlett Solo Gen 3 headphone out noise


How can I go about filtering a variable or file in autohotkey

Question: I am trying to filter specific information to variable via parsing the clipboard but I need some help doing this.
Loop, parse, clipboard, `n, `r
 {
If A_LoopField contains XYZ
;Copy whatever text is found 2 or 3 lines below into file but continue on.
 }

Here is an example of whats
Clipboard =
(

Line 1 - Blank
Line 2 - XYZ Some text telling my script to copy line 4 and so on
Line 3 - Blank
Line 4 - "Text to be copied"
Line 5 - Blank
Line 6 - XYZ Some text telling my script to copy lines 8 and so on
Line 7 . . .
)
Answer: Not sure if something like this is what you are looking for
cb =
(LTrim
    Line1
    Line2
    copy:5
    Line4
    Line5
    Line6
    copy:10
    Line8
    Line9
    Line10
    Line11
    Line12
)

copied := []

Loop, parse, cb, `n, `r
{
    pos := (v:=strSplit(A_LoopField, ":")[2]) ? v:pos

    if (pos && A_Index >= pos){
        copied.push(A_LoopField)
    }
}

for k, v in copied
{
    msgBox % v
}


Não consigo salvar dados no database do Firebase - React Native

Question: Não consigo salvar dados no database do Firebase - React Native. Já fiz a instalação e o import do Firebase no projeto, o código esta assim:
 componentWillMount(){
  var config = {
    apiKey: "***************************",
    authDomain: "configuracaofirebase-3a6ef.firebaseapp.com",
    databaseURL: "https://configuracaofirebase-3a6ef.firebaseio.com",
    projectId: "configuracaofirebase-3a6ef",
    storageBucket: "configuracaofirebase-3a6ef.appspot.com",
    messagingSenderId: "939162871117"
  };

  firebase.initializeApp(config);
}

salvarDados(){
  var database = firebase.database();
  database.ref("pontuacao").set("100");
}

render() {
  return (
    <View style={styles.container}>
      <Button
        onPress={ () => { this.salvarDados() } }
        title="Salvar dados"
        color="#841584"
        accessibilityLabel="Salvar dados"
      />
      <Text>Meu App</Text>
    </View>
  );
}

O componentWillMount esta dando certo, só não funciona quando eu chamo o método salvarDados, aparece o seguinte erro:
Comment: poste o seu código, não fotos dele, fica mais fácil de entender o problema
Answer: O problema do seu código está no componentWillMount(). O seu component App não está sendo inicializado na sua função render(). Fazendo com que o componentWillMount() não seja executado.
Exemplo de inicialização do componente:
export default class App extends component {
  componentWillMount() { . . . }

  render() {
    <App />
  }
}

A solução para isso é você incluir o AppRegistry (pode ser depois da função render), então seu código vai passar pelo componentWillMount()
import { AppRegistry } from 'react-native';

AppRegistry.registerComponent('<NomeDoProjeto>', () => App);

Caso não queira usar o AppRegistry, você pode incluir o codigo do firebase no seu construtor
constructor(props) {
  super(props);

  var config = { ... }
  firebase.initializeApp(config)
}

Comment: Não deu certo, continuou com o mesmo erro
Comment: colocando a inicialização do firebase no construtor também?
Comment: sim, é como se o comando firebase não estivesse ativo
Comment: esse é todo seu código?
Comment: Sim, eu fiz as importações da seguinte maneira:                              import firebase from '@firebase/app';
import '@firebase/firestore';
import '@firebase/auth';
Comment: to usando a versão 5.7.0 do firebase e a versão 0.57.7 do react-native
Answer: Consegui resolver apenas adicionando um novo import.
Estava assim:
import firebase from '@firebase/app';
depois coloquei assim:
import firebase from '@firebase/app';
import '@firebase/database';


Ring of Fractions Isomorphic to Subring of Quotient Field.

Question:
Let $R$ be an integral domain and let $D$ be a nonempty subset of $R$ that is closed under multiplication. Prove that the ring of fractions $D^{-1}R$ is isomorphic to a subring of the quotient field of $R$

Proof:

Let $F$ be $R$'s quotient field, and let $\iota : D \to F$ be defined by $\iota(d) = de/e$, where $e$ can be taken to be any element in $D$. Since this is map is an injective homomorphism, there is an injective homomorphism $\phi : D^{-1}R \to F$ such that $\phi_D = \iota$. The map being injective implies that $D^{-1}R$ is isomorphic to $\phi(D^{-1}R)$, a subring of $F$.

Does this sound right?
EDIT:
Note that I am using the following theorem in my proof:

Theorem 15: Let $R$ be a commutative ring, $D \subseteq R$ nonempty multiplicative subset without $0$ or any zero divisors. Then there is a commutative unital ring $Q$ such that $R$ is a subring of it and every element of $D$ is a unit in $Q$. The ring $Q$ has the following additional properties:
(1) every element of $Q$ is of the form $rd^{-1}$ for some $r \in R$ and $d \in D$. In particular, if $D=R-\{0\}$, then $Q$ is a field
(2) Let $S$ be any commutative unital ring and let $\varphi : R \to S$ be any injective ring homomorphism such that $\varphi(D)$ is contained in the units of $S$. Then there is an injective homomorphism $\phi : Q \to S$ such that $\phi|_R = \varphi$.

I am using (2), in particular, in concluding that $\phi$ exists.
Comment: It is necessary to require $0\not\in D$.
Comment: @FabioLucchini Thanks. I'll be sure to pass this on to Dummit and Foote.
Answer: It's okay but depending on your level I think you should give more justification to the assertions you state. Also, we need to assume $D$ does not contain $0$. The map $i:D \to F$ should just be the composition $D \to R \to F$ where the last map is $r\in R \mapsto r/1 \in F$. The image of $D$ in $F$ consists of non-zero elements (proof: if $d/1=0$ in $F$ then $dr=0$ for some nonzero $r \in R$ so d=0 since R is a domain), and hence since $F$ is a field, the image of $D$ consists of invertible elements in $F$. Hence by universal property, we get a map $i:D^{-1}R \to F$ sending $r/d \in D^{-1}R \mapsto r/d \in F$. If $r/d \in F$ is $0$, then $rs=0$ for nonzero $s \in R$, so $r=0$. So the map is injective.
Comment: Note that it's *not* required $1\in D$.