text:
Q: Namespaces with Module Imports I am learning Python and am still a beginner, although I have been studying it for about a year now. I am trying to write a module of functions which is called within a main module. Each of the functions in the called module needs the math module to run. I am wondering if there is a way to do this without importing the math module inside the called module. Here is what I have:
main.py:
from math import *
import module1

def wow():

    print pi

wow()
module1.cool()

module1.py:
def cool():

    print pi

When running main.py I get:
3.14159265359

Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.cool()
  File "Z:\Python\module1.py", line 3, in cool
    print pi
NameError: global name 'pi' is not defined

What I'm having a hard time understanding is why I get a name error when running main.py. I know that the variable pi becomes global to the main module upon import because wow can access it. I also know that cool becomes global to the main module upon import because I can print module1.cool and get <function cool at 0x02B11AF0>. So since cool is inside the global namespace of the main module, shouldn't the program first look inside the function cool for the variable pi, and then when it doesn't find it there, look inside main module for the variable pi and find it there?
The only way to get around this that I know of is to import the math module inside module1.py. I don't like the idea of that, though because it makes things more complicated and I am a fan of nice, simple code. I feel like I am close to grasping namespaces, but need help on this one. Thanks.

A: "Explicit is better than implicit" is a design decision that was made by the creators of Python (launch python and run import this).
Therefore, when you run module1.cool(), Python will not look for the undefined pi in the main module.

You'll have to import the math module in explicitly whenever you want to use it - that's just how Python works.
Also, you should avoid from X import *-style imports, that's bad practice too. Here, you could do: from math import pi.

A: As the traceback shows, the problem isn't in main.py, but in module1.py:
Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.cool()
  File "Z:\Python\module1.py", line 3, in cool
    print pi
NameError: global name 'pi' is not defined

In other words, in module1, there is no global name pi, because you haven't imported it there. When you do from math import * in main.py, that just imports everything from the math module's namespace into the main module's namespace, not into every module's namespace.
I think the key thing you're missing here is that each module has its own "global" namespace. This can be a bit confusing at first, because in languages like C, there's a single global namespace shared by all extern variables and functions. But once you get past that assumption, the Python way makes perfect sense.
So, if you want to use pi from module1, you have to do the from math import * in module1.py. (Or you could find some other way to inject it—for example, module1.py could do from main import *, or main.py could do module1.pi = pi, etc. Or you could cram pi into the magic builtins/__builtin__ module, or use various other tricks. But the obvious solution is to do the import where you want it imported.)

As a side note, you usually don't want to do from foo import * anywhere except the interactive interpreter or, occasionally, the top-level script. There are exceptions (e.g., a few modules are explicitly designed to be used that way), but the rule of thumb is to either import foo or use a limited from foo import bar, baz.

A: As others have said, there isn't actually a global pi in your module1.  A good solution for you is this, which only imports pi once from math and explicitly ensures that the pi you're getting is the one from module1:
main.py:
import module1

def wow():
    print module1.pi

wow()
module1.cool()

module1.py:
from math import pi

def cool():
    print pi

A: The simple approach of exec (python 3) or execfile (python 2) as mentioned in the comments by @abarnert may be useful for some workflows.  All that is needed is to replace the import line with:
exec( open("module1.py").read() )       # python 3

and then you can simply call the function with cool() rather than module1.cool().  Within cool(), the variable pi will behave like a global, as the OP had originally expected.
In a nutshell, this is simply hiding a function definition that would otherwise appear at the top of your main program and has both advantages and disadvantages.  For large projects with multiple modules and imports, using exec (instead of a proper namespaces) is probably a mistake as you don't generally want to keep too many things within a single global namespace.
But for simple cases (like using Python as a shell script) exec gives you a simple and concise way to hide shared functions while letting them share the global namespace.  Just note that in this case you might want to give extra thought to how you name your functions (e.g. use v1_cool and v2_cool to keep track of different versions since you can't do v1.cool and v2.cool).
One less obvious disadvantage of using exec here is that errors in the executed code may not display the line number of the error although you can work around this:  how to get the line number of an error from exec or execfile in Python

A: Inside the module you could simply define from math import pi, which would only import pi from math but not the entire math module.


text:
Q: Can you progressively update a JPanel through the EventQueue? I have a log on screen that requires three connections to be set up. Each time a connection is successfully set up I immediately want a buffered image to appear next to it (tick or cross).
At the moment, the images will not appear until the main thread has finished and all three connections are set up. I have tried spawning new threads to deal with the separate connections being set up to see if this may help but it hasn't.
Loading an image (same for cross):
 // Create new JLabel to hold images; stored as a field
    picLabelDataMapper = new JLabel();

 try {
        logger.debug("Reading tick.png image");
        tick = ImageIO.read(new File("tick.png")); // Global Field
    } catch (IOException e) {
        // TODO Auto-generated catch block
        logger.debug("Read tick.png failed");
        e.printStackTrace();
    }

    // Ensure label is not visible; nothing is loaded at this moment anyway
    picLabelDataMapper.setVisible(false);
    // Add label to panel
    panelDataMapper.add(picLabelDataMapper, "cell 3 1");

Check to see if database was set up successfully:
/**
 * Ensure the data Mapper database was set up successfully
 */
public void checkForDataMapperCompletion(){

    if(dataMapperPassed){

        picLabelDataMapper.setIcon(new ImageIcon(tick));
        picLabelDataMapper.setVisible(true);

    }else{
        picLabelDataMapper.setIcon(new ImageIcon(cross));
        picLabelDataMapper.setVisible(true);
    }
}

So whats the best way to perform a sequential update like this:
Database 1 Set Up > Update GUI
Database 2 Set Up > Update GUI
Database 3 Set Up > Update GUI
Any directions/avenues anyone could recommend to explore ? Thanks in advance.

A: Putting your database calls on a separate thread puts you on the right track. However, to update the GUI after each thread completes you need to put the GUI update into a Runnable then call SwingUtilities.invokeLater(Runnable).
Here is a rough pseudo-ish example:
public void hitDatabase() {
    Thread thread = new Thread(new DatabaseHelper());
    thread.start();
}

private static class DatabaseHelper implements Runnable {
    public void run() {
        //Hit the DB here
        codeToHitDB();

        //Once Complete update the GUI
        Runnable runnable = new Runnable() {
            public void run() {
                //Update your GUI
            }
        };

        SwingUtilities.invokeLater(runnable);
    }
}

This tutorial will give you more info: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/
There is also a SwingWorker class that some people claim makes this easier. There are details about SwingWorker in the tutorial.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using the mock returned by another mock in phpspec I'm new at phpspec (coming from phpunit) and I have problems setting the behavior of a mock returned by another mock.
I'm creating a wrapper class around the Guzzle client and I want to check the output of the response.
Here's the spec:
function it_gets_response_status_code(Client $client, Url $url, Response $response)
{
    $this->beConstructedWith($client);

    $url->__toString()->willReturn('http://example.com');
    $data = ['foo' => 'bar'];

    $response->getStatusCode()->willReturn(200);
    $client->request('POST', $url, ['form_params' => $data])->willReturn($response);

    $this->post($url, $data);
    assert($this->getResponseStatusCode() === 200); // Failing! :(
}

and the corresponding functions in my class:
public function post(Url $url, array $data)
{
    $this->response = $this->client->request('POST', (string) $url, ['form_params' => $data]);
}

public function getResponseStatusCode()
{
    return $this->response->getStatusCode();
}

The assertion is failing and when I check what is this status code, I see that instead of the integer 200, it's an instance of PhpSpec\Wrapper\Subject. What am I missing here?
I've searched and googled but cannot find resources about using the mock returned by another mock in phpspec. I'm wondering if the reason for this is that it's a code smell? If so I'd be glad to see how I could do this differently (currently I cannot see how I could keep the code simple and doing differently).

A: try:
assert($this->getResponseStatusCode()->getWrappedObject() === 200);

this:
$response->getStatusCode()->willReturn(200)

returns a '200' string wrapped in an Subject object, on which you can then make mock/stub calls if needed. To get the real value of the subject you need to call getWrappedObject


text:
Q: Descargar un TTS quería preguntar como se podría agregar un botón para descargar el audio según el texto ingresado.
Si no existe la posibilidad de hacerlo, ¿Alguna recomendación?.
Adjunto el código de lo que llevo avanzado.

has('dia_final') ? ' has-error' : '' }}">
    Mensaje

      <input type="text" name="text">
      Escuchar Texto!

    <audio src="" hidden class=speech></audio>

A: Que tal hice la prueba con el código que se encuentra en el Post del comentario ¿Como descargar audio generado con ResponsiveVoice en un archivo MP3 con Javascript?

var texto = document.getElementById('texto');
var play = document.getElementById('play');
var download = document.getElementById('download');

play.onclick = function(event) {
  responsiveVoice.speak(texto.value, 'Spanish Female');
}
texto.onblur = function () {
  var url = '//responsivevoice.org/responsivevoice/getvoice.php?t=' +
      encodeURIComponent(texto.value) + '&tl=es-ES';

  download.href = url;
}
texto.onblur();

Texto: <input id="texto" value="hola mundo" />

<button type="button" id="play">Play</button>
Descargar

Lo Probé desde el IDE de Eclipse en Google Chrome y funciona correctamente, permite reproducir y al presionar en Descargar me muestra lo siguiente y me permite descargar el archivo en formato mp3.

Se descarga un archivo con el nombre getvoice.mp3, trata de probarlo de esta forma.
(Nota: parece que suceden algunos inconvenientes con otros navegadores como lo explica en la publicación). Lo probé en FireFox y no se puede descargar, solo reproducir:


text:
Q: Exocortex.dsp FFT vs mathematically strict DFT. C# in Unity3d I'm calculating the autocorrelation of audio samples. The direct calculation of autocorrelation can be sped from O(n^2) to O(nlogn) by using the the FFT - exploiting the convolution theorem. Both forward and inverse FFT are needed.
I made a test script in python, just to make sure I knew what I was doing, and it works. But in my C# version, it doesn't.
I know that many implementations of the FFT give answers that differ from the mathematically strict DFT. For instance, you may need to divide your results by N (the number of bins.)
... tried that, still didn't work ...
I've striven mightily to find some documentation about the details of Exocortex's FFT, to no avail. (cue someone finding it in < 1 sec...)
Does anyone out there know the details of the Exocortex implementation of FFT, and how to get the mathematically strict values for the DFT, and inverse DFT of a signal?

