text:
Q: Unable to instantiate class in 2 different Class library projects i have created 2  Class  library projects in one solution , named  Fundamentls and Fundamentals.test inside Fundamentls  i have  class Greeter
namespace Fundamentals
{
    public  class Greeter
    {
        public string SayHello()
        {
            return "Hello" ;
        }
    }
}

now when in  Fundamentals.test i try to do this
using Fundamentals;
namespace Fundamentals.Test
{
    [TestFixture]
    public class GreeterTest
    {
        [Test]
        public void SayHelloReturnsHello()
        {
            Greeter g = new Greeter();
        }
    }
}

now this is what i get

i have  build the project after adding namespace but still does not work ,

A: Adding a using directive is not enough, first you need to add a reference to your assembly from your test project.Then include the namespace (optional) or use the fully-qualified name of the type.
You can refer to this documentation if you don't know how to add a reference to a different assembly from your project:

*

*How to: Add or Remove References By Using the Add Reference Dialog Box

A: It looks like the Fundamentals.Test project needs to refer to the Fundamentals project.
Just right click on the References node of the Fundamentals.Test project and select Add Reference from the right click menu.

A: If they are two different project then you will have to include the dll in other project. have you done that?
I mean have you, added the reference of the fundamentals project to fundamentals.test by clicking on reference folder and then click add reference. You can directly select the dll from projects tab.


text:
Q: How do "scroll journey" webpages work I'm sorry if this has been asked previously, I really wasn't sure how to word this question. Here's one popular example, and another of what I mean, where when the user scrolls down the page and the page itself actually pans over a scene in a fixed path that needn't be the direction of the scroll at all.
How do these sites work?

A: While you could write all this code yourself, I'd suggest you use the amazing jQuery Scroll Path.
Read the documentaion. It's pretty straightforward.

Here's a quote:

The plugin uses canvas flavored syntax for drawing paths, using the methods moveTo, lineTo and arc. To help with getting the path right, a canvas overlay with the path can be enabled when initializing the plugin.
Scrolling can be done with the mousewheel, up/down arrow keys and spacebar. The spacebar scrolls faster than the arrow keys, and holding shift while pressing space will scroll backwards. A custom scrollbar is also included, which allows click and drag scrolling. The scrollbar is enabled by default.
The plugin also allows rotating the entire page, using CSS transforms. This can be done either along a path, or around the current position. In browsers without CSS transform support, all rotations are ignored, but paths are still followed. This means the plugin works with graceful degradation in all browsers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 404 error when using getJSON Hi guys having some trouble here trying to reuse some code here giving to by the owner of the web site . I have a load and save function the save function works fine now but not the load , I keep getting a 404 error even tho the file is there i tried renaming the file , clear cache ect .. Any ideas
$('#btnLoad').click(function(evt) {
  //    empty the list
  $('#selCaseStudies').find('option').remove();

  //    populate the list of case studies
  $.getJSON("dbs/gcsl.php", function(data) {
    $.each(data, function(key, value) {
      //alert(key + ":" + value);
      $('#selCaseStudies').append("<option value='" + key + "'>" + value[1] + "-" + value[2] + "</option>");
    });
  });

  //    show the dialog
  $('#dlgLoad').dialog({
    buttons: {
      "Ok": function() {
        $(this).dialog("close");
        var csd = {};
        csid = $('#selCaseStudies').val();
        //csid = prompt("casestudyid", "1");
        loadCaseStudy(csid);
      },
      "Cancel": function() {
        $(this).dialog("close");
      }
    }
  });

  //    don't call the home button handler
  evt.stopPropagation();
});


text:
Q: Instanciar variáveis tipadas no construtor via reflectionClass Estou desenvolvendo uma aplicação com URL's amigáveis e chegou um momento em que não consigo achar saída.
Tenho o seguinte:
$constructParams = [];

$reflectionClass = new \ReflectionClass($controller);

$construct = $reflectionClass->getConstructor();

if (isset ( $construct ) ){

    foreach( $construct->getParameters() as $parameter){

        $class = $parameter->getClass();

        $constructParams[$parameter->name] = $class
                                                ? new $class->name
                                                : $parameter->name;

    }

}

$instance = $reflectionClass->newInstanceArgs($constructParams);

Esse código instancia uma classe e popula seu construtor.
Minha dificuldade é que, se algum parâmetro do construtor (caso ele tenha algum) for um objeto de uma classe, o problema será sanado por:
$parameter->getClass();

no entanto, se esse parâmetro (que sempre será tipado), for um int, bool, float ou outa coisa, não consigo determinar seu tipo.
Exemplo:
public function __construct (Classe $classe, int idade)

Já pesquisei de tudo mas nada encontrado!
Em tempo: Se eu não tipo os parâmetros que NÃO são objetos, tudo funciona bem.
Mas o objetivo é tipar.

A: Resposta a quem puder ser útil como foi para mim:
$constructParams = [];

//Fazemos a Reflexão da function da classe
$reflectionClass = new \ReflectionClass($controller);

//pegamos seu construtor caso exista
$construct = $reflectionClass->getConstructor();