A: I've got my code working!
As everybody has probably guessed, there was an additional bug in my code, which was confounding my efforts to understand Exocortex's fft.
In Exocortex's forward fft, you need to divide by the fft size to get the canonical values for the transform. For the inverse fft, you need to multiply by the fft size. I believe this is the same as Apple's Accelerate, whereas in numpy and matlab you get the actual DFT values.
Perhaps the practice of requiring division or multiplication by the fft size is extremely widespread – if you know the situation, I invite you to comment.
Of course, many times people are only interested in fft values relative to each other, in which case scaling by a constant doesn't matter.
If anyone out there knows where there is decent documentation for Exocortex DSP, I invite you to comment on that as well.


text:
Q: Results Based on Date and Save as Finished I'm currently building a CMS/CRM system for my company using CodeIgniter, and I will need a way of displaying a list/table of results based upon whether an event has finished or not.
So, if the event start_date is in the past (based on the current timestamp), I need a way to dynamically set the 'active' column to 0 in the database, thus not showing the record.
How would you guys approach this problem? Would really appreciate your thoughts.
Thanks.

A: as simple as you made your question to pull the list:
$data = $this->db->get_where('table',array('start_date <'=>date('Y-m-d H:i:s',strtotime('now'))))->result_array();

if you need to do an update to show that the event is done though:
$this->db->where('active >',0)->where('start_date <',date('Y-m-d H:i:s',strtotime('now')))->update('table',array('active'=>0));

that being, if the start_date column is a mysql timestamp. but regardless, it's as easy as it sounds.


text:
Q: Return multiple MemoryStream as HttpResponseMessage This post might be duplicate but I didn't find a similar post on the stack so I am posting here.
I want to return the list of MemoryStream as HttpResponseMessage. I have multiple files in a folder I just want to return these files as a HttpResponseMessage from web api.
public async Task<HttpResponseMessage> GetDicomImage(string FolderName)
 {
 try
            {

                    var content = new MultipartContent();
                    MemoryStream dataStream = null;
                    filePathInfo = Directory.GetFiles(FolderName);
                    foreach (var dcm in filePathInfo)
                    {
                        var dataBytes = File.ReadAllBytes(dcm);
                        dataStream = new MemoryStream(dataBytes);
                        content.Add(dataStream);
                    }
                    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
                    httpResponseMessage.Content = content;//new StreamContent(dataStream);
                    httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                    //httpResponseMessage.Content.Headers.ContentDisposition.FileName = bookName;
                    httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/dicom");
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    Content = new StringContent(ex.Message)
                };
            }
 }

this is my code i dnt understand what going wrong with it. I am not getting multiple MemoryStream for different files.

A: You can handle it with the JsonConvert.SerializeObject from Newtonsoft.Json package like below:
{
    public async Task<HttpResponseMessage> GetDicomImage(string FolderName)
    {
        var content = new MultipartContent();
        var filePathInfo = Directory.GetFiles(FolderName);
        var files = new List<FileData>();
        foreach (var dcm in filePathInfo)
        {
            var fileData = new FileData { Content = File.ReadAllBytes(dcm), Name = Path.GetFileName(dcm) };
            files.Add(fileData);
        }
        content.files = files.ToArray();
        var str = JsonConvert.SerializeObject(content);
        httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, str);

    }
}

public class MultipartContent
{
    public FileData[] files;
}

public class FileData
{
    public byte[] Content;
    public string Name;
}

It is not needed to return stream however. It is enough to return byte[] and file name (to make it possible to save file later)
Then you will need to read the response content on client and to deserialize it back to MultipartContent instance
PS Seems that you are trying to send files from the host to the client.
This is not safe since client defines path to be used to get files from. It looks like a security risk even if hosting process do not have permission to read system files.
Probably you can define certain codes for folders to be mapped on the host side.
Like documents - ./documents images - ./images. GetDicomImage should be modified to accept documents images codes and to map the code to the physical paths.
It will prevent client from requesting the "c:\" folder (that will not be processed but can be used to DDOS the hosting service.)


text:
Q: Lubuntu 14.04 - can't connect via wi-fi after deleting and re-creating connection I had a wi-fi connection to my Amped APA20 access point working fine, but I deleted the connection and when I re-created it, now Lubuntu won't connect. Nothing else on the system has changed. Could the system have information in a file somewhere which is preventing the re-created connection from working? I created a new wi-fi connection using my cell phone as a mobile hotspot, temporarily, which works fine.
[Additional info: I had the APA20 set to not broadcast the SSID. When I set it to broadcast, the wi-fi connection is seen by Lubuntu and it connects. This is contrary to past experience, though- I have been able to connect to hidden (non-broadcast) wi-fi networks before.
Update- when I set the APA20 back to not broadcasting the SSID, Lubuntu can now connect to the network. Why it can connect now and couldn't before is somewhat of a mystery.]

A: You can try manually deleting anything that might be left over.

*

*Open a terminal

*Enter cd /etc/NetworkManager/system-connections/

*Enter ls to see what's in the directory

*Enter sudo rm <filename> to delete a connection

You might have to log out and back in for it to take effect. The Ubuntu Network Manager tends not to like it when you manually delete connections.


text:
Q: Send mail with "Send As" or change sender I'm making a script to automate Outlook 2016. I have one account with two different inboxes from clients.
At the end of the script, I need to send an email from the name of the inbox the script is run from. I'm authorized to send email in the name of both inboxes, but I can't get the script to do it. I post my actual code:
The code:
Function Send-Email {
    param ([String]$desde,[String]$subject,[String]$buzon,[String]$inc)

$mail = $Outlook.CreateItem(0)
$firma ="
Textplan
"

$mail.subject = "Closed Ticket "+$subject
[String]$cuerpo =@"
Dear colleague,

bla bla bla

Thank you.
"@

$mail.sender = $buzon
$mail.body = $cuerpo+" "+$firma
$mail.To = $desde
$mail.Send()
Start-Sleep 3

}

$Outlook = New-Object -ComObject Outlook.Application
$desde = client2@mail.com
$buzon = inbox1@mail.com
$inc = 000000001
$subject = "Automat request"
Send-Email -desde $desde -subject $asunto -buzon $Buzon1 -inc $inc

A: Your issues look to be:

*

*Object defined outside the function it's being used in:
$Outlook = New-Object -ComObject Outlook.Application

*Unquoted strings in variables:
$desde = client2@mail.com
$buzon = inbox1@mail.com
$inc = 000000001

*Mix and match of single and double quotes

*

*I'd recommend reading about_quoting_rules to understand the difference as this is quite crucial when using variables within strings.

*the function param $inc is defined has data but is not used for anything?

*

*Recommend to remove this if it's not used.

Not specifically an issue, but I've changed the here string (@" "@) to a normal string with line breaks (`r`n`)

After resolving the issues and tidying the code:
Function Send-Email {
    param (
        [String]$desde,
        [String]$subject,
        [String]$buzon,
        [String]$inc
    )

    $firma = 'Textplan'
    $cuerpo = "Dear colleague,`r`nbla bla bla`r`nThank you."

    $Outlook = New-Object -ComObject Outlook.Application
    $mail = $Outlook.CreateItem(0)
    $mail.subject = 'Closed Ticket ' + $subject
    $mail.sender = $buzon
    $mail.body = "$cuerpo $firma"
    $mail.To = $desde
    $mail.Send()
    Start-Sleep 3
}

$desde = 'client2@mail.com'
$subject = 'Automat request'
$buzon = 'inbox1@mail.com'
$inc = '000000001'

Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc

I don't have Outlook to test the code, but from checking it over with the Outlook.Application documentation it now seems to be valid.

A: I finally used this lines and work well:
$mail.SentOnBehalfOfName = "inbox1d@mail.com"
$mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}

Function Send-Email {
    param (
        [String]$desde,
        [String]$subject,
        [String]$buzon,
        [String]$inc
    )

    $firma = 'Textplan'
    $cuerpo = "Dear colleague,`r`nbla bla bla`r`nThank you."

    $Outlook = New-Object -ComObject Outlook.Application
    $mail = $Outlook.CreateItem(0)
    $mail.subject = 'Closed Ticket ' + $subject
    $mail.sender = $buzon
    $mail.body = "$cuerpo $firma"
    $mail.SentOnBehalfOfName = "inbox1d@mail.com"
    $mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
    $mail.Send()
    Start-Sleep 3
}

$desde = 'client2@mail.com'
$subject = 'Automat request'
$buzon = 'inbox1@mail.com'
$inc = '000000001'

Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc


text:
Q: Why PWA promotted to add to homescreen but just create chrome shortcut and not installed as apk? I check all  add to home screen criteria, and I think I provided all of them in my PWA. When a user visits my PWA Mini-infobar is shown and when user click add to home screen, just shortcut of PWA added to home screen and not installed. PWA is not in the applications list and deep link not working.
UPDATE:
I am in Iran and I realized when my ANDRIOD device connects to VPN or be behind a proxy in other countries web APK installed fine. But if Andriod is connected to Iran network without proxy just chrome shortcut added to home screen.


text:
Q: how to convert doc into docx using power automate I have written a code in C# which converts doc file into docx file. the word documents are looking for template on network drive which is slowing the process. It is taking more than 20 mins to just open the doc file.
Is there any way using power automate/MS flow or any other MS technology which converts the doc into docx without getting connected to network drive for templates?


text:
Q: Tension vs. Temperature in a stretched string Is there a nice way to express tension in a stretched string of fixed length (like a piano string) as a function of temperature?

A: You need to know the Young's modulus of the (steel?) string and its coefficient of the thermal expansion.  Use  the expansion coefficient to compute  the length of the string at temperature $T$ and how much you have to stretch it to the length it needs. Then use Young's modulus to compute the tension needed to stretch it this much.


text:
Q: Help me tune the long-running query I have a problem with the following query executing from the application (Microsoft Dynamics AX):
DECLARE @p1 INT;
SET @p1 = NULL;
DECLARE @p2 INT;
SET @p2 = 0;
DECLARE @p5 INT;
SET @p5 = 2 + 4096;
DECLARE @p6 INT;
SET @p6 = 8193;
DECLARE @p7 INT;
SET @p7 = 0;
EXEC sp_cursorprepexec
     @p1 OUTPUT,
     @p2 OUTPUT,
     N'@P1 nvarchar(5),@P2 int,@P3 nvarchar(5),@P4 int,@P5 nvarchar(5),@P6 nvarchar(5),@P7 datetime,@P8 nvarchar(21),@P9 numeric(28, 12)',
     N'SELECT A.INVENTTRANSIDFATHER,B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_ FROM INVENTTRANS A,INVENTTRANS B,INVENTTABLE C WHERE ((A.DATAAREAID=@P1) AND (A.TRANSTYPE=@P2)) AND ((B.DATAAREAID=@P3) AND (((B.INVENTTRANSID=A.INVENTTRANSIDFATHER) AND (B.TRANSREFID=A.TRANSREFID)) AND (B.TRANSTYPE=@P4))) AND ((C.DATAAREAID=@P5) AND (C.ITEMID=B.ITEMID))
AND EXISTS (SELECT ''x'' FROM INVENTSETTLEMENT D WHERE ((D.DATAAREAID=@P6) AND ((((D.TRANSDATE=@P7) AND (D.VOUCHER=@P8)) AND (D.TRANSRECID=A.RECID)) AND (D.COSTAMOUNTADJUSTMENT<>@P9))))
 GROUP BY A.INVENTTRANSIDFATHER,B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_ ORDER BY B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_',
     @p5 OUTPUT,
     @p6 OUTPUT,
     @p7 OUTPUT,
     N'dat',
     8,
     N'dat',
     2,
     N'dat',
     N'dat',
     '2017-05-17 00:00:00.000',
     N'IM17008141934',
     '0.000000000000';
EXEC sp_cursorfetch
     @p2,
     2,
     1,
     1;

The estimated plan for this query is here
XML version here
The query keeps running for almost 3 hours. I have also captured metrics from WhoIsActive sp for this queries session:
wait_info                       (2ms)PAGEIOLATCH_SH:ecc_wrk:4(*)
CPU                             88,765
CPU_delta                       47
tempdb_allocations              0
tempdb_current                  0
tempdb_allocations_delta        0
tempdb_current_delta            0
blocking_session_id             NULL
blocked_session_count           16
reads                           26,610,593
reads_delta                     20,903
writes                          0
writes_delta                    0
physical_reads                  1,212,764
physical_reads_delta            418
used_memory used_memory_delta   276
status                          0
open_tran_count                 1
host_name                       ***
database_name                   ***
program_name                    Microsoft Dynamics AX

As I can see it reads huge amount of data and executes for enormous amount of time.
I also captured the query and executed it in management studio where it took 1 second to complete. The actual execution plan is here:
XML version here
I cannot understand what the problem might me and where to dig. Any help on what to do next will be deeply appreciated.

A: I have managed to resolve the problem.
I have run a trace and captured what was happening on the server.
Tom V, thanks a  lot. It was actually some form of parameter sniffing. AX first executed a query like this:
declare @p1 int
set @p1=NULL
declare @p2 int
set @p2=0
declare @p5 int
set @p5=28688
declare @p6 int
set @p6=8193
declare @p7 int
set @p7=9
exec sp_cursorprepexec @p1 output,@p2 output,N'@P1 nvarchar(5),@P2 int,@P3 nvarchar(5),@P4 int,@P5 nvarchar(5),@P6 nvarchar(5),@P7 datetime,@P8 nvarchar(21),@P9 numeric(28, 12)',N'SELECT A.INVENTTRANSIDFATHER,B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_ FROM INVENTTRANS A,INVENTTRANS B,INVENTTABLE C WHERE ((A.DATAAREAID=@P1) AND (A.TRANSTYPE=@P2)) AND ((B.DATAAREAID=@P3) AND (((B.INVENTTRANSID=A.INVENTTRANSIDFATHER) AND (B.TRANSREFID=A.TRANSREFID)) AND (B.TRANSTYPE=@P4))) AND ((C.DATAAREAID=@P5) AND (C.ITEMID=B.ITEMID)) AND EXISTS (SELECT ''x'' FROM INVENTSETTLEMENT D WHERE ((D.DATAAREAID=@P6) AND ((((D.TRANSDATE=@P7) AND (D.VOUCHER=@P8)) AND (D.TRANSRECID=A.RECID)) AND (D.COSTAMOUNTADJUSTMENT<>@P9)))) GROUP BY A.INVENTTRANSIDFATHER,B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_ ORDER BY B.INVENTTRANSID,B.TRANSREFID,C.MODELGROUPID,C.COSTGROUPID,C.DIMENSION,C.DIMENSION2_,C.DIMENSION3_',@p5 output,@p6 output,@p7 output,N'dat',8,N'dat',2,N'dat',N'dat','2017-06-05 00:00:00',N'IM17008151695',0.000000000000
select @p1, @p2, @p5, @p6, @p7

And then (RPC Starting event):
declare @p2 int
set @p2=0
declare @p3 int
set @p3=24592
declare @p4 int
set @p4=8193
declare @p5 int
set @p5=9
exec sp_cursorexecute 1073741872,@p2 output,@p3 output,@p4 output,@p5 output,N'dat',9,N'dat',10,N'dat',N'dat','2017-06-05 00:00:00',N'IM17008151695',0.000000000000
select @p2, @p3, @p4, @p5

Then the Profiler throwed Sort Warning and after 2 hours finally finished.
As you can see in the first statement the parameter value for TransType field was "8", in the second case - "9".
We resolved the issue by using forceliterals as you suggested.

A: First of all, the code you posted is not the code executed by the application. There is no Fetch Queryoperator so you aren't retrieving any rows.
As you noted in chat you constructed the code yourself but it's hard to guess what exactly will be the code executed by AX, that depends on some settings and calculations done by the AX kernel.
First of all, your cursor is likely to be FAST_FORWARD and the number of rows fetched could either be everything at once, or a number of records at a time.
The number of rows fetched at once is defined by the Maximum Buffer Size parameter/the row size. See Microsoft Dynamics AX 2012 Server Configuration
The cursor definition will look something like this
declare @p1 int
set @p1=189527589
declare @p3 int
set @p3=16
declare @p4 int
set @p4=1
declare @p5 int
set @p5=2
exec sp_cursoropen @p1 output,N'SELECT A.JOBTYPE FROM PRODROUTEJOB A WHERE ((A.DATAAREAID=N''IW'') AND ((A.CALCTIMEHOURS<>0) AND (A.JOBTYPE<>3))) AND EXISTS (SELECT ''X'' FROM PRODROUTE B WHERE ((B.DATAAREAID=N''IW'') AND (((((B.PRODID=A.PRODID) AND ((B.PROPERTYID=N''PR1526157'') OR (B.PRODID=N''PR1526157''))) AND (B.OPRNUM=A.OPRNUM)) AND (B.OPRPRIORITY=A.OPRPRIORITY)) AND (B.OPRID=N''GRIJZEN''))) AND NOT EXISTS (SELECT ''X'' FROM ADUSHOPFLOORROUTE C WHERE ((C.DATAAREAID=N''IW'') AND ((((((C.WRKCTRID=A.WRKCTRID) AND (C.PRODID=B.PRODID)) AND (C.OPRID=B.OPRID)) AND (C.JOBTYPE=A.JOBTYPE)) AND (C.FROMDATE>{TS ''1900-01-01 00:00:00.000''})) AND ((C.TODATE={TS ''1900-01-01 00:00:00.000''})))))) GROUP BY A.JOBTYPE ORDER BY A.JOBTYPE ',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

or this
declare @p1 int
set @p1=NULL
declare @p2 int
set @p2=0
declare @p5 int
--
-- Fast Forward(16)+Parameterized(4096)+AutoFetch(8192)+AutoClose(16384)
--
set @p5=16+4096+8192
declare @p6 int
set @p6=8193
declare @p7 int
--
-- Number of Rows for AutoFetch.
-- This is calculated by Maximum Buffer Size (24K default) / Row Length
--
set @p7=4
exec sp_cursorprepexec @p1 output,@p2 output,N'@P1 nvarchar(5),@P2 nvarchar(21)',N'SELECT A.SALESID,A.RECID FROM SALESLINE A WHERE ((DATAAREAID=@P1) AND (SALESID>@P2))',@p5 output,@p6 output,@p7 output,N'ceu',N'SO-100004'
-- @p2 contains cursor handle for fetch call
exec sp_cursorfetch @p2,2,1,@p7

That being said, most of the time when I get a poor performing query in AX the query behaves the same with or without a cursor, and it's rare that I need the actual code including the cursors to be able to reproduce the problem in Management Studio, however if you really need the cursor definition the easiest is if you can reproduce it in a test environment.
Once you can reproduce the issue you need to locate the offending query in code.
If you can reproduce the issue in a test environment (because AX is fairly prone to parameter sniffing) you can use the built-in SQL Statement trace log to find the call stack for the query.
You can also look into the Trace Parser tool to capture traces with the actual parameter values and the code trace up to the query. That can help a lot too.
Once you know where the query is executed you could put a breakpoint just before the query and when you hit it fire up SQL Server Profiler to capture the exact code being executed while you step through the select in your AX debugger.
Once you have the problematic code (if you really need it including cursors) the regular tuning principles are valid.
Your first attempts should be indexing because your options to change the query are a bit limited in AX. Then again the estimated plan you posted only has an estimated cost of 0.04 and uses index seeks I'm not sure this is your problem.
AX is very prone to parameter sniffing because of all the select * resulting in a lot of key lookups.
You could try to use some keywords to influence the plan, namely forceliterals to disable parameterization and force a new plan to be compiled for each execution or you could set some row goals using firstfast and that's about it.
See the Select statement syntax documentation to see which options you have, but don't overdo it with the keywords (as I suggested in my answer to your other question). My first guess is you are running into parameter sniffing.


text:
Q: "I suppose so," said Mrs. Dursley stiffly - (Harry Potter) I read this in a Harry Potter novel:

"I suppose so," said Mrs. Dursley stiffly

I looked up the word "stiffy" in Cambridge dictionary, and saw this definition:

an erection (= when a man's penis is harder and bigger than usual and points up)

I'm a little confused, does it mean that Mrs. Dursley stands up?

A: The answer to "Does it mean that Mrs. Dursley stands up?" is No and is  correctly explained in the answer by user 66974. Therefore I won't repeat it. Instead I shall explain why it is not correct.

Adjective - stiff
Adverb - stiffly

The addition of "y" (as opposed to "ly") to an adjective, is a slang way to convert an adjective into a noun. Note that it is the added sound that is important, not the spelling.
stiffy, stiffie  -  A thing that is stiff, usually slang for erect penis
quicky, quickie - Something that is quick, usually slang for a short sex session
biggy, biggie - A thing that is big. E.g. There's a storm coming and I think it is going to be a biggie.
oldy, oldie - A thing that is old. E.g. When it comes to pop music, the oldies are the best.
fatty, fattie - A person who is fat (This is an insult)
meany, meanie - A person who is mean
When can this be used?
I think it would be very difficult to discover a rule. It might be possible but that would require a separate question. You cannot simply add "y" to any adjective of your choice. To form them requires a feel for the language.
For example, none of the following would work:
annoying ---> annoyingie, to mean an annoying person (incorrect)
fast ---> fasty, to mean something that goes fast (incorrect)
stupid ---> stupidie, to mean a stupid person (incorrect)

A: The root word here is "stiff", with the literal meaning "rigid; hard to bend; inflexible". It's quite a common word, with several figurative meanings and derived words more-or-less connected to that basic definition. Both "stiffy" and "stiffly" come from "stiff", but they are very different words, not connected to each other in any other way.
Adding a "y" or "ie" to the end of words is used in some slang (very informal) words to form a noun (a thing) from an adjective (a description of that thing). So the word you found, "stiffy", is a slang noun literally meaning "a stiff thing", with the particular meaning of an erect penis. An erect penis is rigid, so is literally stiff; there is no particular relevance to any other property like standing up or pointing upwards.
The word in the book is the very different "stiffly". The "ly" ending can be used to turn almost any adjective (describing a thing) into an adverb (describing an action), so "stiffly" basically means "in a stiff way". In this case, it's slightly figurative: Mrs Dursley is speaking unusually formally, or her manner is "stiff" as opposite to "relaxed".
To find the correct root in future, remember that adjectives that already end in "y" usually keep an extra syllable as adverbs, ending "ily" - for example "stuffy" becomes "stuffily, not "stuffly". (I'm sure there are exceptions to this rule, because in English there are always exceptions if you look hard enough!)

A: The term is stiffly, not stiffy

UK -
severely:
I wrote a stiffly worded letter of complaint to the council.

(Cambridge Dictionary)


text:
Q: C# General Question about Master Page I am trying to add a label the following way
public partial class _base : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

        lblText.Text ="Hello";
    }
}

}
The problem is it is telling Object reference not set to an intance of an object. This is the code behind my MasterPage.cs.
  <asp:Label ID="lblText" runat="server" Text="Label"></asp:Label>

In master page

A: Where your code has
Label lblText;

you should put
Label lblText = new Label();

instead. This will make the error go away, because then an actual instance of the label control will be referenced by the lblText variable. But the label will not show up until you also add
 Controls.Add(lblText);

to your page load event.
Alternatively, you could add the label to your page as @amonteiro suggests. Then you could put it in a location that makes sense for the rest of your application.

A: You can't find lblText in your page because it's not part of the page's class. It's part of the master page's class. You have to find it in the master page like so:
Label lblText = (Label) Master.FindControl("lblText")};

Also, don't use a Label if a Literal will do the trick.
Edit: Just realized I might have read your question wrong. If you're trying to find it in the code behind for the Master page itself, then my answer does not apply.


text:
Q: Cant get basic JPA working in a dropwizard application I am trying to persist an object into the database using Dropwizard's JPA annotation.
The object to be persisted
TheObject.java
    @JsonIgnoreProperties(ignoreUnknown = true)
    @Entity
    @Table(name = "TheObject")
    @NamedQuery(name = "com.comany.TheObject.findAll", query = "SELECT o FROM TheObject o")
    public classTheObjectimplements  Serializable{

        /**
         *
         */
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @JsonProperty
        String name;

        @OneToMany(cascade = CascadeType.ALL, mappedBy = "TheObject", fetch = FetchType.EAGER)

        public void setName(String name) {
            this.name = name;
        }

        public String getName(Long id) {
            return this.name;
        }

        public TheObject (String name) {
            this.name = name;
        }

    The data access object

public TheObjectDAO(SessionFactory factory) {
        super(factory);
    }

    public List<TheObject> findAll() {

        return list(namedQuery("com.comapny.TheObject.findAll"));
    }

    public TheObject create(TheObject o) {
        return persist(o);

    }
}

The Application class

    public class TheApplication extends Application<AppConfiguration> {
    private final static Logger log = Logger.getLogger(DeployerApplication.class.getName());

    private final HibernateBundle<AppConfiguration> hibernate = new HibernateBundle<AppConfiguration>(
        TheObject.class) {

        public DataSourceFactory getDataSourceFactory(
                AppConfiguration configuration) {
            return configuration.getDataSourceFactory();
        }

    };
    @Override
    public void run(AppConfiguration configuration, Environment environment) throws SQLException {

        final TheObjectDAO dao = new   TheObjectDAO(hibernate.getSessionFactory());
    environment.jersey().register(new TheObjectResource(dao));

 And finally the resource class

    public ObjectResource(TheObjectDAO edao) {
        this.dao = dao;
    }

    @GET
    @Timed
    @UnitOfWork
    public List<TheObject> getAllObjss() {
        return dao.findAll();

    }

When I tru to get this resource I always get the error "Named Query not known". What have I missed

A: Got it, had the namedQuery syntax wrong. IT should have been
       @NamedQueries({
           @NamedQuery(
                  name = "",
                  query = ""
          )
  })


text:
Q: Force close when new fragment with async task is launched I have a button that loads a new fragment but it is force closing with this error:
java.lang.NullPointerException
        at com.beerportfolio.beerportfoliopro.BPTopTastes.onCreateView(BPTopTastes.java:29)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:158)
        at android.app.ActivityThread.main(ActivityThread.java:5789)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
        at dalvik.system.NativeStart.main(Native Method)

the button that loads the new fragment is this:
public class Discover extends Fragment {
    Fragment Fragment_one;
    Fragment Fragment_two;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_discover, container, false);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        //add button onclick fo top beers
        Button bt = (Button)v.findViewById(R.id.discoverBeers);
        bt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // do whatever stuff you wanna do here
                FragmentManager man=getFragmentManager();
                FragmentTransaction tran=man.beginTransaction();
                Fragment_one=new BPTopBeers();
                tran.replace(R.id.main, Fragment_one);//tran.
                tran.addToBackStack(null);
                tran.commit();
            }
        });

        //todo: add button onclick fo top tastes
        Button bt2 = (Button)v.findViewById(R.id.discoverTaste);
        bt2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // do whatever stuff you wanna do here
                FragmentManager man=getFragmentManager();
                FragmentTransaction tran=man.beginTransaction();
                Fragment_two=new BPTopTastes();
                tran.replace(R.id.main, Fragment_two);//tran.
                tran.addToBackStack(null);
                tran.commit();
            }
        });

        // Inflate the layout for this fragment
        //todo: change to discover layout
        return v;

    }

the fragment that is being launched is:
public class BPTopTastes extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.taste_statistics_layout, container, false);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        String title = "Top Tastes on Beer Portfolio";
        TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
        topTitle.setText(title);

        //construct url
        String url = "myURL";

        //async task goes here
        new GetTasteStatisticsJSON(getActivity()).execute(url);

        // Inflate the layout for this fragment
        return v;

    }

}

and the async task which is being called is:
public class GetTasteStatisticsJSON extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;

    public GetTasteStatisticsJSON(Context context)
    {
        c = context;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting  tastes");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);

            //acces listview
            ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourTasteStatistics);

            //make array list for beer
            final List<TasteInfo> tasteList = new ArrayList<TasteInfo>();

            for(int i = 0; i < jsonArray.length(); i++) {

                String style = jsonArray.getJSONObject(i).getString("taste");
                String rate = jsonArray.getJSONObject(i).getString("rate");

                int count = i + 1;

                style = count + ". " + style;

                Log.d("brewery stats", style);

                //create object
                TasteInfo tempTaste = new TasteInfo(style, rate);

                //add to arraylist
                tasteList.add(tempTaste);

                //add items to listview
                TasteInfoAdapter adapter1 = new TasteInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
                lv.setAdapter(adapter1);

                //set up clicks
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        TasteInfo o=(TasteInfo)arg0.getItemAtPosition(arg2);

                        String tempTaste = o.taste;

                        //todo: load taste page fragment
                        //Intent myIntent = new Intent(c, TastePage.class);
                       // myIntent.putExtra("taste", tempTaste);
                        //c.startActivity(myIntent);

                    }
                });

            }

        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

I am a bit confused cause I have another button in the same fragment that launches a new fragment in a similar way just fine...

A: I just noticed my mistake after combing through my code. I have the wrong id here in this line:
 TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);

so it could not find that, to set the title.

A: Can you check the BPTopTastes layout is inflating correctly, and hence topTitle is not null when you call the setText() method on it.
Does it work when you remove the async task ?
The Eclipse debugger can be set to halt on exception which might give you some pointers.


text:
Q: Regular Expression to avoid matching starting tags My intend is that I need to match HTML tags that has some freemarker square brackets tags inside the tag.
Examples:

or
See logo