if (isset ( $construct ) ){

    if ($construct->getNumberOfParameters() > 0) {

        foreach( $construct->getParameters() as $parameter){

            $type = $parameter->getType();

            if ($type == null) {

                $parameter->name;

            } else {

                $type = $type->getName();

                switch($type) {
                    case 'bool':
                        $type = (bool) $parameter->name;
                    break;
                    case 'int':
                        $type = (int) $parameter->name;
                    break;
                    case 'float':
                        $type =  (float) $parameter->name;
                    break;
                    case 'string':
                        $type =  (string) $parameter->name;
                    break;
                    case 'array':
                        $type =  (array) $parameter->name;
                    break;
                    default :
                        $type =  $parameter->name;
                    break;
                }

            }

            $class = $parameter->getClass();

            //instanciamos o objeto no Parâmetro que, obviamente for um bjeto
            //o que não for objeto, apenas repassamos o tipo
            $constructParams[$parameter->name] = $class
                                                    ? new $class->name
                                                    : $type;


text:
Q: late assignment and lazy type checking in typescript intersected types Recently I saw a code like this (in order to have some kind of namespacing):
function f0() {
  return "string";
}

function f1() {
  return 4;
}

type F0 = typeof f0;
type F1 = typeof f1;

const first: F0 & { f1: F1 } = function() {
  return "sample";
};

first.f1 = f1;

the interesting point is that if we remove the first.f1 = f1 line, the typescript compiler gives an error for f1 variable and says

Type '() => string' is not assignable to type '(() => string) & { f1: () => number; }'.

It seems that type checking happens it two steps and it is kind of a lazy type checking!
My question is that how is this possible?
It is more interesting when we cannot do this with object based types. For instance in the following code, it type checking system raises error as expected
const second: { n1: number } & { n2: number } = { n1: 10 };
second.n2 = 8;

Can anyone elaborate what's the reason for this behaviour? (You can see and run the above code here too : https://codesandbox.io/s/react-playground-9chzq)


text:
Q: Canceling checkbox's click event prevents checking it? I need to have a list of checkboxes with the condition that at least one of them must be checked.
The following code produces that effect.

document.querySelector('div').addEventListener('click', function(evt){
    if( this.querySelectorAll('input:checked').length == 0 )
        evt.preventDefault() ;
}) ;
<div>
    <input type=checkbox checked>
    <input type=checkbox>
    <input type=checkbox>
</div>

That's fine, however, I don't understand why this code even works.
Firstly, I'm doing a .preventDefault() on the click event only after I've checked the condition that says there are no checkboxes checked. So canceling the click event at this point should make no difference.
Secondly, the code works even if you try to check the checkboxes using the keyboard, which is totally weird because I'm only canceling the click event.
Please explain why the code works the way it does.

A: While an input event listener is running, its effect on the element's state is actually already performed. If event.preventDefault() is called, this change is undone when the listener returns. This allows a checkbox event handler to test the new state of the checkbox, and allows the handler for a keyboard event on a text input to test the value that includes the new input.
The reason it works when you use the keyboard is that the click event is a high-level event that encompasses all the different ways to click on a checkbox: you can do it with the mouse, with they keyboard, with a touchscreen, etc. If you want to listen to a specific mode of clicking, you would have to use mousedown, keypress, etc.


text:
Q: How do I write the code to this simple statement in C? I have a linked list of nodes which have two integers an up and down value, I want to make a loop that checks each node after the first, and checks to see if the up and down values are the same on any of the other ones. I just do not know the function names in C to do this, is there a length of method, or is there a way I can just say while the next node is not null? I figured it has to be something like this, but sorry ahead of time, this is the second time I have ever looked at C in my life. This is kind of pseudocode of what I need, can anyone point me in the right direction or give me any tips?
while(nextNode != null)
{
  if(currentNodes.up == nextNodes.up && currentNodes.down== nextNodes.down):
  {
    return true;
  }
  else
  {
    return false;
  }
 }

A: You'll also need  some form of updates to the current and next nodes.
For example let's say you have this node:
struct node;
struct node {
    int up;
    int down;
    struct node *next;
};

And then you main code:
/*
* 0 implies false (no clashes) and 1 implies true (clash found).
* Assuming headNode points to the first node in the list.
*/
int checkStuff(struct node *headNode) {
    if(headNode == NULL) {
        return 0;
        //Or return 1 depending on how you want to handle this corner case.
    }
    struct node *nextNode = headNode->next;
    while(nextNode != NULL) {
        if(headNode->up == nextNode->up && headNode->down == nextNode->down) {
            return 1;
        }
        nextNode = nextNode->next;
    }
    return 0;
}

This would currently just compare currentNode with all following nodes; you'll need to rework your loop if you're looking for something else.


text:
Q: Running own's php script upon pressin Paypal buy-now button and thanks for the great help your community provides.
Here is a question regarding Paypal. The code below creates a buy-now non-hosted button. I would like to be able to do run my geoTestArray.php code, currently simply included, as the user presses the Buy Now button, and not when the button is displayed on the page.
Is this possible at all?
Thanks in advance,
Joe
<?php
include ('geoTestArray.php');
echo "<form action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\">
<input type=\"hidden\" name=\"business\" value=\"shop@mysite.com\">
<input type=\"hidden\" name=\"cmd\" value=\"$cmd\">
<input type=\"hidden\" name=\"amount\" value=\"$price\">
<input type=\"hidden\" name=\"shipping\" value=\"$shipping\">
<input type=\"hidden\" name=\"currency_code\" value=\"$currency\">
<input type=\"hidden\" name=\"shipto\" value=\"$shipto\">
<input type=\"hidden\" name=\"item_name\" value=\"$title\">";
if ($cmd == 'cart') {
echo "<input type=\"hidden\" name=\"add\" value=\"1\">";
}
include('./quantities2.php');
echo "<input type=\"hidden\" name=\"lc\" value=\"US\">
<input class=\"submit\" type=\"image\" src=\"$button\" border=\"0\" name=\"submit\" alt=\"$altaction\">
<img alt=\"\" border=\"0\" src=\"https://www.paypal.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">
</form>";
?>

A: You can display only a form with one input, for example item_id.
After submitting this form you search for item details, execute your geoTestArray.php in backend and after that you can redirect your users to paypal using header("location: $query");
here's how I would do:
<?php
if( isset($_POST['do_action']) && $_POST['do_action'] != "" ) {
    //check for non-empty item_id field
    //run your geoTestArray.php script
    //get item details from database and build your paypal query
    $query = "https://www.paypal.com/cgi-bin/webscr&cmd=_xclick";  // add rest of paypal request fields separated by &
    header( "Location: $query" );
}
?>
<form action='' method='post'>
    <input type='hidden' name='item_id' value'your_item_id'>
    <input type='submit' name='do_action' value='Buy'>
<form>

Hope I helped you! :d

A: Thanks everyone for comments and solution options. I have eventually chosen to modify an onSubmit javascript I had on my page, by adding:
function InterceptForm(formObj) {
  var newshipto = httpGet('geoTestArray.php');
  formObj.shipto.value =  newshipto;
}

The above code makes use of the httpGet() function posted in this other stackoverflow post:
HTTP GET request in JavaScript?
To complete the puzzle:
The code below is in the html in my page
<script language="javascript">
// During onLoad, loop through all forms and for each form object do something
function InterceptForm(formobj) {
    formobj.onsubmit = function ff() {
        interceptform(formobj);
    };
}
</script>

The code below gathers all forms on the page and runs the above javascript on each (NOTE: you may want to name your forms so that you only run the script on the relevant forms and not on all forms):
<script language="javascript">
function GetForms() {
var formsCollection = document.getElementsByTagName("form");
for(var i=0;i<formsCollection.length;i++)
{
   if (formsCollection[i].name != "seecart")
   {
   InterceptForm(formsCollection[i]);
   }
}
        return true;
}
</script>

The code below is the onLoad function:
<script language="javascript">
function onLoadFunction () {
  GetForms();
  return true;
}
</script>

Cheers,
Joe


text:
Q: Adding JScrollPane in Netbeans visual editor I have designed a window using Netbean's visual editor. Now, I have a JTextField, which I want to add using a Scroll bar. How can I do that?

A: Use JTextArea and put this into a JScrollPane. If you are using the visual editor it will be done by default (dropping the TextArea into your Window). The JScrollPane has two properties: horizontalScrollBarPolicy and verticalScrollBarPolicy. Set this two properties to ALWAYS and you will see the Scroll bars.

A: You should not add Scollbar to a TextField.TextField is meant for inputting small entries from the user like name,age,roll number,etc.The best component to input large sized texts ,like comments, from user is JTextArea.So You must add JTextArea instead of JTextField.
After adding JTextArea to the JFrame,you can write few lines of code:-
JScrollPane jsc=new JScrollPane();
jsc.add(jta);

where 'jta' is the name of your JTextArea which your Netbeans have generated for you.
(Now ,when you add text greater than the limit size of text Area ,the scrollbars will appear.
If you want the scrollbars appear permanently,then,the JScrollPane has two properties: horizontalScrollBarPolicy and verticalScrollBarPolicy. Set this two properties to ALWAYS and you will see the Scroll bars always irrespective the size of text in JTextArea.)
Here is the complete code to demonstrate you  what you can do:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class TextAreaDemo
{
JTextArea jta;
TextAreaDemo()
{
JFrame jfrm=new JFrame("Text Area");
jfrm.setSize(200,300);
jfrm.getContentPane().setLayout(new FlowLayout());
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jta=new JTextArea("Type Here");

//You can use this line to wrap that text when it extends on right side.
//jtxt.setLineWrap(true);

JScrollPane jscrp=new JScrollPane(jta);
jscrp.setPreferredSize(new Dimension(180,100));
jscrp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

jfrm.add(jscrp);
jfrm.setVisible(true);

}

public static void main(String args[])
{
 SwingUtilities.invokeLater(new Runnable(){public void run(){new TextAreaDemo();}});
}
}


text:
Q: nonlinear integral equation I have a non-linear integral equation that I'd like to solve with Mathematica:

g[y_] := y^2;
h[y_] := y^2/2 + c;
func=(g[y] f[y]/Sqrt[h[y]^2 + f[y]^2]);

A: You should take the derivative with respect to $x$ of both sides. Then you obtain the differential equation
$$ f'(x) = \frac{g(x) f(x)}{\sqrt{h(x)^2+f(x)^2}}$$ and $f(0)=0$.
The latter can be solved using
g[x_] := x^2;
h[x_] := x^2/2 + c;
DSolve[{f'[x] == g[x] f[x]/Sqrt[h[x]^2 + f[x]^2], f[0]==0}, f[x], x]

It turns out that Mathematica is not able to solve the resulting differential equation.
Looking at the numerical solution (setting a value for $c$ and replacing DSolve by NDSolve), I believe that the (only) solution to your problem is
$$ f(x) \equiv 0.$$


text:
Q: Flushdns and registerdns on multiple machine by powershell Simple question but not able to find answer on google at the moment. My powershell version is 2. I want to flush and registerdns on multiple machines.
ipconfig /flushDns

ipconfig /registerdns

I can't use invoke command and psremoting is not enabled on machines.
Any advise how to flushdns & registerdns.

A: It's pretty easy with Invoke-wmimethod
Create a list of your computers in a file named servers.txt, then create a script like this :
$listofservers = Get-Content .\servers.txt

foreach ($servers in $listofservers) {

Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /flushdns") -ComputerName $servers

Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /registerdns") -ComputerName $servers

}

By default you'll not get the output of the command, but you'll only get information if the command sucessfully ran on remote computer through this value :
ReturnValue

If this value equal to 0 that means the command was sucessfully executed on the remote server.
If you want to get the command output, you can achieve it but adding output redirection to txt file :
$listofservers = Get-Content .\servers.txt

foreach ($servers in $listofservers) {

Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /flushdns > c:\flushdnsresult.txt") -ComputerName $servers

Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /registerdns > c:\registerdnsresult.txt") -ComputerName $servers

}

Then you'll find a txt file on your remote server containing the result output of cmd command.

A: If you upgrade your powershell version from 2 (highly recommended - I have a powershell & dotnet update script to do this also) you can use:
# Get Windows servers on Domain
####################
$serversraw=Get-ADComputer -Filter {(OperatingSystem -like "*windows*")}

# Filter responsive
####################
$serversup = $serversraw.name | where {Test-Connection $_ -quiet -count 1}

# Flush DNS & reregister
####################
Clear-DnsClientCache -cimsession $serversup
Register-DnsClientCache -cimsession $serversup


text:
Q: KeyError in wxpython to start up GrassRaPlaT class MapFrameBase(wx.Frame):
    """!Base class for map display window
Derived class must use statusbarManager or override
GetProperty, SetProperty and HasProperty methods.
If derived class enables and disables auto-rendering,
it should override IsAutoRendered method.
"""
def __init__(self, parent = None, id = wx.ID_ANY, title = None,
             style = wx.DEFAULT_FRAME_STYLE, toolbars = None,
             Map = None, auimgr = None, name = None, **kwargs):
    """!
    @param toolbars array of activated toolbars, e.g. ['map', 'digit']
    @param Map instance of render.Map
    @param auimgs AUI manager
    @param name frame name
    @param kwargs wx.Frame attributes
    """

    self.Map        = Map       # instance of render.Map
    self.parent     = parent

    wx.Frame.__init__(self, parent, id, title, style = style, name = name, **kwargs)

    # available cursors
    self.cursors = {
        # default: cross
        # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
        "default" : wx.StockCursor(wx.CURSOR_ARROW),
        "cross"   : wx.StockCursor(wx.CURSOR_CROSS),
        "hand"    : wx.StockCursor(wx.CURSOR_HAND),
        "pencil"  : wx.StockCursor(wx.CURSOR_PENCIL),
        "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
        }

    #
    # set the size & system icon
    #
    self.SetClientSize(self.GetSize())
    self.iconsize = (16, 16)

    self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))

    # toolbars
    self.toolbars = {}

    #
    # Fancy gui
    #
    self._mgr = wx.aui.AuiManager(self)

def _initMap(self, map):
    """!Initialize map display, set dimensions and map region
    """
    if not grass.find_program('g.region', ['--help']):
        sys.exit(_("GRASS module '%s' not found. Unable to start map "
                   "display window.") % 'g.region')

    self.width, self.height = self.GetClientSize()

    Debug.msg(2, "MapFrame._initMap():")
    map.ChangeMapSize(self.GetClientSize())
    map.region = map.GetRegion() # g.region -upgc
    # self.Map.SetRegion() # adjust region to match display window

def SetProperty(self, name, value):
    """!Sets property"""
    self.statusbarManager.SetProperty(name, value)

def GetProperty(self, name):
    """!Returns property"""
    return self.statusbarManager.GetProperty(name)

def HasProperty(self, name):
    """!Checks whether object has property"""
    return self.statusbarManager.HasProperty(name)

def GetPPM(self):
    """! Get pixel per meter

    @todo now computed every time, is it necessary?
    @todo enable user to specify ppm (and store it in UserSettings)
    """
    # TODO: need to be fixed...
    ### screen X region problem
    ### user should specify ppm
    dc = wx.ScreenDC()
    dpSizePx = wx.DisplaySize()   # display size in pixels
    dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
    dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
    sysPpi  = dc.GetPPI()
    comPpi = (dpSizePx[0] / dpSizeIn[0],
              dpSizePx[1] / dpSizeIn[1])

    ppi = comPpi                  # pixel per inch
    ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
                (ppi[1] / 2.54) * 100)

    Debug.msg(4, "MapFrameBase.GetPPM(): size: px=%d,%d mm=%f,%f "
              "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
              (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
               dpSizeIn[0], dpSizeIn[1],
               sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
               ppm[0], ppm[1]))

    return ppm

def SetMapScale(self, value, map = None):
    """! Set current map scale

    @param value scale value (n if scale is 1:n)
    @param map Map instance (if none self.Map is used)
    """
    if not map:
        map = self.Map

    region = self.Map.region
    dEW = value * (region['cols'] / self.GetPPM()[0])
    dNS = value * (region['rows'] / self.GetPPM()[1])
    region['n'] = region['center_northing'] + dNS / 2.
    region['s'] = region['center_northing'] - dNS / 2.
    region['w'] = region['center_easting']  - dEW / 2.
    region['e'] = region['center_easting']  + dEW / 2.

    # add to zoom history
    self.GetWindow().ZoomHistory(region['n'], region['s'],
                               region['e'], region['w'])

def GetMapScale(self, map = None):
    """! Get current map scale

    @param map Map instance (if none self.Map is used)
    """
    if not map:
        map = self.Map

    region = map.region
    ppm = self.GetPPM()

    heightCm = region['rows'] / ppm[1] * 100
    widthCm  = region['cols'] / ppm[0] * 100

    Debug.msg(4, "MapFrame.GetMapScale(): width_cm=%f, height_cm=%f" %
              (widthCm, heightCm))

    xscale = (region['e'] - region['w']) / (region['cols'] / ppm[0])
    yscale = (region['n'] - region['s']) / (region['rows'] / ppm[1])
    scale = (xscale + yscale) / 2.

    Debug.msg(3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" % \
                  (xscale, yscale, scale))

    return scale

def GetProgressBar(self):
    """!Returns progress bar

    Progress bar can be used by other classes.
    """
    return self.statusbarManager.GetProgressBar()

def GetMap(self):
    """!Returns current Map instance
    """
    return self.Map

def GetWindow(self):
    """!Get map window"""
    return self.MapWindow

def GetMapToolbar(self):
   """!Returns toolbar with zooming tools"""
   raise NotImplementedError()

def GetToolbar(self, name):
    """!Returns toolbar if exists else None.

    Toolbars dictionary contains currently used toolbars only.
    """
    if name in self.toolbars:
        return self.toolbars[name]

    return None

def StatusbarUpdate(self):
    """!Update statusbar content"""
    self.statusbarManager.Update()

def IsAutoRendered(self):
    """!Check if auto-rendering is enabled"""
    return self.GetProperty('render')

def CoordinatesChanged(self):
    """!Shows current coordinates on statusbar.

    Used in BufferedWindow to report change of map coordinates (under mouse cursor).
    """
    self.statusbarManager.ShowItem('coordinates')

def StatusbarReposition(self):
    """!Reposition items in statusbar"""
    self.statusbarManager.Reposition()

def StatusbarEnableLongHelp(self, enable = True):
    """!Enable/disable toolbars long help"""
    for toolbar in self.toolbars.itervalues():
        toolbar.EnableLongHelp(enable)

def IsStandalone(self):
    """!Check if Map display is standalone"""
    raise NotImplementedError("IsStandalone")

def OnRender(self, event):
    """!Re-render map composition (each map layer)
    """
    raise NotImplementedError("OnRender")

def OnDraw(self, event):
    """!Re-display current map composition
    """
    self.MapWindow.UpdateMap(render = False)

def OnErase(self, event):
    """!Erase the canvas
    """
    self.MapWindow.EraseMap()

def OnZoomIn(self, event):
    """!Zoom in the map.
    Set mouse cursor, zoombox attributes, and zoom direction
    """
    toolbar = self.GetMapToolbar()
    self._switchTool(toolbar, event)

    win = self.GetWindow()
    self._prepareZoom(mapWindow = win, zoomType = 1)

def OnZoomOut(self, event):
    """!Zoom out the map.
    Set mouse cursor, zoombox attributes, and zoom direction
    """
    toolbar = self.GetMapToolbar()
    self._switchTool(toolbar, event)

    win = self.GetWindow()
    self._prepareZoom(mapWindow = win, zoomType = -1)

def _prepareZoom(self, mapWindow, zoomType):
    """!Prepares MapWindow for zoom, toggles toolbar

    @param mapWindow MapWindow to prepare
    @param zoomType 1 for zoom in, -1 for zoom out
    """
    mapWindow.mouse['use'] = "zoom"
    mapWindow.mouse['box'] = "box"
    mapWindow.zoomtype = zoomType
    mapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)

    # change the cursor
    mapWindow.SetCursor(self.cursors["cross"])

def _switchTool(self, toolbar, event):
    """!Helper function to switch tools"""
    if toolbar:
        toolbar.OnTool(event)
        toolbar.action['desc'] = ''

def OnPointer(self, event):
    """!Sets mouse mode to pointer."""
    self.MapWindow.mouse['use'] = 'pointer'

def OnPan(self, event):
    """!Panning, set mouse to drag
    """
    toolbar = self.GetMapToolbar()
    self._switchTool(toolbar, event)

    win = self.GetWindow()
    self._preparePan(mapWindow = win)

def _preparePan(self, mapWindow):
    """!Prepares MapWindow for pan, toggles toolbar

    @param mapWindow MapWindow to prepare
    """
    mapWindow.mouse['use'] = "pan"
    mapWindow.mouse['box'] = "pan"
    mapWindow.zoomtype = 0

    # change the cursor
    mapWindow.SetCursor(self.cursors["hand"])

def OnZoomBack(self, event):
    """!Zoom last (previously stored position)
    """
    self.MapWindow.ZoomBack()

def OnZoomToMap(self, event):
    """!
    Set display extents to match selected raster (including NULLs)
    or vector map.
    """
    self.MapWindow.ZoomToMap(layers = self.Map.GetListOfLayers())

def OnZoomToWind(self, event):
    """!Set display geometry to match computational region
    settings (set with g.region)
    """
    self.MapWindow.ZoomToWind()

def OnZoomToDefault(self, event):
    """!Set display geometry to match default region settings
    """
    self.MapWindow.ZoomToDefault()

When I try to start up GrassRaPlat in command prompt, appears this as follow:
GRASS 6.4.3RC2 (AMC):~ > Traceback (most recent call last):
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/lmgr/frame.py", line 196, in init
    self.NewDisplay(show = False)
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/lmgr/frame.py", line 1463, in NewDisplay
    auimgr = self._auimgr, showMapDisplay = show)
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/lmgr/layertree.py", line 156, in init
    Map = self.Map, auimgr = self.auimgr)
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/mapdisp/frame.py", line 123, in init
    self.statusbarManager.Update()
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/mapdisp/statusbar.py", line 217, in Update
    item.Update()
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/mapdisp/statusbar.py", line 508, in Update
    scale = self.mapFrame.GetMapScale()
  File "/usr/local/src/grass-6.4.3RC2/dist.i686-pc-linux-gnu/etc/wxpython/gui_core/mapdisp.py", line 168, in GetMapScale
    heightCm = region['rows'] / ppm[1] * 100