so far I have this regex (<)([a-z][a-z0-9]*)[\s\S]+(\[\#[a-z][\s\S]*\])[\s\S]+([^>]+?\/>|>(.*?)(<\/\2>)) which you can test on the following link with a good example
http://regex101.com/r/iZ7qQ5
As you can see, it is "fairly" working, but it is matching some extra tags html and body in the beginning.
I want to negate the finding of any other opening tags before the freemarker tag with a negative lookahead ((?![<][a-z][a-z0-9]*)) but it didn't work.

A: Your problem is with the [\s\S]+ part. This part is equivalent to match everything, since \S means everything that is not \s... under this pattern, all tags can be captured, as well as free text, etc.
I'm not sure this regex is exactly what you need, but it should put you in the right direction:
(<)([a-z][a-z0-9]*)[^>]+(\[\#[a-z][^\]]*\])[^>]+([^>]+?\/>|>(.*?)(<\/\2>))


text:
Q: Phase delay in a thin lens? Let the maximum thickness of a lens (on its axis) be $\Delta_0$, and let the thickness at coordinates $(x,y)$ be $\Delta(x,y)$.
I have read that phase delay suffered by the wave at coordinates $(x,y)$ in passing through a thin lens may be written as
$$
\phi(x,y) = kn \Delta(x,y) + k(\Delta_0 - \Delta(x,y)),
$$
where $n$ is the refractive index of the lens material, $kn\Delta(x,y)$ is the phase delay introduced by the lens, and $k(\Delta_0 - \Delta(x,y)$ is the phase delay introduced by the remaining region of free space between the two planes. Equivalently the lens may be represented by a multiplicative phase transformation of the form
$$
t_l = e^{jk\Delta_0} e^{jk(n-1)\Delta(x,y)}.
$$
No explanation is provided for where these expression comes from. So why is it that the first expression represents the phase delay in thin lens, and what can the phase transformation function $t_l$ be used for in applications?

A: The phase delay that you have found is $\phi = kn \Delta(x,y) + k(\Delta_0 - \Delta(x,y)) = k\Delta_0 + k(n-1)\Delta(x,y)$
Suppose you started with a wave of the form $\cos(\omega t)$ after passing through the lens it becomes $\cos(\omega t + \phi)$.
Using complex numbers such a transformation is made easier.
Assume that the incoming wave is the real part of $e^{j\omega t}$ then the outgoing wave is the real part of $e^{j(\omega t+\phi)} = e^{j\phi} e^{j\omega t}$ and what is $e^{j\phi}$?
It is $e^{j(k\Delta_0 + k(n-1)\Delta(x,y))} = e^{jk\Delta_0} e^{k(n-1)\Delta(x,y)}$ your multiplicative phase transformation.

A: Basically, for a simple monochromatic wave, the phase is given by
$\phi= \omega t - k x + \varphi_0$. Let's ignore the last term by just start counting when it is 0. So the phase is $\omega t - k x$, (or its opposite).
For two waves like that, $\omega$ is the same and the time elapsed is the same. Consequently, the value of $\omega t$ is the same in both waves and that causes no difference. What makes both waves different? The other term: $k x$.
In other words, the delay is $\Delta \phi = \Delta(\omega t - kx) = \stackrel{=0}{\overbrace{\Delta (\omega t)}}-\Delta (kx)\rightarrow\Delta (kx)$
But k is $2\pi/\lambda$, and $\lambda$ varies in different media. But we can use $k_0$ as the $k$ in vacuum (with wavelenght in vaccum). The relation is simple:
$k=n\cdot k_0$
because  $k=\omega/v = \omega / (c/n) = \omega/c \cdot n = k_0\cdot n $.
Then, we can take $k_0$ as common factor outside (in your book, it seems that they use $k$ as $k_0$, but be careful that it refers to the one in vaccuum).
In sum, only the Optical path length $(n\cdot x)$ causes the delay. In your book it is $n\cdot \Delta$. Check that, for air, $n=1$ and it doesn't appear, but it is there! haha.

A: The expression is using the paraxial approximation, i.e. that rays are all propagating within a small angular range. In that case, the distance any ray propagates through the lens is, to a good approximation, simply the thickness $\Delta(x,\,y)$ of the lens, measured along the $z$ direction. The true thickness varies roughly like $\Delta(x,\,y)\,\cos\theta$, where $\theta$ is the angle between the ray and the $z$ axis - the geometry is a bit more complicated in general than this, but the $\cos\theta$ variation is correct up to second order. And, of course, $\cos\theta\approx 1$ to first order.
Given the above paraxial approximations, the calculation runs as follows. The path followed by a ray at transverse position $(x,\,y)$ in reaching the plane $z=\Delta_0$ comprises a thickness $\Delta(x,\,y)$ of lens material, and the complement is a thickness $\Delta_0-\Delta(x,\,y)$ of air. The total phase delay is thus $k\,(\Delta_0-\Delta(x,\,y))$ for the path through air and $k\,n\,(\Delta_0-\Delta(x,\,y))$ for the path through the lens. The sum is the expression you are given. As in the other answers, phase delay $\phi$ corresponds, in phasor notation, to scaling by the unity magnitude quantity $e^{i\,\phi}$, which will yield the second expression.

A: The situation is that there is an incoming light wave that is transmitted through a lens. The thickness of the lens is chosen in the z-direction and the cross section of the lens is in the x,y-plane. A plane is defined at one edge of the lens at $z = z_1$ and another plane is defined at the other edge of the lens at $z = z_2$. We want to know the phase difference of the light between the moments that the light enters the plane at $z=z_1$ and the moment the light leaves the plane at $z = z_2$. In general the light will travel partly in the vacuum and partly in the medium of the lens. If the light would be incident exactly at $\Delta_0$ there would only be travel in the lens medium, but in all other situations part of the light path will be in the vacuum and the other part will be in the lens medium. The total difference in phase is equal to the contribution caused by the part in the lens plus the contribution caused by the part in the vacuum.
Let's assume the incoming light can be written as an amplitude function times an exponential, so: $A(r)e^{ikr}$. The phase has to do with the complex exponential, namely $kr$.
Let's make the discussion a bit general and let some light travel a distance between two planes. The electric and magnetic fields of the light oscillate with a period $T$ and a angular frequency $\omega$. The light has a certain wave length $\lambda$. If you look a the light at position $x = x_0$ and a position $x = x_0 + \lambda$ you don't see a difference due to the periodicity of the light. So, if the light travels a certain distance $r$ you need to subtract the wave length $\lambda$ as many times as you can and the difference that is left at the end is interesting for the difference in phase.
Let the light enter the first plane at position $r_1$ with a light phase $\phi_1$ and let the light hit the second plane at position $r_2$ with a light phase $\phi_2$. Then $mod(|r_2 - r_1|, \lambda)$ is the fraction of the period we need to shift. Also $\phi$ is just a number in the interval $\left[0, 2 \pi \right)$. The phase at position 2 is $\phi_2 = \phi_1 + mod(|r_2 - r_1|, \lambda) \cdot 2 \pi $. Thus: $\phi_2 - \phi_1 = mod(|r_2 - r_1|, \lambda) \cdot 2 \pi$. Let's put the phase in a complex exponential, because that is the formula for the light. $ e^{i(\phi_2 - \phi_1)} = e^{i( mod(|r_2 - r_1|, \lambda) \cdot 2 \pi)}$. The right hand side can be rewritten using the periodicity of the complex exponential. $ e^{i(\phi_2 - \phi_1)} = e^{i( (|r_2 - r_1|/ \lambda )\cdot 2 \pi)}$.
When light enters a medium with a different optical density, such as a lens, the wave length changes but not the frequency. $\lambda_{medium} = \lambda_{vacuum}/n$. The $\lambda$ used in the previous paragraph is $\lambda_{medium}$, so you can replace that $\lambda$ in the previous paragraph with $\lambda_{vacuum}/n$. In the formula's $k$ is the wave vector in vacuum.
The definition of the wave vector: $k = 2 \pi / \lambda_{vacuum}$ leads to  $e^{i (\phi_2-\phi_1)} = e^{i k n |r_2 - r_1|}$. What we know now is that when you let some light of the form $A(r)e^{ikr}$  travel a distance $|r_2 - r_1|$ you can multiply with $e^{i k n|r_2 - r_1|}$ to get the correct phase. Let's call this factor $t$. So $t = e^{i k n|r_2 - r_1|}$.
Back to our set-up. The total distance between the two planes $z_2-z_1 = \Delta_0$. Distance travelled through the lens is $\Delta(x,y)$ and the distance travelled through the vacuum is $\Delta_0 - \Delta(x,y)$. $t$ is the factor we need to multiply our light formula with to get the correct phase after the light has travelled through the two planes.
In the vacuum $n=1$. $t$-factor due to vacuum part: $e^{i k \cdot 1 \cdot distance} = e^{i k \cdot (\Delta_0 - \Delta(x,y))}$.
$t$-factor due to lens part: $e^{i k n \cdot distance} = e^{i k n \cdot \Delta(x,y)}$
Total t-factor is: t = $e^{i k n \cdot \Delta(x,y)} \cdot e^{i k \cdot (\Delta_0 - \Delta(x,y))}$
$$t = e^{i k \Delta_0} e^{i k (n-1) \Delta(x,y)}$$
The resulting formula neglects the fact that the light actually bents due to the lens. We assumed that light travelled in a straight line when we said that the distance the light travels in the vacuum is equal to $\Delta_0 - \Delta(x,y)$ and the distance the light travels in the lens is equal to $\Delta(x,y)$. Because the light rays actually bent, the distances are an underestimation and the phase shift is in reality larger. The approximation becomes exact in the limit of an infinitely thin lens.
An application I can think of is that you can make a computer program to calculate interference patterns. For example define a lens with a certain $\Delta(x,y)$. Then calculate the phase difference for light rays incident at different coordinates $(x, y, z_1)$. Based on the phase differences you can work out what the interference pattern looks like for a lens with a certain $\Delta(x,y)$ function.
In practice, I think the phase of the light is only important in applications where interference plays a role. So you might want to use the formula to make an estimation of a phase shift and compare it with a different phase.


text:
Q: How to pass database adapter to another activity? I'm having some trouble understanding the search dialog in the Android SDK.
The "main activity" of my application provides a button. If the user clicks this button the search dialog is called. The search itself is then done in an async task as it might need some time. So far so good.
The main activity also creates a database adapter object which is used to initialize the database, perform queries, etc. But how can I use this adapter object in the searchable activity?
MAIN activity
// Init database
DatabaseAdapter dba = new DatabaseAdapter();
dba.init();
// open search dialog
if (buttonClick) onSearchRequest();
Searchable activity

*

*Get intent and receive query from search dialog -> OK

*How can I use the database adapter again to perform a query?
Do I have to create a new object? Can I pass it somehow from the min activity to the searchable activity, [...]?
Thanks,
Robert

A: You can create adapter in Application class, and retreieve it in all your activities. That's what I do for my projects.
public class ApplicationClass extends Application {

    Adapter adapter.

    @Override
    public void onCreate(){
    adapter=new Adapter();
        super.onCreate();
    }

    public Adapter getAdapter(){
        return adapter;
    }

}

Then call from Activity:
Adapter adapter=(ApplicationClass)getApplication().getAdapter();

Something like that. ApplicationClass is for your app name. Could be MyAppNameApplication You should create it in your package and then declare in AndroidManifest.xml

A: An option would be to use a singleton and provide access to the DatabaseAdapter via a static method. Ex:
private static DatabaseAdapter sWritableAdapter = null;
private static DatabaseAdapter sReadableAdapter = null;

public static DatabaseAdapter openForReading(Context ctx) {
    if(sReadableAdapter == null)
    sReadableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getReadableDatabase());

    return sReadableAdapter;

}

or for write access:
public static DatabaseAdapter openForWriting(Context ctx) {
if(sWritableAdapter == null)
        sWritableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getWritableDatabase());

    return sWritableAdapter;

}

So in your searchable activity you would write for instance:
DatabaseAdapter adapter = DatabaseAdapter.openForReading(ctx);
adapter.searchSomething();

Marco

A: You should rather implement an ContentProvider
http://developer.android.com/guide/topics/providers/content-providers.html
They are singletons, and accessible from (almost) everywhere in your application.


text:
Q: _this.showModal is not a function because of ref in reactjs I'm opening otp modal component in login register page by using ref. I have created ref this.otpModalRef = React.createRef(); in constructor and calling this.showModal in register api success but it giving undefined below is my code. If I removed this.otpModalRef = React.createRef(); from constructor then modal works but when I click on login then it gives onOpenModal undefined. So I have to createRef in constructor. Any idea why is happening? I'm new to reactjs
below is my code
    static contextTypes = {
    router: PropTypes.object
  }
constructor(props,context){
    super(props,context);
    this.state = {
        fname:'',
        lname:'',
        emailaddress:'',
        password:'',
        mobile:'',
        user:'',
        login_pass:''
    }
    this.regi_data = this.regi_data.bind(this);
    this.login_data = this.login_data.bind(this);
    this.otpModalRef = React.createRef();
}

regi_data(e){
    this.setState({[e.target.name] : e.target.value}
    );
}
login_data(e){
    this.setState({[e.target.name] : e.target.value})
}

otpModalRef = ({onOpenModal}) => {
   this.showModal = onOpenModal;
}

componentDidMount(){

}

login = (e) => {
    e.preventDefault();
     axios.post('/api/signin', {
                    user:this.state.user,
                    password:this.state.login_pass,
                })
      .then(res => {
            console.log(res);
            this.context.router.history.push({
                    pathname:'/',
                });

      })
      .catch(function (error) {
        console.log(error.message);
      })
}

register = (e,ref) => {
    e.preventDefault();
    axios.post('/api/user/add', {
                    firstname: this.state.fname,
                    lastname:this.state.lname,
                    email:this.state.emailaddress,
                    password:this.state.password,
                    mobile:this.state.mobile
                },
            )
      .then(res => {
            console.log(res);
            this.showModal();

      })
}

Below is render code
    render(){
    return(

Log in

Register

                            <form onSubmit={this.login} className="kr-formtheme kr-formlogin">
                                <fieldset>

                                        <input value={this.state.user} onChange={this.login_data} type="text" name="user" className="form-control" placeholder="Username Or Email"/>

                                        <input value={this.state.login_pass}onChange={this.login_data}  type="password" name="login_pass" className="form-control" placeholder="Password"/>

                                            <input type="checkbox" name="remember" id="rememberpass2"/>
                                            Remember me

                                        Lost your Password?

                                    <button className="kr-btn kr-btngreen" >login</button>
                                </fieldset>
                            </form>

                            <form onSubmit={this.register} className="kr-formtheme kr-formlogin">
                                <fieldset>

                                        <input type="text" onChange={this.regi_data} value={this.state.fname} name="fname" className="form-control" placeholder="Firstname"/>

                                        <input type="text" onChange={this.regi_data} value={this.state.lname} name="lname" className="form-control" placeholder="Lastname"/>

                                        <input type="email" onChange={this.regi_data} value={this.state.emailaddress} name="emailaddress" className="form-control" placeholder="Email Address"/>

                                        <input type="password" onChange={this.regi_data} value={this.state.password}  name="password" className="form-control" placeholder="Password"/>

                                        <input type="number" onChange={this.regi_data} value={this.state.mobile} name="mobile" className="form-control" placeholder="Mobile"/>

                                    <button className="kr-btn kr-btngreen">Register</button>
                                </fieldset>
                            </form>

or

Sign in With...

Facebook

Twitter

Google +

                    <Otp ref={this.otpModalRef} ></Otp>

    )
}

A: First point is that below code overwrites your created ref in your constructor.

otpModalRef = ({onOpenModal}) => {
   this.showModal = onOpenModal;
}
second point is that you need to define  this.showModal = null in your constructor.
could you provide render function and JSX code please?
I hope it helps you a bit to change your implementation.

A:

  static contextTypes = {
    router: PropTypes.object
  }

constructor(props,context){
    super(props,context);
    this.state = {
        fname:'',
        lname:'',
        emailaddress:'',
        password:'',
        mobile:'',
        user:'',
        login_pass:''
    }
    this.otpModalRef = React.createRef();
}

regi_data = (e) => {
    this.setState({[e.target.name] : e.target.value}
    );
}
login_data = (e) => {
    this.setState({[e.target.name] : e.target.value})
}

showModal = () => {
   this.otpModalRef.onOpenModal();
   //or
   //this.otpModalRef.current.onOpenModal();
}

login = (e) => {
    e.preventDefault();
     axios.post('/api/signin', {
                    user:this.state.user,
                    password:this.state.login_pass,
                })
      .then(res => {
            console.log(res);
            this.context.router.history.push({
                    pathname:'/',
                });

      })
      .catch(function (error) {
        console.log(error.message);
      })
}

register = (e,ref) => {
    e.preventDefault();
    axios.post('/api/user/add', {
                    firstname: this.state.fname,
                    lastname:this.state.lname,
                    email:this.state.emailaddress,
                    password:this.state.password,
                    mobile:this.state.mobile
                },
            )
      .then(res => {
            console.log(res);
            this.showModal();
      })
}
 render(){
    return(

Log in

Register

                            <form onSubmit={this.login} className="kr-formtheme kr-formlogin">
                                <fieldset>

                                        <input value={this.state.user} onChange={this.login_data} type="text" name="user" className="form-control" placeholder="Username Or Email"/>

                                        <input value={this.state.login_pass}onChange={this.login_data}  type="password" name="login_pass" className="form-control" placeholder="Password"/>

                                            <input type="checkbox" name="remember" id="rememberpass2"/>
                                            Remember me

                                        Lost your Password?

                                    <button className="kr-btn kr-btngreen" >login</button>
                                </fieldset>
                            </form>

                            <form className="kr-formtheme kr-formlogin">
                                <fieldset>

                                        <input type="text" onChange={this.regi_data} value={this.state.fname} name="fname" className="form-control" placeholder="Firstname"/>

                                        <input type="text" onChange={this.regi_data} value={this.state.lname} name="lname" className="form-control" placeholder="Lastname"/>

                                        <input type="email" onChange={this.regi_data} value={this.state.emailaddress} name="emailaddress" className="form-control" placeholder="Email Address"/>

                                        <input type="password" onChange={this.regi_data} value={this.state.password}  name="password" className="form-control" placeholder="Password"/>

                                        <input type="number" onChange={this.regi_data} value={this.state.mobile} name="mobile" className="form-control" placeholder="Mobile"/>

                                    <button onClick={this.register} className="kr-btn kr-btngreen">Register</button>
                                </fieldset>
                            </form>

or

Sign in With...

Facebook

Twitter

Google +

                    <Otp ref={this.otpModalRef} ></Otp>

    )
}

    router: PropTypes.object
  }

constructor(props,context){
    super(props,context);
    this.state = {
        fname:'',
        lname:'',
        emailaddress:'',
        password:'',
        mobile:'',
        user:'',
        login_pass:''
    }
    this.otpModalRef = React.createRef();
}

regi_data = (e) => {
    this.setState({[e.target.name] : e.target.value}
    );
}
login_data = (e) => {
    this.setState({[e.target.name] : e.target.value})
}

showModal = () => {
   this.otpModalRef.onOpenModal();
   //or
   //this.otpModalRef.current.onOpenModal();
}

login = (e) => {
    e.preventDefault();
     axios.post('/api/signin', {
                    user:this.state.user,
                    password:this.state.login_pass,
                })
      .then(res => {
            console.log(res);
            this.context.router.history.push({
                    pathname:'/',
                });

      })
      .catch(function (error) {
        console.log(error.message);
      })
}

register = (e,ref) => {
    e.preventDefault();
    axios.post('/api/user/add', {
                    firstname: this.state.fname,
                    lastname:this.state.lname,
                    email:this.state.emailaddress,
                    password:this.state.password,
                    mobile:this.state.mobile
                },
            )
      .then(res => {
            console.log(res);
            this.showModal();
      })
}


text:
Q: Which permission should be added to add contact? I am trying to add a new contact in android phone.
For that I am using following code.
ContentValues values = new ContentValues();
                values.put(Phone.RAW_CONTACT_ID, "jadeja");
                values.put(Phone.NUMBER, 1234567890);
                values.put(Phone.TYPE, Phone.TYPE_MOBILE);
                Uri uri = getContentResolver().insert(Phone.CONTENT_URI, values);

But it force closes the application and inside "LogCat" it shows that security permission denial.
Is there any way to achieve this?

A: Add the following to the AndroidManifest.XML file:
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>

A: This should be added in manifest
WRITE_CONTACTS

A: Add these permissions in android Maifest.xml file:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />


text:
Q: In a UID namespace, can I setuid to an unmapped UID? Suppose I'm user ID 1000. I run a program inside a UID namespace, mapping UID 0 inside the namespace to UID 1000 outside the namespace. The program then attempts to change its own UID to 50, which doesn't have a corresponding UID outside the namespace.
Does the program successfully change its own (kernel) UID? If so, what does its UID appear to be from outside the namespace? Is it still 1000, or is it something else?

A: You need to define the translations after you've forked.
An excerpt from a fine article at LWN.net: "System calls that return process user and group IDs — for example, getuid() and getgid() — always return credentials as they appear inside the user namespace in which the calling process resides. If a user ID has no mapping inside the namespace, then system calls that return user IDs return the value defined in the file /proc/sys/kernel/overflowuid, which on a standard system defaults to the value 65534. Initially, a user namespace has no user ID mapping, so all user IDs inside the namespace map to this value. Likewise, a new user namespace has no mappings for group IDs, and all unmapped group IDs map to /proc/sys/kernel/overflowgid (which has the same default as overflowuid)."
Basically, once you've clone(2)'d off your progeny, you'll have the child's PID and be able to add to the tables in /proc/CHILDPID/uid-map and /proc/CHILDPID/gid-map to begin defining the translations.
As I understand the situation, if you run seteuid(50) inside your new namespace without a translation for it, you'll find that your euid is still 65534 until the translation is defined. As above, if there is no matching translation, overflowuid/overflowgid will be substituted.
The LWN.net article that explains most of the situation brilliantly is here: http://lwn.net/Articles/532593/

A: I (finally) tested it in Fedora Rawhide. It looks like my initial impression is correct: if you run seteuid(50) inside a namespace, but uid 50 inside the namespace doesn't correspond to a uid outside the namespace, then the call to seteuid simply fails.
In here, I'll use "kernel uid" to refer to a process's uid as seen by the kernel (and most processes outside of the user namespace), and "subjective uid" to refer to a process's uid as seen by itself (and other processes inside the namespace).
Test 1
First, let's see what happens when root calls seteuid(50). We open up Python, and see what its pid is:
[fedora@ip-0-0-0-0 ~]$ sudo python
Python 2.7.6 (default, Feb  4 2014, 15:36:52)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getpid()
1081

In a second terminal, we can see that python's kernel uid is, in fact, 0 (root):
[fedora@ip-0-0-0-0 ~]$ ls -ld /proc/1081
dr-xr-xr-x. 9 root root 0 Feb  7 03:27 /proc/1081

And the subjective uid is, of course, 0 as well:
>>> os.geteuid()
0

So now we change our uid to 50:
>>> os.seteuid(50)

In the second terminal, we see that the kernel uid has indeed changed to 50:
[fedora@ip-0-0-0-0 ~]$ ls -ld /proc/1081
dr-xr-xr-x. 9 50 root 0 Feb  7 03:27 /proc/1081

Test 2
Okay, now let's use "unshare" to create a new user namespace.
[fedora@ip-0-0-0-0 ~]$ unshare --user python
Python 2.7.6 (default, Feb  4 2014, 15:36:52)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getpid()
1084

In the second terminal, we see that this process's kernel uid is 1000 (fedora):
[fedora@ip-0-0-0-0 ~]$ ls -ld /proc/1084
dr-xr-xr-x. 9 fedora fedora 0 Feb  7 03:30 /proc/1084

But in the first terminal, we see that its subjective uid is 65534 (not mapped):
>>> os.geteuid()
65534

So, in the second terminal, we give python a mapping:
[fedora@ip-0-0-0-0 ~]$ echo '0 1000 1' > /proc/1084/uid_map

In the first terminal, we see that python's subjective uid is now 0:
>>> os.geteuid()
0

We try to set python's uid to 50, but this fails with "Invalid argument" (presumably EINVAL), because the subjective uid 50 has no mapping to a kernel uid:
>>> os.seteuid(50)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

In the second terminal, we see that the process's kernel uid is unchanged:
[fedora@ip-0-0-0-0 ~]$ ls -ld /proc/1084
dr-xr-xr-x. 9 fedora fedora 0 Feb  7 03:30 /proc/1084

And in the first terminal, we see that the process's subjective uid is unchanged, too:
>>> os.geteuid()
0

Test 3
Okay, what happens if we define a mapping containing multiple uids? According to the LWN.net article "Namespaces in operation, part 5: User namespaces", we need to run python after mapping the uids. (I tried this without mapping the uids before running python, and the seteuid operation gave "Operation not permitted".) So first, we run a shell in a second new user namespace:
[fedora@ip-0-0-0-0 ~]$ unshare --user
id: cannot find name for user ID 65534
id: cannot find name for group ID 65534
id: cannot find name for user ID 65534
[I have no name!@ip-10-239-133-144 ~]$ echo $$
1798

Then, in the second terminal, we need to be root in order to define the mapping:
[root@ip-10-239-133-144 fedora]# echo '0 1000 2' > /proc/1798/uid_map

According to the whoami command, our subjective uid is root now, so let's open up Python and set our subjective uid to 1:
[I have no name!@ip-0-0-0-0 ~]$ whoami
root
[I have no name!@ip-0-0-0-0 ~]$ python
Python 2.7.6 (default, Feb  4 2014, 15:36:52)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.seteuid(1)
>>> os.getpid()
1837

In the second terminal, we see that our kernel uid is now 1001, as expected:
[root@ip-10-239-133-144 fedora]# ls -ld /proc/1837
dr-xr-xr-x. 9 1001 fedora 0 Feb  7 04:00 /proc/1837

Test 2 again?
In test 3, we needed to define the mapping before running Python in order for the call to seteuid() to succeed. In test 2, we didn't do this. So, the obvious question is, if we did define the mapping before running Python, would the call to seteuid() work? It turns out that the answer is no. First terminal:
[fedora@ip-0-0-0-0 ~]$ unshare --user
id: cannot find name for user ID 65534
id: cannot find name for group ID 65534
id: cannot find name for user ID 65534
[I have no name!@ip-0-0-0-0 ~]$ echo $$
1861

Second terminal:
[fedora@ip-0-0-0-0 ~]$ echo '0 1000 1' > /proc/1861/uid_map

First terminal:
[I have no name!@ip-0-0-0-0 ~]$ whoami
root
[I have no name!@ip-0-0-0-0 ~]$ python
Python 2.7.6 (default, Feb  4 2014, 15:36:52)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.geteuid()
0
>>> os.seteuid(50)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

Conclusion
In order for a call to seteuid within a user namespace to succeed, the uid passed to seteuid must have a mapping outside the user namespace. Otherwise, the call will fail with EINVAL.


text:
Q: Im running asset_path ('') within prawn and getting no getting my assets on deploy Im currently trying to use a custom font on a PDF Prawn document created on Ruby on Rails 4.0.13. I is important to note that I'm also using Cloudfront as a CDN for my assets.
To use my font, on production, I'm using:
font = asset_path ('font.ttf')

I did have to hack my path for my development environment and do this for development:
font = "#{Rails.root}/app/assets#{font_path('/fonts/font.ttf')}"

The interesting thing is that the error that I get is that:
No such file or directory @ rb_sysopen - //d3dlqweqee7.cloudfront.net/assets/FuturaLT-Light-a645a904861503731c3f3fb31c31109bd57c3e82447eac95ca81525374e6f05ac3e.ttf

And the asset is actually there EXCEPT i'm not getting the "https:" protocol.
As you can see:
MISING: "https:" then the rest of the string URL is perfect: "//d3dlqweqee7.cloudfront.net/assets/FuturaLT-Light-a645a904861503731c3f3fb31c31109bd57c3e82447eac95ca81525374e6f05ac3e.ttf"
If I could just add https to that string in my production environment, everything would be perfect.
Any ideas what's going on?

A: Use asset_url. Basically it just calls asset_path but adds { protocol: :request } to the options parameter.
When options[:protocol] is set to :request it will use the URI scheme to construct the URL that was used in the request.


text:
Q: Database Design (Quotation & Invoicing) I have a database question.
I have a database structured something like this:
Quotation, Quotation_line_item
When I convert the quotation to an invoice, is where im stuck wondering:
Should i make tables as such
Invoice, Invoice_line_item
Or should the Invoice just refer to the quotation line items?
Anyone with some experience can maybe help me with some advice on what would be best?
I know that if you change the Quotation the Invoice will change too - but when generating an invoice we are going to be locking the quotation for editing.
What would you recommend?
Thanks,
Jason

A: When an entity goes through processing which results in differing states, those states should be maintained in a separate table. The line items don't seem to be a problem. Have you designed the quotation line items such that the latest ones (assuming you keep previous versions as history) become invoice line items when the quotation becomes an invoice? That is easily done since it doesn't appear there is any actual difference between the two -- only context distinguishes them.
So you would have the QuoteInvoice table, the state table with an FK to the first table and the line items table also with an FK to the first table, a line number and a date (if you keep versions) for when the version became effective.


text:
Q: What's importance of finite state machines (FSM) with respect to embedded systems implementation? I was studying a project that involves  implementation  of a digitally controlled bridgeless power factor correction (BL PFC) converter. It uses PWM to drive the gate driver of the MOSFET switch and an ADC to sense V and I  for voltage and control loop of the control system.
General Reference
I also found they've implemented a finite state machine for the entire system (in CCS .c file.)
Why was a FSM implemented? Is it standard practice in industry to implement a FSM for a project?
Can you give example of FSM implementation on a simple embedded system application?

A: A FSM is a structured method of constructing a sequential machine. The machine can only exist in a fixed number of discrete states - ie 'finite state'.
FSMs can be formally proven for correctness.
Other benefits are that they are easy to construct in code and debug. Going from a state diagram to writing code is a straightforward process.
Traffic lights are a common application used to demonstrate FSMs. There are zillions of examples on the web.
A microprocessor is another example of a FSM albeit somewhat more complex.

A: When using a micro controller to implement a control mechanism like you describe, most programmers would intuitively build/program sort of a state machine anyway.
You do a specific thing at a time (state) and switch (transition) to a different behavior (next state) depending on external information.
There are code frameworks that can help to implement state machines in a clean way. That can be helpful if you have a high number of states with lots of state information and complex transitions.
But for very simple state machines, it is often enough to have a switch case reflecting states and some helper functions to manage transitions.

A: I couldn't find the code: But what's the alternative?
When you have steps (states) to run though an FSM is the best and obvious solution. It's easy to draw diagrams for. An enumeration type for the states is a quick and obvious list of possible states. It generally results in easy to read and maintain code (just a switch case statement). It's also low in memory and runtime requirements (just one variable for the state and a jump instruction).
The other option would be a loose collection of status bits/variables and if statements. Sometimes as code grows you start introducing such status bits. This is a good moment to pause and evaluate if an FSM wouldn't be a cleaner and better way to implement your code.
I'm a digital design engineer, FSMs are our bread and butter. At least for RTL code the linting and code coverage tools usually "understand" FSMs and can provide helpful insights (e.g. state transitions which are not covered).

A: Here's the way I see it.
If the output of a system is determined by its current inputs, you can form a truth table and that truth table can be done by a logic tree (if..if..else....)
If some history is involved, the system has to have memory. And then, the output depends on current inputs and the values in memory.
If there is not just one output but multiple things have to happen depending on inputs and historical conditions, now you need a way to name each resulting condition depending on the trail(s) that can lead to that condition. You need to be able to name them so that you can reason about what should happen on further inputs in such conditions.
To make it possible for multiple people to talk about such systems, you need a paradigm. A way of looking at a system as a set of these conditions we talked about  and the events that cause movement between these conditions, along with any other actions that happen along with the movement.
That paradigm is a state machine. State machines can have different states (conditions in the previous paragraph), events/signals (inputs) and transitions between states, along with possible actions on exit of a state, entry of a state, transition, etc.
Then we have UML having state charts, tools to generate code from visual state charts, check for dead-end states, impossible states, etc.
Essentially, FSMs give a new language for thought about systems and for expression of such thought. Something more than just code can do.
I tried to give you a justification that FSMs are a natural outcome !


text:
Q: Read string block as multiple variables ubuntu I have a script to copy permissions which works fine, being the interesting line this one:
...
bash commands.sh $PAM_USER "medium" /bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed} /usr/bin/{vim,touch,java,python,gcc,awk,make}
...

commands.sh has a loop which reads through all permissions listed and copies them to a specified directory.
Problem comes when I try to do the same thing reading the permissions from a config file.
My config file contains the following:
MEDIUM_PERMISSIONS_BIN=/bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed}
MEDIUM_PERMISSIONS_USR_BIN=/usr/bin/{vim,touch,java,python,gcc,awk,make}
MEDIUM_ENVIROMENT_LIFESPAN=midnight
MEDIUM_PERSISTENT_HOME=true