KeyError: 'rows'
Can you tell me please where is my mistake?
Thank you in advance.


text:
Q: How do I remove part of a string that follows a certain pattern up to, but not including another pattern using R? I have a dataframe in R that contains people data. First part of a string is a full name. Every so often I encounter a nickname in brackets. There could be other data enclosed in brackets that I do not want to delete. Here is an example of a kind of data I am working with:
Name <- c(
    "JOSEPH RYAN SMITH (USRID1)",
    "ANDREA J LOPEZ RAMIREZ (USRID2) (CONTRACTOR)",
    "TIMOTHY (TIM) JOHNSON (USRID3) (INTERN)",
    "JESSICA JENNIFER JONES (USRID4) (CONTRACTOR)",
    "WILLIAM (BILLIE) JOEL (USRID5)")
df <- as.data.frame(Name)

I get:
                                         Name
1                   JOSEPH RYAN SMITH (USRID1)
2 ANDREA J LOPEZ RAMIREZ (USRID2) (CONTRACTOR)
3      TIMOTHY (TIM) JOHNSON (USRID3) (INTERN)
4 JESSICA JENNIFER JONES (USRID4) (CONTRACTOR)
5               WILLIAM (BILLIE) JOEL (USRID5)

I only want to remove nicknames. I noticed that what sets a nickname apart is that it is always in brackets and is always followed by a last name. All other indicators included in brackets are followed by " (" or end of record. I tried to remove a string that is in brackets that is followed by a space and a character A-Z.
df$Name <- str_remove(df$Name, "[\\(][A-Z]+[\\)][ ][A-Z]")

This removed the first letter of the last name and gave me:
 Name
1                   JOSEPH RYAN SMITH (USRID1)
2 ANDREA J LOPEZ RAMIREZ (USRID2) (CONTRACTOR)
3             TIMOTHY OHNSON (USRID3) (INTERN)
4 JESSICA JENNIFER JONES (USRID4) (CONTRACTOR)
5                         WILLIAM OEL (USRID5)

I also unsuccessfully tried "not  followed by (" like this:
df$Name <- str_remove(df$Name, "[\\(][A-Z]+[\\)][ ][^\\(]")

I tried a few other things which removed other indicators that are in brackets that I do need to keep. Any help is appreciated. Thank you.

A: Use positive lookeahd (?=) so that first letter of last name is matched but not removed.
stringr::str_remove(df$Name, "\\([A-Z]+\\)\\s(?=[A-Z])")

#[1] "JOSEPH RYAN SMITH (USRID1)"
#[2] "ANDREA J LOPEZ RAMIREZ (USRID2) (CONTRACTOR)"
#[3] "TIMOTHY JOHNSON (USRID3) (INTERN)"
#[4] "JESSICA JENNIFER JONES (USRID4) (CONTRACTOR)"
#[5] "WILLIAM JOEL (USRID5)"

You can also write this in base R with sub :
sub('\\([A-Z]+\\)\\s(?=[A-Z])', '', df$Name, perl = TRUE)


text:
Q: Edited: How to write Loop for PostHoc Tukey test and multiple comparision This is my sample of a big data matrix & and each column has named with multiple information and separated by an underscore.
structure(list(Gene = c("AGI4120.1_UBQ", "AGI570.1_Acin"), WT_Tissue_0T_1 = c(0.886461437, 1.093164915), WT_Tissue_0T_2 = c(1.075140682, 1.229862834), WT_Tissue_0T_3 = c(0.632903012, 1.094003128), WT_Tissue_1T_1 = c(0.883151274, 1.26322126), WT_Tissue_1T_2 = c(1.005627276, 0.962729188), WT_Tissue_1T_3 = c(0.87123469, 0.968078993), WT_Tissue_3T_1 = c(0.723601456, 0.633890322), WT_Tissue_3T_2 = c(0.392585237, 0.534819363), WT_Tissue_3T_3 = c(0.640185369, 1.021934772), WT_Tissue_5T_1 = c(0.720291294, 0.589244505), WT_Tissue_5T_2 = c(0.362131744, 0.475251717), WT_Tissue_5T_3 = c(0.549486925, 0.618177919), mut1_Tissue_0T_1 = c(1.464415756, 1.130533457), mut1_Tissue_0T_2 = c(1.01489573, 1.114915728), mut1_Tissue_0T_3 = c(1.171797418, 1.399956009), mut1_Tissue_1T_1 = c(0.927507448, 1.231911575), mut1_Tissue_1T_2 = c(1.089705396, 1.256782289 ), mut1_Tissue_1T_3 = c(0.993048659, 0.999044465), mut1_Tissue_3T_1 = c(1.000993049, 1.103486794), mut1_Tissue_3T_2 = c(1.062562066, 0.883617224 ), mut1_Tissue_3T_3 = c(1.037404833, 0.851875438), mut1_Tissue_5T_1 = c(0.730883813, 0.437440083), mut1_Tissue_5T_2 = c(0.480635551, 0.298762126 ), mut1_Tissue_5T_3 = c(0.85468388, 0.614923997)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list( cols = list(Gene = structure(list(), class = c("collector_character", "collector")), WT_Tissue_0T_1 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_0T_2 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_0T_3 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_1T_1 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_1T_2 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_1T_3 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_3T_1 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_3T_2 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_3T_3 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_5T_1 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_5T_2 = structure(list(), class = c("collector_double", "collector")), WT_Tissue_5T_3 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_0T_1 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_0T_2 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_0T_3 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_1T_1 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_1T_2 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_1T_3 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_3T_1 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_3T_2 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_3T_3 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_5T_1 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_5T_2 = structure(list(), class = c("collector_double", "collector")), mut1_Tissue_5T_3 = structure(list(), class = c("collector_double", "collector"))), default = structure(list(), class = c("collector_guess", "collector"))), class = "col_spec"))