Note: the last two configurations are for something different, for now I'm trying to read the first two lines properly.
I add the config file to the previous script and try to execute the following:
source /etc/users/config.cfg
...
 bash commands.sh $PAM_USER "medium" $MEDIUM_PERMISSIONS_BIN $MEDIUM_PERMISSIONS_USR_BIN
...

The problem is that the loop reads it as such:
loop: /bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed}
loop: /usr/bin/{vim,touch,java,python,gcc,awk,make}

when previously it used to read it as /bin/ls, /bin/rm, /bin/rm and so on, hence the loop working with the first version as it is able to find those commands, but not on the second version sisnce the output specified previously is incorrect.
I've read through the sed and awk commands but I'm quite new to this and can't get them to work.
How can I read the permissions from my config file as if I was introducing them directly like in the first version?
Thanks
edit: commands.sh code:
#!/bin/bash

CHROOT="/users/$2/$1"
if [ ! -d "$CHROOT/home/$1" ]; then
    mkdir -p "$CHROOT/home/$1"
fi

for i in $( ldd $* | grep -v dynamic | cut -d " " -f 3 | sed 's/://' | sort | uniq )
do
    cp -v --parents $i $CHROOT
done

#ARCH amd64
if [ -f /lib64/ld-linux-x86-64.so.2 ]; then
    cp --parents /lib64/ld-linux-x86-64.so.2 /$CHROOT