I want to follow a Tukey Test and plot bar charts for each Gene (Response vs. Time; filled by both the genotypes) with multiple comparisons letters.
Syntax
df1 <- df %>%
         gather(var, response, WT_Tissue_0T_1:mut1_Tissue_5T_3) %>%
         separate(var, c("Genotype", "Tissue", "Time"), sep = "_") %>%
         arrange(desc(Gene))
df2 <- df1 %>%
         group_by(`Gene`,Genotype,Tissue,Time) %>%
         mutate(Response=mean(response),n=n(),se=sd(response)/sqrt(n))

Two-way ANOVA
fit1 <- aov(Response ~ Genotype*Time, df2)

Hereafter, I want to go proceed Tukey Test (Multiple Comparison), for e.g. Gene "AGI4120.1_UBQ", plot Response vs. Time, and see how each genotype (WT & mut1) behave in each Time point (0T, 1T, 3T, and 5T)? if the response is significantly different or not and denote by letters in the plot.
As below lsmeans syntax combine all the Genes to one and give output, how can I make it to loop for each gene separately (i.e. "AGI4120.1_UBQ", "AGI570.1_Acin") and get letters to show statistically distinct groups (aka "compact letter display")
 lsmeans(fit1, pairwise ~ Genotype | Time)

My final aim is to plot each gene like this below graph and denote significance letters.
df2$genotype <- factor(df2$genotype, levels = c("WT","mut1")) colours <- c('#336600','#ffcc00')library(ggplot2)ggplot(df2,aes( x=Time, y=Response, fill=Genotype))+geom_bar(stat='identity', position='dodge')+scale_fill_manual(values=colours)+geom_errorbar(aes(ymin=average_measure-se, ymax=average_measure+se)+facet_wrap(~`Gene`)+labs(x='Time', y='Response')

Expecting Graph for denoting compact letter display
I would appreciate your kind help, if possible.

A: There are a number of issues with your code.  I'd go so far as to say it's not really an appropriate post for StackOverflow, as the problems here are diverse and not really extendable beyond this specific constellation of bugs and syntax issues.  But I'll post a few suggestions as an answer to get you started - hope they help.
1. lsmeans():
This function expects a fitted model (like from lm()), or a ref.grid object.  But you are passing it a data frame, without any of the regression properties it needs to compute least-squares means.  (Think: How does lsmeans() know what the dependent variable should be, when you ask for pairwise comparison with Genes as the independent variable?)  Check out the Using lsmeans documentation for more details.
Based on your data, I'd say you probably want to run a multi-level regression, using something like the lme4 package, with Gene and Genotype and maybe Time as nested grouping levels.
But for demonstration I'll keep it simple with lm().  Passing a fitted regression object to lsmeans() works as intended:
fit <- lm(Response ~ Gene + Genotype + Time, data=df2)

lsmeans(fit, pairwise ~ Gene)[[2]]

# Output
contrast                        estimate        SE df t.ratio p.value
AGI4120.1_UBQ - AGI570.1_Acin -0.0515123 0.0299492 42   -1.72  0.0928

Results are averaged over the levels of: Genotype, Time

2. ggplot():
You haven't defined colours or average_measure in the code you've provided; calling these undeclared variables will cause failure.
Structurally, I would suggest you use df1 and allow ggplot to do the grouping, rather than group_by into df2.  Then use stat="summary" and fun.y="mean" to accomplish the summarise() computations you did in df2.  Doing this also allows you to use the mean_se function for your error bars.  Like this:
ggplot(df1,aes( x=Time, y=response, fill=Genotype))+
  geom_bar(stat='summary', fun.y='mean', position=position_dodge(0.9))+
    stat_summary(fun.data = mean_se, geom = "errorbar",
                 color="gray60", width=.1, position=position_dodge(0.9)) +
  scale_fill_manual(values=c("steelblue","orange"))+
  facet_wrap(~`Gene`)+
  labs(x='Time', y='Response')

Finally, note that your use of separate() in df1 will throw a warning, although not an error, as there is an extra value created by splitting on sep="_".  You can avoid that (if it is causing confusion) by adding a level to capture the final value (which appears to be a time index):
separate(var, c("Genotype", "Tissue", "Time", "Index"), sep = "_")


text:
Q: How to extract actual timestamp in Cloud Build CI/CD pipeline yaml script or Cloud Build Triggers page I have a cloud_build.yaml script for my CI/CD pipeline on GP using Cloud Build. In command line I can pass a subtitution variable which will include the actual timestamp: "notebook-instance-$(date +%Y-%m-%d-%H-%M)-v05". This is working fine.
When I add github trigger on the Cloud Build webpage, then I didn't find the way to get the timestamp extracted in the same way that I was using in cli $(date +%Y-%m-%d-%H-%M)-v05:

Any idea idea how to do that on the Triggers Cloud Build page ?
I aslo tried to do it inside the cloud_build.yaml script  but without success for now.
- name: 'gcr.io/cloud-builders/gcloud'
  id: Deploy the AI Platform Notebook instance
  args:
  - 'deployment-manager'
  - 'deployments'
  - 'create'
  - '$(date -u +%Y-%m-%d-%H-%M)-${_NAME_INSTANCE}'

Any idea how to extract and create a variable using the actual timestamp in the .yaml CloudBuild script ?
A third option is to extract the timestamp in my .jinja deployment script. Here I get the same issue as well that I don't find the way to to extract the actual timestampt to build my variable name.

A: One of the solution is to do the following:
- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: sh
  args:
  - '-c'
  - |
    gcloud \
    deployment-manager \
    deployments \
    create \
    xxxx

The issue is that you cannot use it in another step later. Another option is is to write te variable in a file on the workspace. This can be access later during the build stackoverflow


text:
Q: Problem in incrementing the filename
Possible Duplicate:
Way to get unique filename if specified filename already exists (.NET)

Have a look at the following code:
Dim counter As Integer = 0
While System.IO.File.Exists("C:\Desktop\Sample.xls")
    counter = counter + 1
    Dim fileName As String = String.Format("{0}({1}){2}",    System.IO.Path.GetFileNameWithoutExtension(newfile), counter.ToString(), System.IO.Path.GetExtension(newfile))
    newfile = System.IO.Path.Combine(ProcessedView.processedPath, fileName)
End While

If the file exists, the new file name will be Sample(1).xls. Up to this point, it is working fine. If the file name itself is Sample(1).xls, the new filename should be Sample(2).xls. But in this code I am getting it as Sample(1)(2).xls.
How to avoid this problem? Any suggestions?

A: On the first pass, in this line:
newfile = System.IO.Path.Combine(ProcessedView.processedPath, fileName)

newfile will be sample(1).xls. Then when you format it with
System.IO.Path.GetFileNameWithoutExtension(newfile)

It will return sample(1) which is {1} in the format string, then in the second pass of the loop you add ({2}) which is 2, and that makes sample(1)(2).
To fix this, you need to not keep adding the (x) to the file name, like so:
        Dim counter As Integer = 0
        Dim origfile As String = "C:\Desktop\Sample.xls"
        Dim newfile As String = origfile
        While System.IO.File.Exists(newfile)
            counter = counter + 1
            newfile = String.Format("{0}({1}){2}", System.IO.Path.GetFileNameWithoutExtension(newfile), counter.ToString(), System.IO.Path.GetExtension(newfile))
        End While

        use newfile instead of origfile

There was another problem in your original code in the line
While System.IO.File.Exists("C:\Desktop\Sample.xls")

Because if C:\Desktop\Sample.xls exists, it will cause an infinite loop.

A: Try this
Dim counter As Integer = 0
Dim tempBaseFile As String = "C:\Desktop\Sample.xls"
Dim newFile As String = tempBaseFile

While System.IO.File.Exists(newFile)
  counter = counter + 1
  Dim fileName As String = String.Format("{0}({1}){2}", System.IO.Path.GetFileNameWithoutExtension(tempBaseFile), counter.ToString(), System.IO.Path.GetExtension(newFile))
  newFile = System.IO.Path.Combine(ProcessedView.processedPath, fileName)
End While

A: please try this
        Dim counter As Integer = 0
        While System.IO.File.Exists("C:\Desktop\Sample.xls")
            counter = counter + 1
            Dim fileName As String = String.Format("{0}({1}){2}",    System.IO.Path.GetFileNameWithoutExtension(Mid(newfile, 1, InStr(newfile, "(") - 1)), counter.ToString(), System.IO.Path.GetExtension(newfile))
            newfile = System.IO.Path.Combine(ProcessedView.processedPath, fileName)
        End While

the reason is because you need to get the filenamewithoutextension WITHOUT the stuff in the parenthesis (###)

A: logic can be :
Dim counter As Integer = 0
Dim testFileName as String = "Sample"
Dim searchFileName as String = testFileName
While System.IO.File.Exists("C:\Desktop\" & searchFileName & ".xls")
   counter = counter + 1
   searchFileName  = testFileName & "(" & counter & ")"
End While

Dim fileName As String = String.Format("{0}({1}){2}",           System.IO.Path.GetFileNameWithoutExtension(newfile), counter.ToString(), System.IO.Path.GetExtension(newfile))
newfile = System.IO.Path.Combine(ProcessedView.processedPath, fileName)

A: you can do this as well:
Dim counter As Integer = 0

Dim newFileName As String = orginialFileName

While File.Exists(newFileName)
    counter = counter + 1
    newFileName = String.Format("{0}({1}", orginialFileName, counter.ToString())
End While


text:
Q: How to check and test how much memory a javascript app is leaking iam looking for some tools or ways to detect memory leaks, slow methods in my javascript app.

A: You need to use the profiler; I recommend Chrome's.  In the profiler the steps are

*

*Go to the profile part of the developer tools

*Get to the part where the slow js is

*Start recording

*Start the suspect code

*Stop recording

After that, the profiler will tell you everything you want to know about how many objects there are, how much time is spent in each method, etc...
The procedure should be similar with Firebug on Firefox.

A: Good question.  Profilers/browser plugins are handy, but very well may yield results unique to the browser being tested on.  There are a number of techniques available from testing via multiple browser's plugins/profilers to inline debugging performance statements.
Two good articles with, robust examples and recommendations:

*

*How do you performance test JavaScript code?

*Memory leak patterns in JavaScript


text:
Q: The Periodic Collatz Conjecture Consider the function
$$f(n)=\begin{cases}n/2&\mbox{if }n\mbox{ is even}\\3n+1&\mbox{otherwise}\end{cases}.$$
Starting from any positive integer $x_0$, we can iterate the sequence $x_1=f(x_0)$, $x_2=f(x_1)$, and so on, with $x_n=f^n(x_0)$. The Collatz conjecture is a famous unsolved problem that claims that the sequence eventually reaches $1$ for any starting value $x_0$.
We can separate the steps of the sequence into "even" and "odd" moves, based on whether $x_n$ is even or odd. This leads us to the following, much easier conjecture:

There is no divergent Collatz sequence such that $x_n\bmod 2$ is periodic.

(This does not rule out the possibility of a nontrivial cycle; here I am talking only about sequences that go to infinity.) Can we show this?

A: Any sequence of parities corresponds to specific composition of the two possible linear transformations, hence to a transformation of the form $n\mapsto \frac{3^an+b}{2^c}$ with non-negative integers $a,b,c$.
For this to produce an integer, it must be the case that $2^c\mid 3^an+b$, i.e., $n$ must be in one specific residue class modulo $2^c$.
As we can consider several periods instead of one, it follows that $n$ must be in a specific residue class modulo $2^{kc}$ for every $k\in\Bbb N$. This means that there can be only one such $n$. But then $\frac{3^an+b}{2^c}$ must be the same number and hence the sequence does not diverge.


text:
Q: Ruby reads .50 as .5 I have an Item class, and I initialized five variables. I am trying to match the output in my terminal to the value of the expected_summary. I am calling Item.summary in the following code:
class Item
  attr_reader :name, :description, :manufacturer, :price, :summary

  def initialize (name, manufacturer, price, description=nil, summary=nil)
    @name = name
    @manufacturer = manufacturer
    @price = price
    @description = description
    if description
      @summary = "Name: #{name}
Description: #{description}
Manufacturer: #{manufacturer}
Price: $#{price}"
    else
      @summary = "Name: #{name}
Manufacturer: #{manufacturer}
Price: $#{price}"
    end
  end
end

#expected_summary = %q(Name: Spy Notebook
#Manufacturer: Spys-R-Us
#Price: $10.50)
item = Item.new("Spy Notebook", "Spys-R-Us", 10.50)
puts item.summary

When I pass a number 10.50 as the price argument, it returns as 10.5. I cannot figure out why. Why does Ruby read 10.50 as 10.5? Is there a way to correct this?

A: The answer is in the string format operator which allows you to coerce the float into a string with 2 decimal places.  This method will also work to do the rounding of 3 digit numbers, I didn't try it any further, but I'm fairly certain it will work. Here is your original code modified to showcase exactly how it would work.
class Item
  attr_reader :name, :description, :manufacturer, :price, :summary

  def initialize (name, manufacturer, price, description=nil, summary=nil)
    @name = name
    @manufacturer = manufacturer
    @price = "%.2f" % price
    @description = description

    if description
      @summary = "Name: #{name}
                  Description: #{description}
                  Manufacturer: #{manufacturer}
                  Price: $#{@price}"
    else
      @summary = "Name: #{name}
                  Manufacturer: #{manufacturer}
                  Price: $#{@price}"
    end
  end

  def price
     @price
  end
end

EDIT: I didn't see @tadman's comment until after posting this, he beat me to the answer.

A: Maybe you can define your custom method to format the number as string with two decimals:
def two_decimals(number)
  number = Float(number)
  price_split = number.to_s.split('.')
  price_split[1] = price_split.last + '0'*(2-price_split.last.size) if price_split.last.size < 2
  price_split.join('.')
end

two_decimals(10.25) #=> "10.25"
two_decimals(10.2) #=> "10.20"
two_decimals(10) #=> "10.00"

Or something better...

A: The usual way of formatting numbers is:
'%.02f' % number

Where that is the printf-style notation for describing how you want something formatted. This is inherited from C and shows up in a lot of other languages:
'%f' % number    # A floating-point number with default precision
'%.02f' % number # A floating-point number rounded to 2 places

Within Rails you also have helper methods like number_with_precision which can handle localization cases where the decimal separator is not a dot:
number_with_precision(number, precision: 2, locale: :fr)
# => 1,50


text:
Q: F# Canopy: Can a test be excluded from the report? I am a beginner in f# canopy UI testing and I have one small problem:
I want to exclude one test from the report. I use LiveHtmlReporter and I do not want this test to be displayed in the final table. Is there a way to do this?


text:
Q: A question about Hom functor in category theory Suppose $\mathcal{C}$ is a category and $f: A \rightarrow B $ is a morphism from an object $A$ to another object $B$ such that $f_*:Hom(C,A) \to Hom(C,B)$ is bijective $\forall C \in ob(\mathcal{C})$. Can it be concluded that $f$ is an equivalence ?
I am able to see that $\exists g: B \to A$ such that $fg=id_B$ but am unable to find an $h$ such that $hf=id_A$.
We can assume that the category is small if it helps.
If it is not true, how can we find a counterexample ? Thanks

A: Yes indeed, you just found the famous Yoneda Lemma (http://en.wikipedia.org/wiki/Yoneda_lemma). Concretely, while you only needed surjectivity of $f_{\ast}$ to deduce the existence of $g: B\to A$ with $fg=\text{id}_B$, you can use injectivity to deduce from $f_{\ast}(gf)=f(gf)=(fg)f=\text{id}_B\ f=f\ \text{id}_A=f_{\ast}(\text{id}_A)$ that $gf=\text{id}_A$ as well, hence $g$ is a two-sided inverse of $f$.
Addendum concerning the relation to the Yoneda Lemma:
The Yoneda-Lemma says that for any category ${\mathscr C}$ the Yoneda-functor $${\mathbb Y}: {\mathscr C}\to\text{Func}({\mathscr C}^{\text{op}},\textsf{Set}), \quad X\mapsto{\mathbb Y}(X) := \text{Hom}_{{\mathscr C}}(-,X)$$ is fully faithful. In particular - as does any fully faithful functor - it reflects isomorphisms.
Now, your assumption is that for all $C\in{\mathscr C}$ the map $f_{\ast}:\text{Hom}_{\mathscr C}(C,X)\to \text{Hom}_{\mathscr C}(C,Y)$ is bijective, which means that the morphism ${\mathbb Y}(f): {\mathbb Y}(X)\to{\mathbb Y}(Y)$ of functors ${\mathscr C}^{\text{op}}\to\textsf{Set}$ is a pointwise isomorphism. However, pointwise isomorphisms of functors are already isomorphisms (check this), so your assumption implies that ${\mathbb Y}(f)$ is an isomorphism, and hence so is $f$.


text:
Q: Symfony 2. Doesn't work usort() guys! I need help. Usort() doesn't work in symfony2 class.
class UserController extends Controller
{   ...
 /**
 * @Route("/dashboard", name="dashboard")
 */

public function dashboard()
{

SQL Query:
    /** @var \MyBundle\Entity\User $user */
    $user = $this->getDoctrine()
        ->getRepository('MyBundle:User')
        ->find($this->getUser()->getId());
    /** @var \MyBundle\Entity\Event[] $events */
    $events = $this->getDoctrine()
        ->getRepository('MyBundle:Event')
        ->findBy(['creator' => $user->getId()]);

Data Arrays:
$allEvents = [];
    foreach ($events as $event) {
        $allEvents[] = $event;
    }
    foreach ($user->getEvents() as $event) {
        $allEvents[] = $event;
    }

Result to twig:
    return $this->render(
        'MyBundle:User:dashboard.html.twig',
        [ 'allEvents' => usort($allEvents, function( $a, $b )
            { if ( $a["schedule"] == $b["schedule"] )
                { return 0; }
                else
                { return ( $a["schedule"] < $b["schedule"] ) ? -1 : 1; }
            }),

code continuation...
What's wrong?

A: As @Rizier123 says, usort() returns a boolean.
So try this:
// First, sort the array
usort($allEvents, function($a, $b) { // $a and $b are instances of MyBundle\Entity\Event
    // this depends on your object, just call the right function
    if ($a->getSchedule() == $b->getSchedule()) {
        return 0;
    }

    return $a->getSchedule() < $b->getSchedule() ? -1 : 1;
});

// Then, use the sorted array in your template
return $this->render('MyBundle:User:dashboard.html.twig', [
    'allEvents' => $allEvents,
]);


text:
Q: Datawarehouse in Hive I have a requirement to make datawarehouse in Hive and use HBase to serve real time access
So I would like to know what would be the architecture for the same
Can I first dump the data on HBase and access it as Rest Service and create external table in Hive and run hive queries on it ?
Will Hive be distributed i.e i need to install Hive on all nodes of my cluster or it it will be central

A: In answer to your questions:
Hive will be distributed.
For best performance, I would consider installing Hive on every node of the cluster. Hive translates HiveQL into MapReduce jobs - the jobs will be performed where the data is. If that's not possible, the data will have to move to the job. For the sake of response time, you'll want Hive on every node.
To create a Hive table that references data stored in HBase, you can check out the Hive - HBase Integration wiki. Here's a quick example:
CREATE TABLE hbase_table_1(key int, value string)
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
WITH SERDEPROPERTIES ("hbase.columns.mapping" = ":key,cf1:val")
TBLPROPERTIES ("hbase.table.name" = "xyz");


text:
Q: Wordpress Hook into page body I am working on a plugin that will be used to add a customized form of Acuity Scheduling for a specific page. I want to add the scheduling form after the menu and page title on one particular page. Here is my current code:
add_action( 'template_redirect', 'check_if_acuity_page');

function check_if_acuity_page(){
    if(is_page('Schedule Page')){
    add_action( 'add to acuity', 'display_acuity_scheduling_api');
    }

}

function display_acuity_scheduling_api(){
    echo '
"Code to add Acuity Schedule to page"
';

}

The 'add to acuity' is a custom action hook that is currently added in the header.php file of the theme I am using. It adds the schedule at the very top of the page currently, so I can at least get it on the proper page, but it is located above the Menu and Title for the page. I am working on creating a custom layout and using PHP code to modify the page depending on what the user chooses, which is why I am not just using a simple embed code.
I am new to Wordpress Plugins and Hooks so I am not sure if I am supposed to be using an action or filter hook for this. Any help would be very appreciated.

A: To add code just before content which is below page title use following code:
function check_if_acuity_page(){
    if(is_page('Schedule Page')){
    echo '
"Code to add Acuity Schedule to page"
';}
}
function add_code_before_content($content){
    $acuity_page = check_if_acuity_page();
    $content = $acuity_page.$content;
    return $content;
}
add_filter('the_content','add_code_before_content');

Hope this helps.

A: WordPress action hooks are a means of providing a way for other developers to insert their own code in specific locations within your code, in order to change or expand the functionality of your code.
So in this case you should be using an action hook.
The concept of filters and hooks is explained in this article.
So by placing the add_action function in your template after the menu and page title you can hook onto it with a function.
In your page template after the menu and page title:
add_action( 'add to acuity', 'check_if_acuity_page');

In your functions.php:
function check_if_acuity_page() {
  if(is_page('Schedule Page')) {
    echo '
"Code to add Acuity Schedule to page"
';
  }
}


text:
Q: To reduce the resistance In the circuit I need to find out equivalence Resistance.

I have applied the Kirchhoff theorem and  but these  look too broad and might take too much time to solve. Is there any easy way to solve it?>
EDIT:
So if the vertical resistor doesn't apply any affect to the voltage then the equivalent resistance will be,
$$1/(R_e)=1/2R+1/2R+1/2R$$
That means
$$R_e=2/3R$$
. Is it right?? but the question is why the vertical resistor is not applying voltage changes to the circuit??? Are they acting as only voltage divisor, nothing else?

A: Here is a great way to look at a problem where all resistances are equivalent:

*

*Intuition: Lets (temporarily) remove the vertical resistors and attempt to analyze the problem. After removing the vertical resistors, lets look at what elements exist at the nodes of the voltage source:

*

*Connected between both nodes are 3 branches in parallel

*Inside of each branch are 2 resistors in series.

Since all three branches are identical, lets look at only a single branch first. Lets call the node in between the two resitors "MiddleNode". We apply voltage division and we find that that voltage at MiddleNode is 0.5*Vsource (because both resistors are identical).
Note that the MiddleNode voltage is identical on each of the three branches.
So if we look at the potential difference (voltage drop) between two MiddleNodes, we find that the voltage drop will be 0V. If you have a 0V potential difference between two nodes (two MiddleNodes in our case), no current will flow through an element placed there. Hence, the vertical resistors play no role.

*Solution: You have 3 branches in parallel with 2R resistance per branch.
2R//2R//2R = (2/3)R


text:
Q: SQL using a variable SQL query within another variable SQL query I've created a variable SQL query, where I declare the SQL query I want to use, due to variable table names. Our SQL is set up, based on an account name in the system. Meaning that it looks somewhat like this: [LSRetail].[dbo].[AccountName$Item].
Here the LSRetail part is dynamic, since it is called LSRetailDK if it's Denmark, and LSRetailSE if it's Sweden. The AccountName is also dynamic, due to different store names and zip codes...
All this actually works and is declared and set to @Sql, but due to space, I would like to make another DECLARE @Sql2 VARCHAR(8000), in which I want to SELECT * FROM @Sql. Since @Sql starts with a with cte1 AS ( statement, it wont allow me to do this.
Is it possible to do something here? I would like to combine the two in @Sql2 or maybe in an @Sql3.
Right now, the only thing that works is SET @Sql2 = @Sql and executing that.
The code below, is the code for @Sql of which I want to use inside @Sql2.
DECLARE @OrderNo VARCHAR(50);
DECLARE @StoreName VARCHAR(100);
DECLARE @Table1 VARCHAR(1000);
DECLARE @Table2 VARCHAR(1000);
DECLARE @Table3 VARCHAR(1000);
DECLARE @Table4 VARCHAR(1000);
DECLARE @Table5 VARCHAR(1000);
DECLARE @Table6 VARCHAR(1000);
DECLARE @Table7 VARCHAR(1000);
DECLARE @Table8 VARCHAR(1000);
DECLARE @Table9 VARCHAR(1000);
DECLARE @Database VARCHAR(1000);
DECLARE @BulkDiscount VARCHAR(1000);
DECLARE @DisclaimerDiscount VARCHAR(1000);
DECLARE @CashDiscount VARCHAR(1000);
DECLARE @Loyalty VARCHAR(1000);
DECLARE @Orders VARCHAR(8000);

SET @Database = '[LSRetail]'
SET @StoreName = 'AccountName';
SET @Orders = '''TI0573057'', ''TI0572704'', ''TI0572541'', ''TI0573058'', ''TI0572983'', ''TI0572595'', ''TI0573516'', ''TI0572841'', ''TI0573175'', ''TI0572759'', ''TI0572861'', ''TI0572917'', ''TI0568408'', ''TI0573077'', ''TI0572641'', ''TI0570757'', ''TI0573419'', ''TI0573394'', ''TI0572893'', ''TI0573029'', ''TI0573317'', ''TI0572581'', ''TI0570652'', ''TI0573061'', ''TI0573340'', ''TI0572417'', ''TI0572769'', ''TI0573315'', ''TI0572975'', ''TI0573304'', ''TI0573381'', ''TI0572976'', ''TI0572862'', ''TI0572886'', ''TI0573615'', ''TI0573049'', ''TI0572811'', ''TI0573156'', ''TI0573222'', ''TI0573095'', ''TI0573023''';

SET @BulkDiscount = 2.5/100
SET @DisclaimerDiscount = 1.5/100
SET @CashDiscount = 0.0/100
SET @Loyalty = 5.3/100

SET @Table1 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Invoice Line]');
SET @Table2 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Invoice Header]');
SET @Table3 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Item]');
SET @Table4 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Cr_Memo Line]');
SET @Table5 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Cr_Memo Header]');
SET @Table6 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Inv_ Header]');
SET @Table7 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Inv_ Line]');
SET @Table8 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Cr_ Memo Hdr_]');
SET @Table9 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Cr_ Memo Line]');

DECLARE @Sql VARCHAR(8000);
SET @Sql =
'
WITH cte1 AS(
SELECT a.[Document No_]
      ,''Invoice'' AS [Document Type]
      ,b.[Unique Document No_]
      ,a.[Type]
      ,a.[No_]
      ,c.[Vendor Item No_]
      ,a.[Gen_ Prod_ Posting Group]
      ,a.[VAT Bus_ Posting Group]
      ,a.[VAT Prod_ Posting Group]
      ,a.[Description]
      ,a.[Item Order Group Code]
      ,a.[Quantity]
      ,a.[Unit of Measure]
      ,a.[Unit Cost (LCY)]
      ,a.[Unit Price]
      ,a.[Line Amount]
      ,a.[Line Discount %]
      ,a.[Line Amount]/(a.[VAT %]/100+1)*0.96 AS [Total Line Sales]
      ,CASE WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @DisclaimerDiscount + ') * (1-' + @BulkDiscount + ') * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] LIKE ''SM%'' OR a.[No_] LIKE ''LE%'' AND a.[No_] LIKE ''%99999''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] <> ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] = ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
       END AS [Total Line Cost]
FROM ' + @Table1 + ' a
LEFT JOIN ' + @Table2 + ' b ON a.[Document No_] = b.[No_]
LEFT JOIN ' + @Table3 + ' c ON a.[No_] = c.[No_]
WHERE b.[Prepayment Invoice] = 0
),
cte2 AS(
SELECT a.[Document No_]
      ,''Credit Memo'' AS [Document Type]
      ,b.[Unique Document No_]
      ,a.[Type]
      ,a.[No_]
      ,c.[Vendor Item No_]
      ,a.[Gen_ Prod_ Posting Group]
      ,a.[VAT Bus_ Posting Group]
      ,a.[VAT Prod_ Posting Group]
      ,a.[Description]
      ,a.[Item Order Group Code]
      ,a.[Quantity] * (-1) AS [Quantity]
      ,a.[Unit of Measure]
      ,a.[Unit Cost (LCY)]
      ,a.[Unit Price]
      ,a.[Line Amount]
      ,a.[Line Discount %]
      ,a.[Line Amount]/(a.[VAT %]/100+1)*0.96 AS [Total Line Sales]
      ,CASE WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @DisclaimerDiscount + ') * (1-' + @BulkDiscount + ') * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] LIKE ''SM%'' OR a.[No_] LIKE ''LE%'' AND a.[No_] LIKE ''%99999''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] <> ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] = ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
       END AS [Total Line Cost]
FROM ' + @Table4 + ' a
LEFT JOIN ' + @Table5 + ' b ON a.[Document No_] = b.[No_]
LEFT JOIN ' + @Table3 + ' c ON a.[No_] = c.[No_]
WHERE b.[Prepayment Credit Memo] = 0
),
cte3 AS(
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
)
SELECT *
      ,CASE WHEN [Total Line Sales] <> 0
            THEN ([Total Line Sales] - [Total Line Cost])
            ELSE 0
       END AS [Margin]
      ,CASE WHEN [Total Line Sales] <> 0
            THEN ([Total Line Sales] - [Total Line Cost])/[Total Line Sales]
            ELSE 0
       END AS [Margin %]
FROM cte3
WHERE [No_] <> ''''
AND [Unique Document No_] IN (' + @Orders + ')
ORDER BY [Unique Document No_], [Item Order Group Code]
'

Thank you in advance for your assistance.
Note: I use SQL Server.

A: I found the solution to my problem...
By removing the last SELECT statement, I was able to use it in a second variable.
DECLARE @OrderNo VARCHAR(50);
DECLARE @StoreName VARCHAR(100);
DECLARE @Table1 VARCHAR(1000);
DECLARE @Table2 VARCHAR(1000);
DECLARE @Table3 VARCHAR(1000);
DECLARE @Table4 VARCHAR(1000);
DECLARE @Table5 VARCHAR(1000);
DECLARE @Table6 VARCHAR(1000);
DECLARE @Table7 VARCHAR(1000);
DECLARE @Table8 VARCHAR(1000);
DECLARE @Table9 VARCHAR(1000);
DECLARE @Database VARCHAR(1000);
DECLARE @BulkDiscount VARCHAR(1000);
DECLARE @DisclaimerDiscount VARCHAR(1000);
DECLARE @CashDiscount VARCHAR(1000);
DECLARE @Loyalty VARCHAR(1000);
DECLARE @Orders VARCHAR(8000);

SET @Database = '[LSRetail]'
SET @StoreName = 'AccountName';
SET @Orders = '''TI0573057'', ''TI0572704'', ''TI0572541'', ''TI0573058'', ''TI0572983'', ''TI0572595'', ''TI0573516'', ''TI0572841'', ''TI0573175'', ''TI0572759'', ''TI0572861'', ''TI0572917'', ''TI0568408'', ''TI0573077'', ''TI0572641'', ''TI0570757'', ''TI0573419'', ''TI0573394'', ''TI0572893'', ''TI0573029'', ''TI0573317'', ''TI0572581'', ''TI0570652'', ''TI0573061'', ''TI0573340'', ''TI0572417'', ''TI0572769'', ''TI0573315'', ''TI0572975'', ''TI0573304'', ''TI0573381'', ''TI0572976'', ''TI0572862'', ''TI0572886'', ''TI0573615'', ''TI0573049'', ''TI0572811'', ''TI0573156'', ''TI0573222'', ''TI0573095'', ''TI0573023''';

SET @BulkDiscount = 2.5/100
SET @DisclaimerDiscount = 1.5/100
SET @CashDiscount = 0.0/100
SET @Loyalty = 5.3/100

SET @Table1 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Invoice Line]');
SET @Table2 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Invoice Header]');
SET @Table3 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Item]');
SET @Table4 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Cr_Memo Line]');
SET @Table5 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Sales Cr_Memo Header]');
SET @Table6 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Inv_ Header]');
SET @Table7 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Inv_ Line]');
SET @Table8 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Cr_ Memo Hdr_]');
SET @Table9 = CONCAT(@Database,'.[dbo].[','' + @StoreName + '','$Purchase Cr_ Memo Line]');

DECLARE @Sql VARCHAR(8000);
SET @Sql =
'
WITH cte1 AS(
SELECT a.[Document No_]
      ,''Invoice'' AS [Document Type]
      ,b.[Unique Document No_]
      ,a.[Type]
      ,a.[No_]
      ,c.[Vendor Item No_]
      ,a.[Gen_ Prod_ Posting Group]
      ,a.[VAT Bus_ Posting Group]
      ,a.[VAT Prod_ Posting Group]
      ,a.[Description]
      ,a.[Item Order Group Code]
      ,a.[Quantity]
      ,a.[Unit of Measure]
      ,a.[Unit Cost (LCY)]
      ,a.[Unit Price]
      ,a.[Line Amount]
      ,a.[Line Discount %]
      ,a.[Line Amount]/(a.[VAT %]/100+1)*0.96 AS [Total Line Sales]
      ,CASE WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @DisclaimerDiscount + ') * (1-' + @BulkDiscount + ') * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] LIKE ''SM%'' OR a.[No_] LIKE ''LE%'' AND a.[No_] LIKE ''%99999''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] <> ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] = ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
       END AS [Total Line Cost]
FROM ' + @Table1 + ' a
LEFT JOIN ' + @Table2 + ' b ON a.[Document No_] = b.[No_]
LEFT JOIN ' + @Table3 + ' c ON a.[No_] = c.[No_]
WHERE b.[Prepayment Invoice] = 0
),
cte2 AS(
SELECT a.[Document No_]
      ,''Credit Memo'' AS [Document Type]
      ,b.[Unique Document No_]
      ,a.[Type]
      ,a.[No_]
      ,c.[Vendor Item No_]
      ,a.[Gen_ Prod_ Posting Group]
      ,a.[VAT Bus_ Posting Group]
      ,a.[VAT Prod_ Posting Group]
      ,a.[Description]
      ,a.[Item Order Group Code]
      ,a.[Quantity] * (-1) AS [Quantity]
      ,a.[Unit of Measure]
      ,a.[Unit Cost (LCY)]
      ,a.[Unit Price]
      ,a.[Line Amount]
      ,a.[Line Discount %]
      ,a.[Line Amount]/(a.[VAT %]/100+1)*0.96 AS [Total Line Sales]
      ,CASE WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @DisclaimerDiscount + ') * (1-' + @BulkDiscount + ') * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] LIKE ''SM%'' OR a.[No_] LIKE ''LE%'' AND a.[No_] LIKE ''%99999''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] <> ''OVT00100'' AND a.[Item Order Group Code] <> ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity] * (1-' + @CashDiscount + ') * (1-' + @Loyalty + ')
            WHEN a.[No_] NOT LIKE ''SM%'' OR a.[No_] NOT LIKE ''LE%'' AND a.[No_] NOT LIKE ''%99999'' AND a.[Item Order Group Code] = ''OVT00100'' AND a.[Item Order Group Code] = ''OVT00500''
            THEN a.[Unit Cost (LCY)]*a.[Quantity]
       END AS [Total Line Cost]
FROM ' + @Table4 + ' a
LEFT JOIN ' + @Table5 + ' b ON a.[Document No_] = b.[No_]
LEFT JOIN ' + @Table3 + ' c ON a.[No_] = c.[No_]
WHERE b.[Prepayment Credit Memo] = 0
),
cte3 AS(
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
)
'
@DECLARE @Sql2 VARCHAR(8000);
SET @Sql2 =
@Sql + '
SELECT *
      ,CASE WHEN [Total Line Sales] <> 0
            THEN ([Total Line Sales] - [Total Line Cost])
            ELSE 0
       END AS [Margin]
      ,CASE WHEN [Total Line Sales] <> 0
            THEN ([Total Line Sales] - [Total Line Cost])/[Total Line Sales]
            ELSE 0
       END AS [Margin %]
FROM cte3
WHERE [No_] <> ''''
AND [Unique Document No_] IN (' + @Orders + ')
ORDER BY [Unique Document No_], [Item Order Group Code]
'


text:
Q: I am trying to import a set of lists in python and call a random item from one of the lists #Set of lists I want to import into my python program called "setlist.txt"
---------------------------------------------------------------------------------------------
Tripolee = ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox')
Ranch = ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade')
Sherwood = ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume')
Jubilee = ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO')
The Hangar = ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD')
Forest = ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')
---------------------------------------------------------------------------------------------

#program

from sys import exit
from random import randint
from sys import argv

script, setlist = argv

setlist = open(setlist)

print "Here is the setlist for day 1"
print setlist.read()
print "%r is playing on the Tripolee stage" % random.choice(setlist.readline(2))

I have a bunch more code in between all this that I"m not putting up here but basically that last line what I'm having trouble with.

A: Probably not the best format for your file but you can split and use ast.literal_eval:
from ast import literal_eval
with open("in.txt") as f:
    choices = [literal_eval(line.split(" = ")[-1]) for line in f]

Which will give you a list of tuples which you can pass to random.choice:
[('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox'), ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade'), ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume'), ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO'), ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD'), ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')]

I have no idea where setlist is supposed to come from, you file is what looks like tuple assignments. setlist.readline(2) would read 2 bytes or actually in your case nothing as you have already exhausted the file iterator calling read.
I would suggest after extracting using literal_eval putting your file in a more usable format, maybe creating a dict using the name as the key and dumping the dict.
from ast import literal_eval
with open("in.txt") as f:
    choices = {}
    for line in f:
        ven, tpl = line.split(" = ")
        choices[ven] = literal_eval(tpl)
    print(choices)

Output:
{'Jubilee': ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO'), 'Tripolee': ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox'), 'The Hangar': ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD'), 'Ranch': ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade'), 'Sherwood': ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume'), 'Forest': ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')}

You can persist the dict using json.dump or the pickle module so your data will be in a lot easier format to each time.
To make it a little clearer what you have below is the content of your .txt file:
---------------------------------------------------------------------------------------------
Tripolee = ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox')
Ranch = ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade')
Sherwood = ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume')
Jubilee = ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO')
The Hangar = ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD')
Forest = ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')

To print the venue and set list you can use dict.items:
for ven, set_l in choices.items():
    print("Set list for {}: {}".format(ven, ", ".join(set_l)))

Output:
Set list for Jubilee:  Chaz French, MartyParty, Sango, Brodinski, Phutureprimitive, EOTO
Set list for Tripolee:  Saeed Younan, Matrixxman, Pete Tong, Dubfire, John Digweed, Carl Cox
Set list for The Hangar:  Vourteque, The Gentlemen Callers, Bart&Baker, Jaga Jazzist, JPOD
Set list for Ranch:  Dabin, Galantis, Borgeous, Shpongle, ODESZA, Kaskade
Set list for Sherwood:  Nadus, Mr. Carmack, Wave Racer, Lido, Goldlink, Four Tet, Flume
Set list for Forest:  Vibe Street, Lafa Taylor, Vaski, Little People, jackLNDN, MartyParty