fi

#ARCH i386
if [ -f /lib/ld-linux.so.2 ]; then
    cp --parents /lib/ld-linux.so.2 /$CHROOT
fi

clear
cd

Comment: I removed all the debugging echoes. This code is pretty much a copy from a code you can find here: https://linuxconfig.org/how-to-automatically-chroot-jail-selected-ssh-user-logins

A: You are trying to define an array variable but are using the format for a string:
## This will define a string variable
$ MEDIUM_PERMISSIONS_BIN=/bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed}
$ echo $MEDIUM_PERMISSIONS_BIN
/bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed}

## The parentheses tell the shell this is an array
$ MEDIUM_PERMISSIONS_BIN=(/bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed})
$ echo $MEDIUM_PERMISSIONS_BIN  ## the 1st element of the array
/bin/ls
$ echo ${MEDIUM_PERMISSIONS_BIN[@]} ## the entire array
/bin/ls /bin/rm /bin/bash /bin/nano /bin/mkdir /bin/kill /bin/ln /bin/ps /bin/grep /bin/sed

So just change your config file to:
MEDIUM_PERMISSIONS_BIN=(/bin/{ls,rm,bash,nano,mkdir,kill,ln,ps,grep,sed})
MEDIUM_PERMISSIONS_USR_BIN=(/usr/bin/{vim,touch,java,python,gcc,awk,make})
MEDIUM_ENVIROMENT_LIFESPAN=midnight
MEDIUM_PERSISTENT_HOME=true