When you open the file and call read you now have all the content in your file stored as a string. You then print the string, next you try random.choice(setlist.readline(2)), readline(2) is trying to read two bytes which it cannot even do as the file pointer is at the end of the file as you have already called read so you see an empty string outputted.
If you want to get a random string from the first tuple:
choices = [literal_eval(line.split(" = ")[-1]) for line in f]
from random import choice
print(choice(choices[0]))


text:
Q: Get value of a directive from the controller I'im new to AngularJs, I'm trying to access the value of 'data-page' when it's 'Active'  from my Controller (the pager is generated from a third party plugin)
Example: in the following example what i'm trying to get is the value:  3

       «

       4

       1

    ...
    ...

Edit folowing a suggestion
I added a directive:
  .directive('dataPage', function pageDirective() { // do the name dataPage Wrong ?

    return {
        restrict: 'A',
        link: function link(scope, element, attributes) {
            scope.page = attributes.dataPage;
            alert(scope.page);             // this one should i get the right value ?
        }
    }

})

And I added an alert in the controller just to know what is inside:
  $scope.fooFunc= function(){
     alert($scope.page); /*I supposed the value is now
                           avelaible in the controller scope, still get **undefined** */
  }

A: That is highly irregular as controllers shouldn't care about the DOM. Amongst many things, this rule helps to keep controllers very testable.
As soon as you begin to concern yourself with the DOM, then you move into Angular's directive territory.
Using the directive approach we could assign the data-page attribute to our controller scope by using the following:
app.directive('page', function pageDirective() {

    return {
        restrict: 'A',
        link: function link(scope, element, attributes) {
            scope.page = attributes.page;
        }
    }

});

Since the scope will be implicitly the same as the controller's scope, anything you perform on the scope variable inside the directive will be reflected on the controller – as long as the directive is in the controller's scope – ng-controller.
By specifying scope: true you will create a new scope for your directive which could access the controller's scope from the prototype chain, or by using scope.$parent. We also have scope: {} which creates an isolate scope and is a whole different kettle of fish.

A: Your question is really incomplete, but I'll do my best to try to answer it, since you specifically asked for my help in another thread.
SPECULATING: It seems like maybe you're trying to update the 'active' state of a DOM element, and have it update some data based on some paging index.
You probably don't need a new directive
You might be going about this the wrong way.
In Angular, the idea is to have your controller "control" all of your "business logic" for the page. The "business logic" being "what should I display and when?" This includes both your class and what data you want to display.
app.controller('MyCtrl', function($scope, someService) {
  // initialize your "data page" to something
  $scope.dataPage = 0;

  // watch for changes to dataPage
  $scope.$watch('dataPage', function(dataPage) {
    // do whatever it is you're doing to get your data.
    $scope.data = someService.getData(dataPage);
  });
});

Then in your view (HTML):

       «

       4

       1

    ...
    ...

{{data | json}}

More advanced information:
What I've shown above is a "quick and dirty" solution to the problem. The most ideal solution would be to leverage updates to the URL via $location and/or links with resolved data on the routes to load the data, so your pageData would be persisted in the URL itself (and therefor retain forward/back history in the browser). The solution for that looks quite a bit different and gets into some more advanced Angular topics. For now I'd just work on mastering the approach above and look into using routing, $location and $routeParams to persist the dataPage value.
Hopefully this helps you and I wish you the best of luck.

A: I recommend you always share data between your controllers and directives using a Service/Factory and injecting it on both sides.
app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: '',
      value2: ''
    }
  };
});

app.controller('FirstCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.directive('myDirective',['SharedService', function(SharedService){
  return{
    restrict: 'E',
    link: function(scope){
      scope.model = SharedService.sharedObject;
    },
    template: '
<input type="text" ng-model="model.value"/>
'
  }
}]);