And then, in your script, use "${MEDIUM_PERMISSIONS_BIN[@]}".


text:
Q: Problem with height adjustment of an  : scrollHeight returns 0 I'm working on a mailbox, i get a mail from a HTTP request and try to display it in a iframe, because it can be a plain text or HTML email.
There is no problem to display the content but i'm not able to adjust the height to that content. I always get a 0 from contentWindow.document.body.scrollHeight.
I tried to see if it comes from the fact that the mail could be in plain text, but it's the same thing for an html email.
I know that the content is displayed because i manually edited the page to change the height and show the content. The only problem right now is the auto adjustment of this height.
By the way, the iframe.contentWindow.document.body is an [Object HTMLBodyElement]
$scope.iFrameDisplayMail = function (Mail_content) {

    var iframe = document.getElementById('mail-display');
    if (Mail_content.html != null) {
      iframe.contentWindow.document.write(Mail_content.html);
    } else {
      iframe.contentWindow.document.write(Mail_content.plain);
    }
    iframe.style.width = 'auto';
    alert(iframe.contentWindow.document.body.scrollHeight);
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
    iframe.contentWindow.document.close();
}

There is no error in the console about this.

A: Based on your example, you can use:
var iframe = document.getElementById('mail-display');
var scrollHeight = iframe.ownerDocument.body.scrollHeight;

A: I also had this problem and found this question while researching how to fix it. In case it might help someone else, here's how I got it to work:
TLDR: Try adding an empty  tag to the HTML content of the Email you want to display in the iFrame if it doesn't have one.
I set the HTML content for the iFrame using iFrame.contentWindow.document.write("Html-Content-From-Received-Email"). As for you, this content would be displayed (if I changed the height manually when troubleshooting), but the iFrame.contentWindow.document.body.scrollHeight returns 0, so I can't set my height correctly programmatically.
What I found is that this problem only occurred for HTML content that does not have a  tag - which is common for E-Mails, eg. sent from Thunderbird. When I added an empty  tag to the E-Mail-content I received (otherwise exactly the same), the correct scrollHeight was returned. So, for example, this E-Mail content would not work (scrollHeight=0):

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

Das ist ein Test.

Das ist ein Test.

Das ist ein Test.

But when I add the  tag, it would work correctly and the correct scrollHeight would be returned:

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

Das ist ein Test.

Das ist ein Test.

Das ist ein Test.

I am not a web expert, so I can't explain why exactly this works, but it cost me quite some time to fix this issue and I hope the solution that worked for me also helps someone else.


text:
Q: Treat an UIPickerView like a combo/select box I'm working with XCode 8.2.1, Swift 3 and iOS10.
I've a list of items with the following format:
ID | Name
---------
1 | John
2 | Maria
3 | Peter
4 | Roger

The code looks like this:
var formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]

What I want to do is to set that data into an UIPickerView, so when someone chooses for example John, the ID 1 is returned, or if someone chooses Peter, the ID 3 is returned.
I do other stuff once I get that ID, that's why I need it.
Any idea or suggestion on how I can achieve this?
Thanks!

A: Your approach of using a dictionary of your data structure is problematic. Dictionaries are, by design, unordered.
There are lots of ways to do this. Most involve creating an array of some sort containing items for each entry from which you want the user to pick.
For example, create an array of tuples:
typealias NameTuple = (id: Int, name: String)

var namesArray: [NameTuple]

Feed your picker view with the name field of each entry in your array. When the user selects an item, use the selected index to fetch that tuple and then get the ID.
You could also use an array of structs, or an array of name objects.

A: You just need to sort your dictionary by its keys and use it as your picker data source:
let formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]
let dataSource = formsList.sorted{$0.key<$1.key}

This way you have all your dictionary names sorted in an array including their IDs. Your picker should look something like this:
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var label: UILabel!
    let formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]
    var dataSource: [(key: Int, value: String)] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource = formsList.sorted{$0.key<$1.key}
        pickerView.delegate = self
        pickerView.dataSource = self
        label.text = "id: " + String(dataSource[pickerView.selectedRow(inComponent: 0)].key) + " - " + "name: " + dataSource[pickerView.selectedRow(inComponent: 0)].value
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return dataSource.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return dataSource[row].value
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        label.text = "id: " + String(dataSource[row].key) + " - " + "name: " + dataSource[row].value
    }
}

sample


text:
Q: How to make es6 import/export works in Nightwatch test? I want to import into my test file utility module, which is written in ES6 and exports several things I need.  So what I do is
import { module } from 'file'

but it throws the 'SyntaxError: Unexpected token import' error.
I tried to:

*

*add require('babel-core/register') to the top of the nightwatch.conf.js

*add require('babel-register')() to the top of the nightwatch.conf.js

*npm i babel-plugin-add-module-exports --save-dev ,  and add "add-module-exports" plugin to the .babelrc config file

*npm i babel-preset-es2015 --save-dev , and add es2015 preset to the .babelrc config file

*add
require('babel-core')
require('babel-loader')
require('babel-plugin-add-module-exports')
require('babel-polyfill')
require('babel-preset-stage-2')
require('babel-preset-es2015')

to the top of the nightwatch.conf.js
All this didn't help. What should I do to make import/export works?

A: Appears I was very close, the one thing missed from my attention:
I had
"presets": [
    ["es2015", { "modules": false }]
  ],

and { "modules": false } was the blocking thing. So, to make import/export works  you need:
1 At the top of nightwatch.config
require('babel-register')() // or require('babel-core/register')

2 .babelrc should contain
{
  "presets": ["es2015"],
  "plugins": [
    "add-module-exports",
  ]
}

3 install babel
npm i babel-plugin-add-module-exports babel-core babel-preset-es2015 --save-dev