Here is a plunkr showing how it can be done:
http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m


text:
Q: Flask request.get_json() возвращает None Спасайте. request.get_json() возвращает None. Я просто в отчаянье. В интернете ничего не помогло. + делал по шаблону, как в видео. Но у человека возвращается верный результат, а у меня - None. Спасибо большое заранее!

A: Разобрался. Отныне, чтобы не возвращался None, ОБЯЗАТЕЛЬНО ставьте параметр force=True.
request.get_json(force=True)


text:
Q: Creating copy of UIImageView in IOS I am creating an app in which i draw something over imageview using a sublayer function, now i want to create a copy of that image view (over which there is everything like sublayers and image) so that my original imageview don't get effected while accessing imageview for some other purposes. Is it possible to create a copy of image view containing all the contents and use that imageview again and again for different purposes.
Thanks

A: I'm not sure if you're trying to copy only the contained UIImage, or an image of all the layers. Examples for both:
import UIKit

// Original UIImageView
var imageView = UIImageView()

// Copying image into new UIImageView
var _imageView = UIImageView(image: imageView.image)

// Rendering everything inside the UIImageView into a new UIImageView
UIGraphicsBeginImageContextWithOptions(_imageView.bounds.size, _imageView.opaque, 0.0);
_imageView.layer.renderInContext(UIGraphicsGetCurrentContext())
let allLayersImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var __imageView = UIImageView(image: allLayersImage)


text:
Q: R installation won't let me open packages library issue Hi so I'm having trouble with R studios on my desktop where it won't let me open any packages.
When I attempt to install a package with install.packages()  like Tidyverse I get this error.

Error in library("tidyverse") : there is no package called 'tidyverse'
Show in New Window Error in install.Rtools() : could not find function
"install.Rtools" Show in New Window WARNING: Rtools is required to
build R packages but is not currently installed. Please download and
install the appropriate version of Rtools before proceeding:
https://cran.rstudio.com/bin/windows/Rtools/ Installing package into
'C:/Users/athen/Documents/R/win-library/4.1' (as 'lib' is unspecified)
trying URL
'https://cran.rstudio.com/bin/windows/contrib/4.1/tidyverse_1.3.1.zip'
Content type 'application/zip' length 430128 bytes (420 KB) downloaded
420 KB

Then when I try to load the package into my library with library("tidyverse") I receive this error

Error: package or namespace load failed for 'tidyverse' in inDL(x, as.logical(local), as.logical(now), ...):
unable to load shared object 'C:/Program Files/R/R-4.1.2/library/stats/libs/x64/stats.dll':
LoadLibrary failure: The specified module could not be found.

This error isn't just for tidyverse but all packages I try to run. I have uninstalled R and RStudios multiple times, but the error doesn't go away. I have been to IT at my university and they were completely baffled. Please help if you can, I really need R to work for both my job and classes.


text:
Q: Conjugate element Let $G$ be a group of order $2014$. Let $\theta\in G$ such that $|\theta|=19$ and $\alpha\in G$ such that $|\alpha|=2$. Show that $\alpha\theta\alpha=\theta^{\pm1}$.
Since the order of $\alpha$ is 2 I know that $\alpha=\alpha^{-1}$ so $\alpha\theta\alpha=\alpha^{-1}\theta\alpha$ so the element is conjugate to $\theta$ and thas must be $\theta^x$ for some positive integer x such that $0<x<19$ (I already showed that the group generated by $\theta$ is a unique sylow-p group in $G$). I would like a hint on how to continue from here

A: Hint: What is the group of automorphims of $\mathbb Z/19\mathbb Z$? (Or at least: What is the order of it?)

 There are $18$ automorphisms of $\mathbb Z/19\mathbb Z$: for $1\le k\le 18$ we obtain one from $1\mapsto k$. Among these is $x\mapsto x^{-1}$, which is of order $2$ and (because $18=2\cdot 9$) is the only automorphism of order $2$. Since conjugation with $\alpha$ is an automorphism of order at most $2$, the claim follows.


text:
Q: How to fix this? (Kali Linux 32-bit in Virtualbox) root@kali:~# sudo apt-get install -f
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
root@kali:~# sudo apt-get install -f
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
root@kali:~# sudo apt-get install curl
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
root@kali:~# sudo dpkg --configure -a
Setting up man-db (2.6.2-1) ...
Building database of manual pages ...
df -h
dpkg: dependency problems prevent configuration of steam-launcher:
 steam-launcher depends on libc6 (>= 2.15); however:
  Version of libc6:i386 on system is 2.13-38+deb7u1.

dpkg: error processing steam-launcher (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 steam-launcher
root@kali:~# sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages will be REMOVED:
  steam-launcher
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 2,898 kB disk space will be freed.
Do you want to continue [Y/n]? Abort.
root@kali:~# y
bash: y: command not found
root@kali:~# Y
bash: Y: command not found
root@kali:~#
GDBus.Error:org.gtk.GDBus.UnmappedGError.Quark._pk_5ftransaction_5ferror.Code4: SimulateInstallFiles not supported by backend

bash: cd: Downloads/: No such file or directory
root@kali:~# sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages will be REMOVED:
  steam-launcher
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 2,898 kB disk space will be freed.
Do you want to continue [Y/n]? y
(Reading database ... 337668 files and directories currently installed.)
Removing steam-launcher ...
Processing triggers for man-db ...
Processing triggers for hicolor-icon-theme ...
Processing triggers for desktop-file-utils ...
Processing triggers for gnome-menus ...
But it's STUCK at Processing triggers for gnome-menus ...

A: I have some pointers for you that should help you out.

*

*You should first read the Official Kali Linux Documentation to help you if you run into any issues.

*If not then you should google the specifics of your issue, including the exact error message. Someone else has probably ran into a similar problem as you and has either asked the question and received an answer or created a blog documenting what they did to solve the issue. You should also check out this site to read up on how to ask better questions.

*Lastly concerning the issue you are experiencing, this statement is directly from the Kali Linux documentation (emphasis mine):

While Kali Linux is architected to be highly customizable, don't expect to be able to add random unrelated packages and repositories that are "out of band" of the regular Kali software sources and have it Just Work. In particular, there is absolutely no support whatsoever for the apt-add-repository command, LaunchPad, or PPAs. Trying to install Steam on your Kali Linux desktop is an experiment that will not end well. Even getting a package as mainstream as NodeJS onto a Kali Linux installation can take a little extra effort and tinkering.

*

*To put it shortly, you will need to manually install the missing dependencies to complete the installation. I would recommend you use a different Distro if you wish to use Steam on Linux. Kali Linux is a tool for penetration testing, you are not really meant to install just any software on it.

*If you still want to continue, this post appears related to your issue.


text:
Q: Vim/Perl Regex Tag Match Problem I have data that looks like this:
[Shift]);[Ctrl][Ctrl+S][Left mouse-click][Backspace][Ctrl]

I want to find all [.*] tags that have the word mouse in them. Keeping in mind non-greedy specifiers, I tried this in Vim: \[.\{-}mouse.\{-}\], but this yielded this result,
[Shift]);[Ctrl][Ctrl+S][Left mouse-click]

Rather than just the desired,
[Left mouse-click]

Any ideas? Ultimately I need this pattern in Perl syntax as well, so if anyone has a solution in Perl that would also be appreciated.

A: \[[^]]*mouse[^[]*\]

That is, match a literal opening bracket, then any number of characters that aren't closing brackets, then "mouse," then any number of non-opening-brackets, and finally a literal closing bracket. Should be the same in Perl.

A: You can use the following regex:
\[[^\]]*mouse.*?\]


text:
Q: Compute $\int_{|z|=2}\frac{f'(z)}{f(z)}$ where $f$ I want to compute the following integral:
$\int_{|z|=2}\frac{f'(z)}{f(z)}$ where $f$ is defined as follows:
$f(z) = 1 + \frac{1}{z}+\frac{1}{2!z^2}+\dots+\frac{1}{n!z^n}$
I have already shown that $f$ has no zeros $|z|\geq 2$. Now, I want to use the Argument Principle Theorem.
In order to do this I have to compute the zeros, their multiplicities, the poles and their multiplicities.
But how can I compute the zeros? I only see that $0$ is a pole with multiplicity 9. I tried using the Rouche Theorem but got stuck.

A: It is an application of Rouché's Theorem. More precisely, it can be shown using the ideas of the proof of Rouché's Theorem.
Let $g(z)=\mathrm{e}^{1/z}$ and $f(z)=\sum_{k=0}^n \frac{1}{k!z^k}$.
Clearly, $$
\frac{1}{2\pi i}\int_{|z|=2}\frac{f'}{f}\in\mathbb Z
\quad\text{and}\quad
\frac{1}{2\pi i}\int_{|z|=2}\frac{g'}{g}\in\mathbb Z.
$$
Hence, if the function
$$
I(t)=\frac{1}{2\pi i}\int_{|z|=2}\frac{tf'+(1-t)g'}{tf+(1-t)g},
\quad t\in [0,1],
$$
is well-defined and continuous, then it is constant and hence
$$
\frac{1}{2\pi i}\int_{|z|=2}\frac{f'}{f}=I(1)=I(0)=
\frac{1}{2\pi i}\int_{|z|=2}\frac{g'}{g}=0.
$$
It suffices to show that $|g(z)|>|g(z)-f(z)|$,
for all $|z|=2$. Once this is proven then we shall have that
$$
|tf(z)+(1-t)g(z)|\le |g(z)|-t|g(z)-f(z)|> 0,
\quad \text{whenever $t\in [0,1],\,\,|z|=2$}.
$$
We have
$$
g(z)-f(z)=\sum_{k=n+1}^\infty \frac{1}{k!z^k}
=\frac{1}{(n+1)!z^{n+1}}\sum_{k=0}^\infty \frac{(n+1)!}{(n+1+k)!z^k}
$$
and hence, for $|z|=2$
$$
|g(z)-f(z)|\le
\frac{1}{(n+1)!|z|^{n+1}}\sum_{k=0}^\infty \frac{(n+1)!}{(n+1+k)!|z|^k}
\le \frac{1}{(n+1)!|z|^{n+1}}\mathrm{e}^{1/|z|} =\frac{\mathrm{e}^{½}}{2^{n+1}(n+1)!}.
$$
Meanwhile, also for $|z|=2$
$$
|g(z)|=|\mathrm{e}^{1/z}|\ge \mathrm{e}^{-½} .
$$
Finally, for $n\ge 1$,
$$
\frac{\mathrm{e}^{½}}{2^{n+1}(n+1)!}\le \frac{\mathrm{e}^{½}}{2^{2}2!} =\frac{\mathrm{e}^{½}}{8} <\mathrm{e}^{-½}.
$$
Hence, $\frac{1}{2\pi i}\int_{|z|=2}\frac{f'}{f}=0$.