text:
Q: Descending Fibonacci numbers using an iterator So my code essentially works, at least how I expected. But my issue is my Fibonacci numbers are supposed to be descending not ascending. The reason I am struggling with this is because the starting number is user input, so unlike ascending I don't know what the first step is everytime.  I considered just loading the ints into an array, sorting and printing them, but I feel like that defeats the purpose of the iterator... Any thoughts? Here is my code:
import java.util.Iterator;
import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.DateFormat;

public class Conversion1
{

    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        int choice = 0;
        int prime = 0, p = 0;
        int fib = 0, f = 0;
        long pTime = 0;
        long fTime = 0;
        long pETime = 0;
        long fETime = 0;
        int ff[];
        long start = System.currentTimeMillis();

        while (choice != 3)
        {
            System.out.println("Enter 1 or 2 to print out Fibonacci or Prime number iterator or enter 3 to exit.");
            System.out.println("1 - Fibonacci Number Iterator");
            System.out.println("2 - Prime Number Iterator");
            System.out.println("3 - Exit");
            choice = scanner.nextInt();
            switch (choice)
            {
                case 1:
                    fTime += System.currentTimeMillis();
                    System.out.println("Enter the Max value");
                    int maxInt2 = scanner.nextInt();
                    ff = new int[maxInt2];
                    Iterator iterator = new FibonacciIterator(maxInt2);
                    while (iterator.hasNext())
                    {
                        ff[f] = (int) iterator.next();
                        f++;
                    }
                    for (int i = 0; i < f; i++)
                        System.out.println(ff[i]);
                    fETime += System.currentTimeMillis();
                    fib++;
                    break;

                case 2:
                    pTime += System.currentTimeMillis();
                    System.out.println("Enter the Max value");
                    int maxInt = scanner.nextInt();
                    Iterator iterator2 = new PrimeIterator(maxInt);

                    while (iterator2.hasNext())
                    {
                        System.out.println(iterator2.next());
                        p++;
                    }

                    System.out.println("\n");
                    pETime += System.currentTimeMillis();
                    prime++;
                    break;

                case 3:
                    long pFinal = pETime - pTime;
                    long fFinal = fETime - fTime;
                    double fseconds = ((fFinal / 1000) % 60);
                    double pseconds = ((pFinal / 1000) % 60);
                    System.out.println("\n");
                    System.out.println(fib + " Fibonacci commands yielding " + f + " individual outputs requiring "
                        + fseconds + " seconds.");
                    System.out.println("\n");
                    System.out.println(prime + " Prime commands yielding " + p + " individual outputs requiring " + pseconds
                        + " seconds.");
                    System.out.println("\n");
                    long end = System.currentTimeMillis();
                    DateFormat df = new SimpleDateFormat("HH':'mm':'ss");
                    System.out.println("Program started at " + df.format(new Date(start)) + " and terminated at: "
                        + df.format(new Date(end)));
                    System.out.println("\n");
                    System.out.println("Program Ended");
                    System.out.println("\n");
                    break;

                default:

                    System.out.println("Invalid Input");

            }

        }
    }

    static class PrimeIterator implements java.util.Iterator
    {
        private int limit = 0;
        private int current;
        private int a_number;

        public PrimeIterator(int current)
        {
            this.current = current;
        }

        @Override
        public Integer next()
        {
            return current;
        }

        static boolean isPrime(int number)
        {
            for (int divisor = 2; divisor < number; divisor++)
                if (number % divisor == 0)
                    return false;

            return true;

        }

        @Override
        public boolean hasNext()
        {
            current--;

            while (true)
            {
                if (isPrime(current))
                    break;

                current--;
            }

            if (current <= limit)

                return false;

            else

                return true;

        }
    }

    static class FibonacciIterator implements java.util.Iterator
    {
        private int limit;
        private int current = 1;// -1,1,0,1,1,2,3,5
        private int prev = -1;

        public FibonacciIterator(int limit)
        {
            this.limit = limit;
        }

        @Override
        public Integer next()
        {
            return current;
        }

        @Override
        public boolean hasNext()
        {
            int temp = current;
            current = current + prev;// -1+1=0
            prev = temp;

            if (current >= limit)
                return false;

            else

                return true;

        }

        @Override
        public void remove()
        {
            throw new UnsupportedOperationException("Method not supported");
        }
    }
}

A: If you have to reverse the order, can you not just flip the order of the Fibonacci values captured?
                for (int i = f - 1; i >= 0; i--)
                    System.out.println(ff[i]);

As opposed to what you have where you start at index 0.
                for (int i = 0; i < f; i++)
                    System.out.println(ff[i]);


text:
Q: Can I get content to overlap scroll bar? CSS I have a situation where the 'bar' div, display some information about the 'foo' element, when the 'foo' element is hovered. But the scroll bar conflict with that, and hide the rest of my div. Can I get it to display the full 'bar' div somehow?
HTML

        xxx

Info text, info text

CSS
.box {
    height: 80px;
    width: 80px;
    background: blue;
    position: absolute;
    overflow-y: scroll;
    overflow-x: hidden;
}
.foo {
    float: left;
    background: red;
    height: 50px;
    width: 50px;
    position: relative;
}
.bar {
    float: left;
    height: 20px;
    width: 125px;
    background: orange;
    position: relative;
    top: -10px;
    right: -30px;
    display: none;
}
.foo:hover > .bar {
    display: block;
}

A: You could set the .bar div to position:fixed
JSfiddle Demo
CSS
.box {
    height: 80px;
    width: 80px;
    background: blue;
    position: absolute;
    overflow-y: scroll;
    overflow-x: hidden;
}
.foo {
    float: left;
    background: red;
    height: 50px;
    width: 50px;
}
.bar {
    height: 20px;
    width: 125px;
    background: orange;
    position: fixed;
    display: none;
}
.foo:hover > .bar {
    display: block;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling asynchronous functions identified by key I'm trying to call a group of asynchronous functions identified by parameters.
Example: callFunctions("A,C"); would call both objFns["A"] and objFns["C"].
The problem I have run into is that arrayParams[i] is resolved when the internal function is finally called by async.parallel().  This means that i == arrayParams.length which of course crashes since objFns[arrayParams.length] is undefined. Help pointing me in the right direction would be appreciated.
objFns = {};
objFns["A"] = function (callback) {...}
objFns["B"] = function (callback) {...}
objFns["C"] = function (callback) {...}

function callFunctions(arrayParam) {
    var i, arrayFns = [];

    for (i = 0; i < arrayParams.length; i++) {
        arrayFns.push(function (callback) {
            objFns[arrayParams[i]](callback);
        }
    }

    async.parallel(arrayFns, function (error) {...});
}

A: You can use anonymous function to make copy of i on each iteration.
var async = require('async');

objFns = {};
objFns["A"] = function (callback) {callback();};
objFns["B"] = function (callback) {callback();};
objFns["C"] = function (callback) {callback();};

function callFunctions(arrayParams) {
  var i,arrayFns = [];

  for (i = 0; i < arrayParams.length; i++) {
    (function (i) {
      arrayFns.push(function (callback) {
        objFns[arrayParams[i]](callback);
      });
    })(i);
  }

  async.parallel(arrayFns,function(error) {
  });
}

callFunctions(['A', 'B']);

If you don't need to change functions behaviour you can simple copy functions to array without outer function.
var async = require('async');

objFns = {};
objFns["A"] = function (callback) {callback();};
objFns["B"] = function (callback) {callback();};
objFns["C"] = function (callback) {callback();};

function callFunctions(arrayParams) {
  var i,arrayFns = [];

  for (i = 0; i < arrayParams.length; i++) {
    arrayFns.push(objFns[arrayParams[i]]);
  }

  async.parallel(arrayFns,function(error) {
  });
}

callFunctions(['A', 'B']);

A: As far as i can tell, what you are pushing onto arrayFns is a function which directly calls another function with the same parameters, is there any reason why this should not work:
function callFunctions(arrayParam)
{
  var i,arrayFns = [];

  for (i = 0; i < arrayParams.length; i++)
  {
    arrayFns.push(objFns[arrayParams[i]]);
  }

  async.parallel(arrayFns,function(error) {...});
}


text:
Q: Pie chart with multiple dropdown options I'm trying to make a pie chart with 3 options:

*

*Create graph for all item when don't select dropdown options

*Show each graph for each item selection.

*Create graph for multiple item options. It's the sum of item options.

Below is my code:
import pandas as pd
import numpy as np
import plotly.express as px
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.graph_objects as go

df = pd.DataFrame({
    'invoiceTotal': [123.25,237.55,220.13,211.35,135.46],
    'itemType': ['item','service','service','service','item'],
    'Channel':['In Store','Phone Order','In Store','E-mail','Website']})

app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
                dbc.Row([
                        dcc.Dropdown(id='channel_type',placeholder="Channel", # Dropdown for heatmap color
                                options=[{'label':y,'value':y} for y in df.sort_values('Channel')['Channel'].unique()],
                                multi=False,
                                disabled=False,
                                clearable=True,
                                searchable=True),
                        dcc.Graph(id='pie-chart',figure={},style={'height':400,'width':'auto'})
                        ])
])

@app.callback(Output('pie-chart', 'figure'),
             [Input('channel_type', 'value')])

def build_graph(channeltype):
    if not channeltype or 'Select' in channeltype:
        df1 = df.copy()
        df1_1 = pd.pivot_table(df1,('invoiceTotal'),index=['itemType'],aggfunc=np.sum).reset_index()
        df1_1['Channel'] = 'All channel'
    else:
        df1 = df.copy()
        df1_1 = pd.pivot_table(df1,('invoiceTotal'),index=['itemType','Channel'],aggfunc=np.sum).reset_index()
        df1_1 = df1_1[(df1_1['Channel'] == channeltype)]

    pie_chart = px.pie(df1_1,values='invoiceTotal',names='itemType',
               color_discrete_sequence=px.colors.qualitative.Prism,hole=.3)
    pie_chart.update_traces(textinfo='percent+label',
                    title_position="top center",
                    title_font_size=18,
                    showlegend=True)
    pie_chart.update_layout(plot_bgcolor='white',margin=dict(l=20, r=20, t=20, b=20))
    pie_chart.update_yaxes(showline=False,showgrid=False)
    pie_chart.update_xaxes(showline=False,showgrid=False)
    return pie_chart

if __name__ == "__main__":
    app.run_server(debug=False,port=1200)

It's just working for option 1 and option 2. When I change options of dropdown from False to True, it raised error that said: ValueError: ('Lengths must match to compare', (5,), (1,))
I'm curious is that anyway to make option 3. Thank you.

A: The multiple selection in the dropdown should be set as multi=positive and the values received will be a mixture of single and multiple values, so the format needs to be changed to extract conditions by the values included using isin. I'm also adding a setting as an initial graph. Please verify the data yourself as we have not verified all the data.
import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
from jupyter_dash import JupyterDash
from dash.dependencies import Input, Output, State
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({
    'invoiceTotal': [123.25,237.55,220.13,211.35,135.46],
    'itemType': ['item','service','service','service','item'],
    'Channel':['In Store','Phone Order','In Store','E-mail','Website']})

app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
#app = JupyterDash(__name__,external_stylesheets=[dbc.themes.LUX])

app.layout = html.Div([
                dbc.Row([
                        dcc.Dropdown(id='channel_type',placeholder="Channel", # Dropdown for heatmap color
                                options=[{'label':y,'value':y} for y in df.sort_values('Channel')['Channel'].unique()],
                                multi=True, # update
                                disabled=False,
                                clearable=True,
                                searchable=True),
                        dcc.Graph(id='pie-chart',figure=pie_chart, style={'height':400,'width':'auto'}) # update
                        ])
])

@app.callback(Output('pie-chart', 'figure'),
             [Input('channel_type', 'value')])

def build_graph(channeltype):
    if not channeltype or 'Select' in channeltype:
        df1 = df.copy()
        df1_1 = pd.pivot_table(df1,('invoiceTotal'),index=['itemType'],aggfunc=np.sum).reset_index()
        df1_1['Channel'] = 'All channel'
    else:
        df1 = df.copy()
        df1_1 = pd.pivot_table(df1,('invoiceTotal'),index=['itemType','Channel'],aggfunc=np.sum).reset_index()
        df1_1 = df1_1[df1_1['Channel'].isin(channeltype)] # update

    pie_chart = px.pie(df1_1,values='invoiceTotal',names='itemType',
               color_discrete_sequence=px.colors.qualitative.Prism,hole=.3)
    pie_chart.update_traces(textinfo='percent+label',
                    title_position="top center",
                    title_font_size=18,
                    showlegend=True)
    pie_chart.update_layout(plot_bgcolor='white',margin=dict(l=20, r=20, t=20, b=20))
    pie_chart.update_yaxes(showline=False,showgrid=False)
    pie_chart.update_xaxes(showline=False,showgrid=False)
    return pie_chart

if __name__ == "__main__":
    app.run_server(debug=False, port=1200)# mode='inline'


text:
Q: $request->file('image') result is null I want to save an image on a directory and retrieve it on the webpage. I've tried several methods to store an image in a folder, but I got this error.
When I use  $request->file('image') result is null
I find out solutions and try as that solutions. But I can't fix it.
How can I fix this error and how can I save an image on a file directory
 Controller

   public function dili(Request $request)
   {
    $di = new diligent;

    $di->jobtype = $request->jobtype;
    $di->jobC = $request->jobC;
    $di->details = $request->details;
    $di->image = $request->image;

    $imag =  $request->image;

    //dd($imag);
    $path = $imag->getClientOriginalName();

    $destinationPath = public_path('img');

    $imag->move($destinationPath, $path);

    $di->save();
    $de = diligent::all();
    return view('admin')->with('dw', $de);
}

web.php
 Route::post('/admin', ['as'=> 'image.add', 'uses' => 'diligents@dili' ]);

admin.blade.php
<form class="row login_form" action="/admin" method="post"
novalidate="novalidate" enctype="multipart/form-data">
{{csrf_field()}}

<input type="text" class="form-control" id="job" name="jobtype"
 placeholder="Job " onfocus="this.placeholder =
 ''"onblur="this.placeholder = 'Job'">

<input type="text" class="form-control" id="jobC" name="jobC" placeholder="Job Catagary" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Job Catagary'">

<textarea class="form-control" name="details" id="details" rows="4" placeholder="Details" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Details'"></textarea>

Upload Image

<input type="file" name="image" id="image">

<button type="submit" value="submit" class="primary-btn">Submit</button>

<button type="submit" value="submit" class="primary-btn">Update</button>

</form>

This is the error message I got:

Call to a member function getClientOriginalName() on string

A: Try this code for your project.
   $image = $request->file('image');

   $path = $image->getClientOriginalName();

   dd($path);

By dd()you find your image name.
And I hope the error will be removed.


text:
Q: How to access grails Arraylist of Object from JavaScript My grails controller MyController.groovy has following action:
def index = {
    def myModel = new MyModel()
    // res below is a list of MyChild objects from a service call
    def childList = jacksonObjectMapper.readValue(res, new TypeReference<List<MyChild>>() {})
    myModel.setMyChildList(childList)

    render(view: 'index', model: [myModelInstance: myModel])
}

This renders index.gsp having access to myModel through myModelInstance.
In index.gsp, I have a javascript method as below:
<g:javascript>
    function someJavascriptFunction(){
        var message = $.parseJSON("${myModelInstance.myChildList as grails.converters.JSON}");
        console.log("I am from grails: "+message);
    }
</g:javascript>

Considering I have two elements in the list, this prints:
I am from grails: [object Object],[object Object]

But this is not what I want. How can I access the MyChild Objects in the list and the properties/values within those MyChild objects inside my javascript function ?

A: Do the some modifications in your Groovy and JS code.
def index = {
                    def myModel = new MyModel()
                    // res below is a list of MyChild objects from a service call
                    def childList = jacksonObjectMapper.readValue(res, new TypeReference<List<MyChild>>() {})
                    myModel.setMyChildList(childList)

                    render(view: 'index', model: [myModelInstance: myModel grails.converters.JSON])
            }

In javascript

  // Get model rendered from groovy action.
  var myModelInstance = ${myModelInstance};
  //Now iterate over the json object to get values
  for(var i = 0 ; i < myModelInstance.length; i++){
     console.log(myModelInstance[i]);
    /*If the list contain nested object (groovy map inside the list)
    then get key and values as,*/
    console.log("key:",myModelInstance[i].keyName);
    console.log("value:",myModelInstance[i].valueName);
  }

</script>


text:
Q: JPA Eclipse link query.firstResult() & query.setMaxResults() with Postgres Postgres supports offset and limit on SQL statements to support pagination style queries. With limit and/or offset in the queries the results come back much faster from the DB.
I am using Eclipse Link as the JPA provider and by using  query.firstResult() & query.setMaxResults(), the generated SQL does not use limit & offset to narrow the result set. I see that when I turn logging on. I believe it is setting the first pointer in the result set to start at query.firstResult(). This is not even close to being as efficient as using the limit or offset in the SQL directly.
Is there a way to get JPA to use limit/offset or I am stuck with query.firstResult() & query.setMaxResults()?

A: You are either using an older version that does not have pagination implemented in the PostgreSQLPlatform, or have not configured EclipseLink to use the PostgreSQLPlatform.
Support was added through https://bugs.eclipse.org/bugs/show_bug.cgi?id=211691 to EclipseLink 1.1, so check that autodetection is using the correct database platform.  You may need to add the "eclipselink.target-database" persistence property with a value of PostgreSQL if it cannot be detected correctly.


text:
Q: XDomainRequest has no content type when sending POST request I'm working on some cross-domain ajax requests. I use XDomainRequest to send requests in IE8 and IE9. Currently, it works well on Get requests, but not on Post requests.
When I use Fiddle capturing the requests, I find that the Post request has no Content-Type header.
Does anyone know about this?

A: Unfortunately, it looks like they screwed up and left it out. I am having the same problem.
According to this there is no way to set the Content-Type header and I have not found a way myself. You'll see that they actually made it WORSE with a later bug fix. As XDomainRequest is deprecated in IE10 for the correct XMLHttpRequest object using CORS I doubt there will ever be a fix.
If you ever found a way around the problem please post back and let the world know. This is preventing me from using Amazon S3 POST for uploading avatars.


text:
Q: ASP NET 5 - Custom Authentication scheme handler is ignored when using Identity Custom authentication scheme and handlers are ignored.
When controller method is annotated by [Authorize], my scheme is not challenged even though it is set as default authentication scheme. Instead, 302 status is send with redirection to /Accounts/Login....
Not only that this URL does not even exist in my app (I am using Blazor WASM on client side), but there is no code at all in my application that should inflict this behavior.
My authentication handler is invoked when I specify it directly in the attribute: [Authorize(AuthenticationScheme = CustomAuthHandler.SchemeName)]
Why is default authentication scheme ignored and instead is run something not specified in the code at all?
If AddIdentity() configures this unexpected behavior, where is it documented and how can it be reconfigured?
How to make the framework not ignore my handler, registered as default?
Everything worked properly until i switched to .NET 5 and started using Identity framework.
This is my ConfigureServices:
services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), ServerVersion.FromString("10.5.6-mariadb"));
        });

services.AddIdentity<ApplicationUser, IdentityRole>(
        options =>
            {
                options.User.RequireUniqueEmail = true;
            }
        )
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddClaimsPrincipalFactory<ApplicationUserClaimsFactory>();

services.AddControllersWithViews();
services.AddRazorPages();

services.AddAuthentication(
     options =>
     {
         options.DefaultScheme = CustomAuthHandler.SchemeName;
     }
)
.AddScheme<AuthenticationSchemeOptions, CustomAuthHandler>(CustomAuthHandler.SchemeName, x => {  });

A: Ok, AddIdentity() method actually caused the problem.
Solution is to replace it with AddIdentityCore(), which is more lightweight method and does less under the hood. Then the missing services have to be added manually, e.g. AddRoles(), as stated in documentation.


text:
Q: How to accept socket with timeout Is there is a timeout crossplatform soulution to accept client using accept function without setting socket to non-blocking?
I know that i should use select function to it, but what i'm doing wrong?
SOCKET NativesAcceptClient(SOCKET s, int timeout)
{
   int iResult;
   struct timeval tv;
   fd_set rfds;
   FD_ZERO(&rfds);
   FD_SET(s, &rfds);

   tv.tv_sec = (long)timeout;
   tv.tv_usec = 0;

   iResult = select(s, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
   if(iResult > 0)
   {
      return accept(s, NULL, NULL);
   }
   else
   {
     //always here, even if i connect from another application
   }
   return 0;
}

How to fix that?
Thanks!

A: The first parameter of the select call should be equal to the the highest number file descriptor in your fd_set set plus 1 (see here). Try changing the first argument to s+1; you will need to add some logic when your have more than one socket in your set.

A: The first argument of select() is an int that is at least 1 greater than the highest value of the file descriptors in any of the bitsets.  In this case
iResult = select(s + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);

should work.

A: select() returns >0 if a socket is signaled, 0 on timeout, and -1 on error.  What value is select() actually returning to you?  You are only checking for >0 and <=0, which means you are not differentiating between -1 and 0.  If it is returning 0 then no client is connecting to your socket, but if it is returning -1 then your socket is likely not valid to begin with.


text:
Q: Should exceptions ever be caught No doubt exceptions are usefull as they show programmer where he's using functions incorrectly or something bad happens with an environment but is there a real need to catch them?
Not caught exceptions are terminating the program but you can still see where the problem is. In well designed libraries every "unexpected" situation has actually workaround. For example using map::find instead of map::at, checking whether your int variable is smaller than vector::size prior to using index operator.
Why would anyone need to do it (excluding people using libraries that enforce it)? Basically if you are writing a handler to given exception you could as well write a code that prevents it from happening.

A: Not all exceptions are fatal. They may be unusual and, therefore, "exceptions," but a point higher in the call stack can be implemented to either retry or move on. In this way, exceptions are used to unwind the stack and a nested series of function or method calls to a point in the program which can actually handle the cause of the exception -- even if only to clean up some resources, log an error, and continue on as before.

A: You can't always write code that prevents an exception. Just for an obvious example, consider concurrent code. Let's assume I attempt to verify that i is between (say) 0 and 20, then use i to index into some array. So, I check and i == 12, so I proceed to use it to index into the array. Unfortunately, in between the test and the indexing operation, some other thread added 20 to i, so by the time it's used as an index, it's not in range any more.
The concurrency has led to a race condition, so the attempt at assuring against an exceptional condition has failed. While it's possible to prevent this by (for example) wrapping each such test/use sequence in a critical section (or similar), it's often impractical to do so--first, getting the code correct will often be quite difficult, and second even if you do get it correct, the consequences on execution speed may be unacceptable.
Exceptions also decouple code that detects an exceptional condition from code that reacts to that exceptional condition. This is why exception handling is so popular with library writers. The code in the library doesn't have a clue of the correct way to react to a particular exceptional condition. Just for a really trivial example, let's assume it can't read from a file. Should it print a message to stderr, pop up a MessageBox, or write to a log?
In reality, it should do none of these. At least two (and possibly all three) will be wrong for any given program. So, what it should do is throw an exception, and let code at a higher level determine the appropriate way to respond. For one program it may make sense to log the error and continue with other work, but for another the file may be sufficiently critical that its only reasonable reaction is to abort execution entirely.

A: Exceptions are very expensive, performance vise - thus, whenever performance matter you will want to write an exception free code (using "plain C" techniques for error propagation).
However, if performance is not of immediate concern, then exceptions would allow you to develop a less cluttered code, as error handling can be postponed (but then you will have to deal with non-local transfer of control, which may be confusing in itself).

A: I have used extensivelly exceptions as a method to transfer control on specific positions depending on event handling.
Exceptions may also be a method to transfer control to a "labeled" position alog the tree of calling functions.
When an exception happens the code may be thought as backtracking one level at a time and checking if that level has an exception active and executing it.
The real problem with exceptions is that you don't really know where these will happen.
The code that arrives to an exception, usually doesn't know why there is a problem, so a fast returning back to a known state is a good action.
Let's make an example: You are in Venice and you look at the map walking throught small roads, at a moment you arrive somewhere that you aren't able to find in the map.
Essentially you are confused and you don't understand where you are.
If you have the ariadne "μιτος" you may go back to a known point and restart to try to arrive where you want.
I think you should treat error handling only as a control structure allowing to go back at any level signaled (by the error handling routine and the error code).


text:
Q: Angular Library outside the Angular Cli Workspace Is it possible to have a library outside the workspace of angular cli?
Traditional scheme:
my-workspace/
  ...             (workspace-wide config files)
  projects/       (generated applications and libraries)
    my-first-app/ --(an explicitly generated application)
      ...         --(application-specific config)
      e2e/        ----(corresponding e2e tests)
         src/     ----(e2e tests source)
         ...      ----(e2e-specific config)
      src/        --(source and support files for application)
    my-lib/       --(a generated library)
      ...         --(library-specific config)
      src/        --source and support files for library)

Now, I have a library: my-lib2 that reside in another directory, not inside the projects directory. I put the configuration of my-lib2 in angular.json file of my-workspace, with relative path, but, when I compile this: ng build my-lib2, inside the workspace, I have this errors:
Building Angular Package

** It is not recommended to publish Ivy libraries to NPM repositories **

------------------------------------------------------------------------------
Building entry point 'my-lib2'
------------------------------------------------------------------------------
Compiling TypeScript sources through ngc
ERROR: ../my-lib2/src/lib/my-lib2.component.ts(1,35): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.module.ts(1,26): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.service.ts(1,28): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.service.ts(3,1): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.

An unhandled exception occurred: ../my-lib2/src/lib/my-lib2.component.ts(1,35): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.module.ts(1,26): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.service.ts(1,28): error TS2307: Cannot find module '@angular/core'.
../my-lib2/src/lib/my-lib2.service.ts(3,1): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.

See "/tmp/ng-bt10hE/angular-errors.log" for further details.

Schema
my-lib2/
      ...
      src/

my-workspace/
  ...
  projects/
    my-first-app/
      ...
      e2e/
         src/
         ...
      src/
    my-lib/
      ...
      src/

Configuration of angular.json inside of workspace:
...
   ...
   "my-lib2": {
      "projectType": "library",
      "root": "projects/../../my-lib2/",
      "sourceRoot": "projects/../../my-lib2/src",
      "prefix": "lib",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/../../my-lib2/tsconfig.lib.json",
            "project": "projects/../../my-lib2/ng-package.json"
          },
          "configurations": {
            "production": {
              "tsConfig": "projects/../../my-lib2/tsconfig.lib.prod.json"
            }
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/../../my-lib2/src/test.ts",
            "tsConfig": "projects/../../my-lib2/tsconfig.spec.json",
            "karmaConfig": "projects/../../my-lib2/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/../../my-lib2/tsconfig.lib.json",
              "projects/../../my-lib2/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }},
    ...
    ...

tsconfig.lib.ts (configuration file of my-lib2)
{
  "extends": "../my-workspace/tsconfig.json",
  "compilerOptions": {
    "outDir": "../my-workspace/out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ]
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

As can be seen, all paths are relative ...
Any idea how I can configure the entries in angular.json of the workspace to take the library out of the projects path?

A: The solution was the correct configuration of the tsconfig.lib.ts file of the library.
Schema of directory:
my-lib2/
      ...
      src/

my-workspace/
  ...
  projects/
    my-first-app/
      ...
      e2e/
         src/
         ...
      src/
    my-lib/
      ...
      src/

my-lib2 entry in the angular.json file in the workspace:
"my-lib2": {
      "projectType": "library",
      "root": "../my-lib2",
      "sourceRoot": "../my-lib2/src",
      "prefix": "lib",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "../my-lib2/tsconfig.lib.json",
            "project": "../my-lib2/ng-package.json"
          },
          "configurations": {
            "production": {
              "tsConfig": "../my-lib2/tsconfig.lib.prod.json"
            }
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "../my-lib2/src/test.ts",
            "tsConfig": "../my-lib2/tsconfig.spec.json",
            "karmaConfig": "../my-lib2/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "../my-lib2/tsconfig.lib.json",
              "../my-lib2/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }},

tsconfig.lib.ts file configuration in my-lib2 directory:
{
  "extends": "../my-workspace/tsconfig.json",
  "compilerOptions": {
    "outDir": "../my-workspace/out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ],
    "baseUrl": "../my-workspace/",
    "paths": {
      "*": ["../my-workspace/node_modules/*"]
    }
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

This is the important part in the configuration:
 ...
 "baseUrl": "../my-workspace/",
 "paths": {
       "*": ["../my-workspace/node_modules/*"]
 }
 ...

Run compilation:
Building Angular Package

** It is not recommended to publish Ivy libraries to NPM repositories **

------------------------------------------------------------------------------
Building entry point 'my-lib2'
------------------------------------------------------------------------------
Compiling TypeScript sources through ngc
Bundling to FESM2015
Bundling to FESM5
Bundling to UMD
Minifying UMD bundle
Copying declaration files
Writing package metadata
Built my-lib2

------------------------------------------------------------------------------
Built Angular Package!
 - from: /home/usuario/my-project/my-lib2
 - to:   /home/usuario/my-project/my-workspace/dist/my-lib2
------------------------------------------------------------------------------


text:
Q: Union Columns Vertically in SQL Assume these Tables:
Group: (Id, Title):  {1,G1}, {2,G2}, {3,G3}, {4, G4}
Category: (Id, Title): {1, Cat1}, {2, Cat2}, {3, Cat3}, {4, Cat4}
Product: (Id, GroupId, CategoryId, Name):
{1, 1, 1, G1C1P1},
{2, 1, 2, G1C2P2},
{3, 1, 2, G1C2P3},
{4, 2, 2, G2C2P4},
{5, 2, 2, G2C2P5},
{6, 3, 1, G3C1P6},
{7, 3, 3, G3C3P7}

Dealer: (Id, Name):  {1, 'Dealer1'}, {2, 'Dealer2'}, {3, 'Dealer3'}
ProductDealer (Id, ProductId (UK), DealerId, LastSale, Number):
{1, 1, 1, 5, '2012-12-10 12:34:31'},
{2, 2, 2, 120, '2012-11-10 12:34:31'},
{3, 5, 1, 75, '2012-12-02 12:34:31'}

So I going to create a full view of product, this is my first try:
SELECT
    [PR].[Id],
    [PR].[Name],
    [PR].[GroupId],
    [GR].[Title] AS [Group],
    [PR].[CategoryId],
    [CA].[Title] AS [Category]

FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]

Then I think to add ProductDealer columns to view, so I try this one:
SELECT
    [PR].[Id],
    [PR].[Name],
    [PR].[GroupId],
    [GR].[Title] AS [Group],
    [PR].[CategoryId],
    [CA].[Title] AS [Category],
    ISNULL(
    (SELECT [PD].[Id] FROM [dbo].[ProductDealer] AS [PD]
     WHERE [PD].[ProductId] = [PR].[Id]),
     CAST(-1 AS BIGINT)
    ) AS [ProductDealerId],
    ISNULL(
    (SELECT [DE].[Id] FROM [dbo].[Dealer] AS [DE]
    INNER JOIN [dbo].[ProductDealer] AS [PD] ON [DE].[Id] = [PD].[DealerId]
     WHERE [PD].[ProductId] = [PR].[Id]),
     CAST(-1 AS BIGINT)
    ) AS [DealerId],
     ISNULL(
    (SELECT [DE].[Name] FROM [dbo].[Dealer] AS [DE]
    INNER JOIN [dbo].[ProductDealer] AS [PD] ON [DE].[Id] = [PD].[DealerId]
     WHERE [PD].[ProductId] = [PR].[Id]),
     CAST('HaveNotDealer' AS NVARCHAR)
    ) AS [Dealer],
    ISNULL(
    (SELECT [PD].[LastSale] FROM [dbo].[ProductDealer] AS [PD]
     WHERE [PD].[ProductId] = [PR].[Id]),
    CAST('0001-01-01 00:00:01' AS DATETIME2)
    ) AS [LastSale],
    ISNULL(
    (SELECT [PD].[Number] FROM [dbo].[ProductDealer] AS [PD]
     WHERE [PD].[ProductId] = [PR].[Id]),
    CAST(0 AS BIGINT)
    ) AS [SaleNumber]

FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]

As you see for each column in ProductDealer I write a full select query I don't know is there any better way to do this? something like union this columns to first view, what is your suggestion to best implement it?
Update
In ProductDealer Table, the ProductId is UK, So each Product could have one dealer or nothing, I want if the product have a dealer get ProductDealer Columns in view and if not get my default values like: (-1, 'HaveNotDealer').

A: SELECT
    [PR].[Id],
    [PR].[Name],
    [PR].[GroupId],
    [GR].[Title] AS [Group],
    [PR].[CategoryId],
    [CA].[Title] AS [Category],
    ISNULL([PD].[Id],
    CAST(-1 AS BIGINT)) AS [ProductDealerId],
    ISNULL([D].Id,
    CAST(-1 AS BIGINT)) as DealerId,
    ISNULL([D].Name,
    CAST('HaveNotDealer' AS NVARCHAR)) as DealerName,
    ISNULL(PD.LastSale,
    CAST('0001-01-01 00:00:01' AS DATETIME2)) as LastSale,
    ISNULL([PD].Number,
    CAST(0 AS BIGINT)) as SaleNumber

FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
LEFT OUTER JOIN [dbo].[ProductDealer] AS [PD] ON [PR].[Id] = [PD].[ProductId]
LEFT OUTER JOIN [dbo].[Dealer] AS [D] ON [PD].DealerId = [D].Id

A: Perhaps only answering this question in "spirit", but this is the "Union Columns Vertically" answer I was looking for when I stumbled upon this Question =)
with aa(col1, col2) as (
    select * from (values (1,2) ) blah
),
 bb(col3, col4) as (
    select * from (values (5,6) ) blah
)

select select aa.col1, aa.col2, bb.col3, bb.col4
from aa , bb

Gives
col1|col2|col3|col4
1   |2   |5   |6

Disclaimer The above only works cleanly for single row aa , bb .

A: Here is the "vertical UNION" version:
WITH "Group"
     AS
     (
      SELECT *
        FROM (
              VALUES (1,'G1'), (2,'G2'), (3,'G3'), (4, 'G4')
             ) AS T (Id, Title)
     ),
     Category
     AS
     (
      SELECT *
        FROM (
              VALUES (1, 'Cat1'), (2, 'Cat2'), (3, 'Cat3'), (4, 'Cat4')
             ) AS T (Id, Title)
     ),
     Product
     AS
     (
      SELECT *
        FROM (
              VALUES (1, 1, 1, 'G1C1P1'),
                     (2, 1, 2, 'G1C2P2'),
                     (3, 1, 2, 'G1C2P3'),
                     (4, 2, 2, 'G2C2P4'),
                     (5, 2, 2, 'G2C2P5'),
                     (6, 3, 1, 'G3C1P6'),
                     (7, 3, 3, 'G3C3P7')
             ) AS T (Id, GroupId, CategoryId, Name)
     ),
     Dealer
     AS
     (
      SELECT *
        FROM (
              VALUES (1, 'Dealer1'), (2, 'Dealer2'), (3, 'Dealer3')
             ) AS T (Id, Name)
     ),
     ProductDealer
     AS
     (
      SELECT *
        FROM (
              VALUES (1, 1, 1, 5, '2012-12-10 12:34:31'),
                     (2, 2, 2, 120, '2012-11-10 12:34:31'),
                     (3, 5, 1, 75, '2012-12-02 12:34:31')
             ) AS T (Id, ProductId, DealerId, Number, LastSale)
     )
SELECT PR.Id, PR.Name, PR.GroupId, GR.Title AS "Group",
       PR.CategoryId, CA.Title AS Category,
       PD.Id AS ProductDealerId,
       D.Id DealerId,
       D.Name AS DealerName,
       PD.LastSale AS LastSale,
       PD.Number AS SaleNumber
  FROM Product AS PR
       JOIN "Group" AS GR ON PR.GroupId = GR.Id
       JOIN Category AS CA ON PR.CategoryId = CA.Id
       JOIN ProductDealer AS PD ON PR.Id = PD.ProductId
       JOIN Dealer AS D ON PD.DealerId = D.Id

UNION

SELECT PR.Id, PR.Name, PR.GroupId, GR.Title AS "Group",
       PR.CategoryId, CA.Title AS Category,
       PD.Id AS ProductDealerId,
       CAST(-1 AS BIGINT) DealerId,
       CAST('HaveNotDealer' AS NVARCHAR) AS DealerName,
       PD.LastSale AS LastSale,
       PD.Number AS SaleNumber
  FROM Product AS PR
       JOIN "Group" AS GR ON PR.GroupId = GR.Id
       JOIN Category AS CA ON PR.CategoryId = CA.Id
       JOIN ProductDealer AS PD ON PR.Id = PD.ProductId
 WHERE PD.DealerId NOT IN ( SELECT Id FROM Dealer )

UNION

SELECT PR.Id, PR.Name, PR.GroupId, GR.Title AS "Group",
       PR.CategoryId, CA.Title AS Category,
       CAST(-1 AS BIGINT) AS ProductDealerId,
       CAST(-1 AS BIGINT) DealerId,
       CAST('HaveNotDealer' AS NVARCHAR) AS DealerName,
       CAST('0001-01-01 00:00:01' AS DATETIME2) AS LastSale,
       CAST(0 AS BIGINT) AS SaleNumber
  FROM Product AS PR
       JOIN "Group" AS GR ON PR.GroupId = GR.Id
       JOIN Category AS CA ON PR.CategoryId = CA.Id
 WHERE PR.Id NOT IN ( SELECT ProductId FROM ProductDealer );

A: Like this:
SELECT
    [PR].[Id],
    [PR].[Name],
    [PR].[GroupId],
    [GR].[Title] AS [Group],
    [PR].[CategoryId],
    [CA].[Title] AS [Category],
    PD.ID AS ProductDealerID,
    PD.DealerId,
    DE.Name AS Dealer,
    PD.LastSale,
    PD.Number AS SaleNumber

FROM [dbo].[Product] AS [PR]
INNER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
INNER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
LEFT JOIN  ProductDealer AS [PD] ON PD.ProductId = PR.ID
LEFT JOIN  Dealer AS DE ON DE.ID = PD.DealerId


text:
Q: Rewarded Video Ads for Facebook Instant Game not working for me, but working for client I am developing a Facebook Instant Game for a client and my task is to integrate some Rewarded Video Ads.
I've already put the basic code which loads the video ads and my client says they are able to watch the videos successfully on their side.
However, I am unable to see it on my account / device. I always get the ADS_NO_FILL error.
As a test, I tried to play Video Ads from other Instant Games, but I also couldn't view them. My client however says that they're able to view ads on other Instant Games as well.
Would be nice if someone had an idea what could be going on. Is this expected? Is it normal to get ADS_NO_FILL all the time?
Here's the code I'm using just in case:
FBInstant.getRewardedVideoAsync(AD_PLACEMENT_ID).then((rewarded) => {

    // Load the Ad asynchronously
    DebugScreen.log('Load the Ad asynchronously');
    preloadedRewardedVideo = rewarded;
    return preloadedRewardedVideo.loadAsync();

}).then(() => {
    DebugScreen.log('Rewarded video preloaded..');

    preloadedRewardedVideo.showAsync().then(() => {
        // Perform post-ad success operation
        DebugScreen.log('Video watched successfully');
    }).catch((e) => {
        DebugScreen.log(e.message);
    });

}).catch((err) => {
    DebugScreen.log('Video failed to preload.. msg: ' + err.message + ', code: ' + err.code);
});


text:
Q: Reading Spark Dataframe from S3 Bucket While Another Process Writes to it? Would there be any issues reading a spark dataframe and say persisting it via a Jupyter notebook and another process writing to the s3 bucket concurrently?
Say,
I read a dataframe like:
 s3 = spark.read.parquet('s3://path/to/table')

And work on this in a notebook.
Concurrently I write out to the same s3 bucket at some point via a different process, e.g.
system('s3-dist-cp --src --dest s3://path/to/table)

Would this ever prove to be an issue? I am ok with messing up the read / dataframe but I would not want to block writing out to the bucket.

A: This will cause FNF exception on any action on the first DF that you read.
 s3 = spark.read.parquet('s3://path/to/table')

The first spark job that is involved in the above is listing leaf files and directories. As there was another process that was writing/ rewriting data, the paths would be stale.
Furthermore, the eventual consistency behavior of the S3 should also be considered.


text:
Q: jQuery Context Selector Discrepancy The challenge is to add a specific class to a specific button in a jQuery UI Dialog Box.
I have tested both of these and this will work:
$('button:contains("Add New")', $('#selectDialog').parent()).addClass('alternateButtonStyle');

This; however, will not work:
$('button:contains("Add New")', '#selectDialog:parent').addClass('alternateButtonStyle');

Why won't the second code sample work?

A: the :parent selector does not select the parent element, it just filters to elements that are a parent. It is the inverse of :empty.
http://api.jquery.com/parent-selector/
It won't work because it doesn't do what you think it does.
That use-case is also undocumented, your context selector should actually be a jquery object, just wrap it in $()
Undocumented functionality is likely to be broken without warning.


text:
Q: Finding maxima using Lagrange multipliers Finding maxima of $x^2+y^2+z^2$ subject to conditions $\frac{x^2}{4}+\frac{y^2}{5}+\frac{z^2}{25} = 1 $ and $z=x+y$
Now I form $F(x,y,z, \lambda_1 , \lambda_2 )= x^2+y^2+z^2 + \lambda_1(\frac{x^2}{4}+\frac{y^2}{5}+\frac{z^2}{25} - 1 ) + \lambda_2(z-(x+y)) = 0  $
Partially differentiating w.r.t x,y,z we get
$f_x = 2x + \lambda_1\frac{x}{2} + \lambda_2 = 0$
$f_y = 2y + \lambda_1\frac{2y}{5} + \lambda_2 = 0$
$f_z = 2z + \lambda_1\frac{2z}{25} - \lambda_2 = 0$
how do I solve ?


text:
Q: Why don't computers start loading the OS earlier in the boot process? I was reading an article referred to me from another thread on the Windows OS boot process, and while reading, I couldn't help but wonder --
When a computer turns on, why can't it start loading the OS earlier on in the boot process?
Regarding the gradual unfolding of a computer's boot processes from power-on -> OS loaded, why are there so many "hoops" to jump through in the boot process? It seems like the BIOS has to point to this location, this location can then read that location, that location can then load this location, this location runs this to load that location, etc., progressively higher and higher level. Even accessing a hard drive, it seems like there are multiple incarnations of "drivers" that need to be used until the highest-level drivers within the OS can take over.
I can sort of understand why it's necessary for a lifeless piece of machinery be able to go from a powerless, very low-level functionality and climb the ladder to higher functionality (with analogies like needing to start in lower gears to work up speed toward higher gears), but as far as computers go, I don't particularly understand the specifics of why it can't be done in less "hoops". I'd guess it's a large part of what the BIOS->UEFI transition is for -- a higher-level intermediary between powerless low-level hardware and higher-functioning OS abilities...?
I think I can catch the drift analogy-wise, but if anyone can provide specifics, it'd be much appreciated.

A: Because your OS is stored on disk.
You need to read it off it and put it into memory. Interacting with hardware is not easy. Interacting with them with high-performance is hard. So you do it awkwardly and slowly with BIOS services, then load your own drivers for disk access, then set up the rest of your OS stuff in memory. Meanwhile you NEED a display, to see what's happening and debug any issues. So you need to use BIOS services for that. Same for keyboard. And the network, if you want to boot off an installation image on the network. And a SCSI controller, if your boot disk is connected to it. And your CD/DVD drive, if you want to boot from it. And so on....
If there was a way to directly put the kernel + drivers into memory, then booting would immediately be a relic. And that day won't be far off, since we now have non-volatile RAM.
With UEFI, we have a more standard platform to build on. It will not be hard to have a non-volatile ram stick in the first slot, and normal DDR SDRAM in the others. The processor can be redirected to any memory location to execute by the firmware. The kernel initialization code can be kept at a specific location. The entire set up of registers and interrupts and drivers will take a fraction of a second if it's already in memory.
I await this day.


text:
Q: Replace XML field in Python I am trying to replace certain fields of an xml file in python, the xml file looks like this:
      ...
      <DialogEntry ID="179" IsRoot="false" IsGroup="false" NodeColor="Pink" DelaySimStatus="false" FalseCondtionAction="Block" ConditionPriority="Normal">
        <Fields>
          <Field Hint="(Wird Ingame nicht verwendet.)" Type="Text">
            <Title>Title</Title>
            <Value>Reaktion TS34 Antwort 2</Value>
          </Field>
          <Field Hint="The actor who is talking." Type="Actor">
            <Title>Actor</Title>
            <Value>2</Value>
          </Field>
          <Field Hint="The actor who is listening." Type="Actor">
            <Title>Conversant</Title>
            <Value>1</Value>
          </Field>
          <Field Hint="The text that is spoken by the actor." Type="Localization">
            <Title>Dialogue Text</Title>
            <Value>[Speaking]</Value>

          <Field Hint="Audiofile to play" Type="Text">
            <Title>Audio-File</Title>
            <Value />
          </Field>

        </Fields>
        <ReviewerNotes />
        <ReviewerStatus>None</ReviewerStatus>
        <OutgoingLinks />
        <ConditionsString />
        <UserScript />
      </DialogEntry>
    </DialogEntries>

Please note that the xml file consists of multiple DialogEntries and there are more Fields than the ones shown but what I want to do is: For a certain DialogEntry ID for example 179 I want to replace: <Title>Audio-File</Title>...<Value /> with generic text like <Title>Audio-File</Title>...<Value>Audiofile_XYZ.mp3</Value>
I have been trying with regular expressions, somethingl like this:
  r1 = re.compile("<DialogEntry ID=\"%d\".*?<Title>Audio-File</Title>\n {16}<Value />" % (id_to change),re.DOTALL)
  r2 = re.compile("<DialogEntry ID=\"%d\".*?<Title>Audio-File</Title>\n {16}<Value>%s</Value>"  % (id_to change, filename), re.DOTALL)
  content = re.sub(r1,r2 ,content)

but I am stuck because it's not working as expected.
The problems I have are:

*

*Making the RE match multiple lines(re.DOTALL seams only to work with precompiled REs for re.sub())

*The indicator ID and the part to replace are quite far away and there is a lot of dynamic text inbetween, how can I identify the correct DialogueEntry and still replace only the part I want to change without having to deal with the Titles between Audio-File and ID

Can you please help me out or show me a more appropritate way to do these changes?
Regards,
BPR

A: You should probably consider a more appropriate medium for your transformations: XML -> text -> XML is doomed to failure / unnecessary complexity for non-trivial problems.
Perhaps it'd be best to parse the file using the ElementTree XML API (consider using lxml if performance is important). Then you can modify the XML representation for your <Value/> nodes in the tree using the API, and then write to an output file.
Alternatively, outside of Python completely (or almost completely, depending how you invoke it), you could even just use XSLT to transform this XML to slightly different XML; that's what it was designed for after all.


text:
Q: Trying to generate a simple password generator in C#. This is what I have so far. Trying to get the console to print out what the user has picked I can't seem to figure out how to print out what the user has entered for their password once their finished answering the questions.
I want to use 4 different for loops for upperCase, lowerCase, numbers, symbols,based on what the user has entered. If anyone has any different ideas please share. It would be a great help. I'm new to programming.
Here is what I have so far
string upperCase = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ;
string lowerCase = ("abcdefghijklmnopqrstuvwxyz");
string numbers = ("1234567890" );
string specChac = ("!@#$%^&*():<>?/");
string randomPassword = upperCase + lowerCase + numbers + specChac;
string allPasswords = "randomPassword";
Random rnd = new Random();

Console.WriteLine("Welocme to the C# password generator! ");
Console.WriteLine("----------------------------------------");

Console.WriteLine("How many uppercase letters would you like in your password ?");
int upperAmount = int.Parse(Console.ReadLine());

Console.WriteLine("How many lowercase letters would you like in your password ?");
int lowerAmount = int.Parse(Console.ReadLine());

Console.WriteLine("How many numbers would you like in your password ?");
int numAmount = int.Parse(Console.ReadLine());

Console.WriteLine("How many special characters would you like in your password?");
int charAmount = int.Parse(Console.ReadLine());

A: Well, there are many many ways on how to implement that.
Here is one showing the concept of seeding.
Instead of defining the possible characters I just assign the possible minimum and maximum ASCII character code.
You can do it however you want.
internal static class RandomPswd
{
    const int CHAR_UPPER_MIN = 0x41;
    const int CHAR_UPPER_MAX = 0x5a;
    const int CHAR_LOWER_MIN = 0x61;
    const int CHAR_LOWER_MAX = 0x7a;
    const int CHAR_DIGIT_MIN = 0x30;
    const int CHAR_DIGIT_MAX = 0x39;
    const int CHAR_SYMBL_MIN = 0x21;
    const int CHAR_SYMBL_MAX = 0x2f;

    private static void Shuffle(char[] buffer)
    {
        int seed = GetSeed();
        Random r = new Random(seed);

        int n = buffer.Length;
        while (n > 1) {
            int k = r.Next(n--);
            char t = buffer[n];
            buffer[n] = buffer[k];
            buffer[k] = t;
        }
    }

    private static int GetSeed()
    {
        unchecked
        {
            int hash = (int)DateTime.Now.Ticks * 7302013 ^ Environment.UserName.GetHashCode();
            hash = hash * 7302013 ^ (CHAR_UPPER_MIN.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_UPPER_MAX.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_LOWER_MIN.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_LOWER_MAX.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_DIGIT_MIN.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_DIGIT_MAX.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_SYMBL_MIN.GetHashCode());
            hash = hash * 7302013 ^ (CHAR_SYMBL_MAX.GetHashCode());
            return hash;
        }
    }

    public static string Create(int upper, int lower, int digits, int symbols)
    {
        char[] upperChars = new char[upper];
        char[] lowerChars = new char[lower];
        char[] digitChars = new char[digits];
        char[] symblChars = new char[symbols];

        int seed = GetSeed();
        Random r = new Random(seed);
        for (int i=0; i<upper; i++) {
            upperChars[i] = (char)r.Next(CHAR_UPPER_MIN, CHAR_UPPER_MAX);
        }

        seed = GetSeed();
        r = new Random(seed);
        for (int i = 0; i < lower; i++) {
            lowerChars[i] = (char)r.Next(CHAR_LOWER_MIN, CHAR_LOWER_MAX);
        }

        seed = GetSeed();
        r = new Random(seed);
        for (int i = 0; i < digits; i++) {
            digitChars[i] = (char)r.Next(CHAR_DIGIT_MIN, CHAR_DIGIT_MAX);
        }

        seed = GetSeed();
        r = new Random(seed);
        for (int i=0; i< symbols; i++) {
            symblChars[i] = (char)r.Next(CHAR_SYMBL_MIN, CHAR_SYMBL_MAX);
        }

        char[] buf = new char[upper + lower + digits + symbols];
        upperChars.CopyTo(buf, 0);
        lowerChars.CopyTo(buf, upper);
        digitChars.CopyTo(buf, upper + lower);
        symblChars.CopyTo(buf, upper + lower + digits);
        Shuffle(buf);

        return new string(buf);
    }
}

static void Main()
{
    var pw = RandomPswd.Create(12, 8, 7, 5);
}


text:
Q: How to solve html form submission with input containing "select from" keywords? This issue is being represented only on server-side and not localhost.
When submitting a simple form with one textarea containing the two keywords "select" and "from" in this order, or even separated with multiple words; the form submission is showing the following error:

Internal Server Error
The server encountered an internal error or misconfiguration and was
  unable to complete your request.
Additionally, a 500 Internal Server Error error was encountered while
  trying to use an ErrorDocument to handle the request.

This error has been generated even with the following sentence: "The selection of this team will be from the list ...", since "selection" contains the word "select" in it and followed by "from" keyword.
The only temporary solution is to use "select" or "from" capitalized to prevent the internal server error. However, this is not what I need. I need to solve it with a reasonable solution.

A: If the problem is on server side it may depend on the method you use to submit form data.
First, please carefully check documentation here.

The GET Method
GET is used to request data from a specified resource.
The POST Method
POST is used to send data to a server to create/update a resource.
The PUT Method
PUT is used to send data to a server to create/update a resource.

A: This is usually caused by the firewall of your server. To solve it you need to check the error log file and see what is the error provided, then you will have to add an exception for this error.
If you find it hard to be done, you can contact the support of your server and they can do it for you. Hope this can help.


text:
Q: SharePoint ACL on OSX Lion Server - Posix group always takes over ACLs Trying to configure a SharePoint on a Lion Server machine.
The directory is created by the local server admin (serveradmin) and has rwxr-x--- given to it.
The serveradmin user belongs to the local staff group so
serveradmin readwrite
staff group read
Others      none

We have an OD group for all the employees (Workers) . Using the Server tool we've given Full Control to the SharePoint:
Workers     Full Control
serveradmin readwrite
staff group read
Others      none

We would assume that Workers could then do what they want on the share but that doesn't seem to be the case. It appears the POSIX permissions take over the ACL permissions for Worker.
If I change the staff permission to readwrite then the Workers can create a file or folder in SharePoint.
I would think the ACL should take over but it doesn't, posix always win, rendering ACL useless.
Furthermore, if I leave the readwrite permission for staff and take Write permission away for the Workers group then the posix group still wins. Essentially the Workers ACL does absolutely nothing.
There are reports of similar problems in this Apple forum thread: https://discussions.apple.com/thread/3722901
The directory nesting fix suggested there doesn't work for us.
Has anyone had similar issues and know how to fix this?
Edit: in Workgroup Manager the employees user are set to primary group staff and given the additional OD group Workers. Changing their primary group doesn't help, it only shifts the problem onto Others taking over rights (logically)
Edit 2: Ok, this is interesting, adding OD Users to the share's ACL works totally fine

A: I'm going to post this as an answer because this workaround fixes all access issues for us.
We've basically stopped trying OD Groups for permissions altogether.
It works perfectly if we add OD Users to the share and propagate down (after resetting all ACL to clean up the previous mess).
When we give permissions based on Users everything works fine as expected and the ACL takes over the posix permissions.
Really not sure why the group doesn't work. We thought it might be because the OD group doesn't match a local group on the respective client machine but creating an explicit local group doesn't seem to fix it (though we only tried matching the group name, not the gid).
Anyway, hope this helps someone.
A side note: It use to work perfectly fine on Snow Leopard server, this is just on Lion server.


text:
Q: Django contrib problems showing blank templates Im trying to deploy an application i made with Django on a Ubuntu 10 Server with mod_wsgi and Apache.
Everything seems to be all right, but, when i try to use the django admin nothing is showed. I inspect the html, and is a bank html :

I thought was only a admin problem, but i discovered it actually happends when i try to use the django.contrib auth login... so.. i tried a lot of thing, permissions, moving admin tempaltes... etc..
any ideas??
thank you a lot!!

A: Are you sure Apache can find the directory where the admin static media is located? I recall having a similar problem in the past, and solved it by creating a symbolic link for it inside my media directory:
mgibsonbr@***(~/***/media)$ ls -l
total 4K
lrwxr-xr-x 1 mgibsonbr users  87 Nov 18 14:29 admin -> /home/mgibsonbr/***/lib/python2.5/site-packages/django/contrib/admin/media

My httpd.conf:
DocumentRoot /home/mgibsonbr/www/***
Alias /media/ /home/mgibsonbr/www/***/media/

WSGIDaemonProcess *** user=mgibsonbr group=users threads=5
WSGIProcessGroup ***
WSGIScriptAlias / /home/mgibsonbr/www/***.wsgi

And my Django settings.py:
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/'

Note: some parts anonymized
If you haven't done any programming mistakes, maybe you could ask this question in serverfault.com, they'll probably be able to better help you there.


text:
Q: How to map a subdomain to a servlet I have a Google App Engine project that consists of multiple modules, with each module serving as a microservice. Each module is located at the project's root level and has its own web.xml file.
I am familiar with how the servlet spec works and can map a servlet to a relative path:
<servlet>
    <servlet-name>accounts</servlet-name>
    <servlet-class>com.myapp.accounts.DatastoreServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>accounts</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

But if I use any domain in my browser that gets directed to my web app, the servlet above will be executed. What I really want is that the servlet only launches for the subdomain:
https://accounts.myapp.com

and not for some other domain like:
https://users.myapp.com

Is there a way to specify this in the web.xml file? According to the servlet 3.1 spec:

The empty string ("") is a special URL pattern that exactly maps to
  the application's context root, i.e., requests of the form
  http://host:port//. In this case the path info is '/'
  and the servlet path and context path is empty string ("").

But this does not indicate any support for a subdomain.

A: Mapping to specific domains is not supported, but you can use request.getServerName() and return 404 if you don't like what it returns for the same effect.
Note that in http the server name is technically optional (the value is in the Host header). In practice it is always sent unless the server is accessed via the IP address (ie: URL http://<ip address>).

A: Please update your DNS with *.yourdomain.com and save the subdomains in your database once the request coming to the specific subdomain get the subdomain using request.getServerName().split("\\.")[0]
and check in DB and map the result as per the subdomain.


text:
Q: Entity Framework stored procedure result I can have stored procedure return a collection of existing entities. How do I join/include other entities in this scenario? Is this even possible?

A: Would something along these lines suffice?
var joinResult = (from product in dbContext.sp_GetProducts()
                 join cat in dbContext.ProductCategory on product.catID equals cat.ID
                 select new { product = product, category = cat }).ToList();

Alternatively you could do the joining inside of the store procedure.


text:
Q: DNN DAL 2 hydrate object and other Using basic DAL 2 to grab data from a table that has tabid. Would like to also get the Tab Url through the DNN API. I could join to the Tabs table, but want to work with the api.
Here is my model.

[TableName("My_Products")]
    [PrimaryKey("ProductId")]
    [Cacheable("My_Products_", CacheItemPriority.Normal, 20)]

    public class ProductInfo
    {
        public ProductInfo()
        {
            Langs = new List<ProductLangInfo>();
        }
        public int ProductId { get; set; }
        [ReadOnlyColumn]
        public string ProductImage { get; set; }
        public int LineID { get; set; }
        [ReadOnlyColumn]
        public string Culture { get; set; }
        [ReadOnlyColumn]
        public string ProductName { get; set; }
        [ReadOnlyColumn]
        public string ProductShortDesc { get; set; }
        [ReadOnlyColumn]
        public int TabId { get; set; }
        [ReadOnlyColumn]
        public string ProductURL { get; set; } //GET THIS FROM API
        [ReadOnlyColumn]
        public List<ProductLangInfo> Langs { get; set; }
    }

This is my Controller

 public IEnumerable<ProductInfo> GetProducts(string language)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                string sqlCmd = ";WITH cte as (SELECT * FROM [ProductsLang] WHERE Culture = @0)" +
                                " SELECT Products.*,cte.ProductName, cte.ProductShortDesc, cte.TabId" +
                                " FROM [Products] as Products" +
                                " INNER JOIN cte ON Products.ProductId = cte.ProductId";

                string order = " ORDER BY Products.ProductId DESC";
                return ctx.ExecuteQuery<ProductInfo>(CommandType.Text, sqlCmd + order, language);
            }
        }

I guess my question is where is the best way to pass in the tabid from my query to the DNN API?

A: This should be fairly straightforward using the NavigateURL method off DotNetNuke.Common.Globals
var url = DotNetNuke.Common.Globals.NavigateURL(TabId);

There are other ways to get URLs in DNN, but that is the easiest way that should respect all the various Providers that can be used to build out a URL
private string _productUrl = '';
public string ProductURL { get return DotnetNuke.Common.Globals.NavigateURL(TabId);  }


text:
Q: Subclassed UITableView I want a subclass of UITableView that paints custom Section headers. I tryed as follows:
#import <UIKit/UIKit.h>
@interface MyTableView : UITableView
@end
@implementation MyTableView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  //my drawing code goes here
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
  //returns the height
}
@end

However when I use this class it draws the normal headers. What am I doing wrong?
When I Set those functions directly into a controller (without subclassing) it works fine.
UPDATE:
I already have many classes that use UITableView, I want to subclass it because it may be faster  to just change the class that writing the needed classes. How can I change the titles by just changing the class, is it possible?

A: This is happening because you inherited the UITableView class and this methods are not from UITableView, they are from the UITableViewDelegate.
It works on your controller because either you have set the delegate property of your UITableView pointing to your controller, or you are using a UITableViewController, which has the tableview delegate set automatically. (Actually, in your case, using a UITableViewController is worse because it already implements UITableView instead of your custom class).
EDIT: Unfortunately, due to the delegation pattern used in UITableView class to change its section header views, it is not straightforward to implement this kind of action
One way of doing that is providing these "helper" methods in your class, and then implement the delegate on each of your controllers to call these methods properly when the delegate method is fired.
If this approach is acceptable you should even consider using a category with these methods instead of subclassing you UITableView, which would make the code much cleaner.
Obviously you could set the UITableView delegate to be your custom class and then create another delegate for the calls you still want to be fired to the controller, such as cellForRowAtIndexPath, and then call this new delegate methods as soon as the tableview fires the methods, but this is by far the worst possible solution

A: I don't understand why you are implementing TableView and not MyTableView:
@implementation MyTableView

UPDATE:
Check if you set correctly dataSource and delegate properties of that table.
UPDATE2:
You should subclass from UITableViewController:
@interface MyTableView : UITableViewController
@end

A: You could subclass UITableViewController, handling the viewForHeaderInSection and heightForHeaderInSection, then use MyTableViewController as the base class for each table view that you want to have your custom headers. However, viewForHeaderInSection is going to need to have the information necessary to create the UILabel or whatever you are going to use to display a header, so you are going to need some consistent code in your subclasses that will provide that - like an NSArray filled with the strings that you want for the headers, or a method that can be called from viewForHeaderInSection.


text:
Q: Groupby, transpose and top 5 python I have a dataframe like this:
d = {'col1': ['Category1', 'Category1','Category1', 'Category1','Category1', 'Category2','Category2', 'Category2','Category2', 'Category2',],
 'col2': ['Type1', 'Type2','Type3','Type4','Type5','Type1', 'Type2','Type3','Type4','Type5'],
 'col3':[32,44,87,10,12,10,14,800,3200,35]}

df_test = pd.DataFrame(data=d)

df_test

col1        col2    col3
Category1   Type1   32
Category1   Type2   44
Category1   Type3   87
Category1   Type4   10
Category1   Type5   12
Category2   Type1   10
Category2   Type2   14
Category2   Type3   800
Category2   Type4   3200
Category2   Type5   35

What I'd like to get is the two rows Category 1 and Category 2 containing the sorted 3 largest Type based on col3 numbers. So the output would look like this:
col1       order1  order2  order3
Category1  Type3   Type2   Type1
Category2  Type4   Type3   Type5

I've tried:
df_test=df_test.groupby(['col1']).apply(lambda x: (x.groupby('col2')
                                      .sum()
                                      .sort_values('col3', ascending=False))
                                      .head(3)).T

And other different ways with no success.
Any ideas? Thank you

A: df_test['col3'] = df_test.groupby('col1')['col3'].rank(ascending = False)
df1 = df_test.query('col3 <= 3').reset_index(drop = True)
df1['col4'] = 'order' + df1['col3'].astype(int).astype(str)
df1.pivot('col1', 'col4', 'col2').reset_index()

col3       col1 order1 order2 order3
0     Category1  Type3  Type2  Type1
1     Category2  Type4  Type3  Type5

A: df_t = df.pivot(columns='col2', index='col1')
df_t = df_t.apply(lambda s: [x[1] for x in s.nlargest(3).index], axis=1)
print(df_t)

Output:
col1
Category1    [Type3, Type2, Type1]
Category2    [Type4, Type3, Type5]
dtype: object


text:
Q: Probability of getting a number with two identical digits I have a fairly simply question which I am not sure about. A 3 digits number is being chosen by random (100-999). What is the probability of getting a number with two identical digits ? (like 101). Thank you !

A: There are $900$ numbers. all equally likely. We now count the favourables, the ones with exactly two identical digits.
It is clear by symmetry that there is the same number from $100$ to $199$ as there is from $200$ to $299$, as there is from $300$ to $399$ and so on.
We count the number from $800$ to $899$, and multiply by $9$.
Maybe the repeated digit is $8$, in which case the second occurrence can be at any of $2$ places. There are then $9$ choices for the third digit, for a total of $(2)(9)$.
Or maybe it  is the last $2$ digits that repeat. That gives $9$ possibilities.
Thus the total number of favourables is $9\left((2)(9)+9\right)$.

A: The best way to approach these problems is to make lists of what could happen, and pick numbers one by one.
So the first number must be 1-9 The second number must be 0-9. (No restrictions so far.)
But we have to pick the third number carefully. If the first two numbers matched, we must pick a different number for the last one. If the first two did NOT match, we must copy one of these two for the last number.
So for this last step, we split into two cases (how many numbers can we pick the first two match, and how many numbers can we pick the first two not matching), and then add these together at the end. If you do so, you should get an answer similar to the one posted in comments.

A: There are ten numbers of the form aa*.  9 of them are not aaa. There are 9 possible chooses for a.  So there are 81 numbers where the first two digits are the same.
By exact same reasoning there are 81 numbers where where the first and last digit are the same.
Counting the numbers where the last two digits are the same is a little different.  If we ignore *00 numbers for now there are 81 numbers by the same argument above. Except we can not count the number 0aa.  So that's only 72.  But we also have  9 *00 numbers. So there are 81 after all.  So there are 81 numbers where the last two digits are the same.
So there are 243 numbers with exactly 2 digits the same.


text:
Q: Fourier Integral Representation of $H(t)-\frac{1}{2}$ I know that the following theorem holds

Fourier's Integral Theorem. Suppose $f:\mathbb{R}\to\mathbb{R}$ is piece-wise continuous on $\mathbb{R}$ and at every point $x$ the right and left derivatives exist. Also, assume that $f$ satisfies $\int_{-\infty}^{+\infty}|f(t)|dt<+\infty$. Then the following holds
  \begin{align*}
\frac{1}{2}\big(f(t^+)+f(t^-)\big)&=\int_{0}^{+\infty}(A(\omega)\cos(\omega t)+B(\omega)\sin(\omega t))dt \\
A(\omega)&=\frac{1}{\pi}\int_{-\infty}^{+\infty}f(t)\cos(\omega t)dt \\
B(\omega)&=\frac{1}{\pi}\int_{-\infty}^{+\infty}f(t)\sin(\omega t)dt
\end{align*}

Assume that $H(t)$ is the usual Heaviside or unit-step function. I saw in some text that the Fourier integral representation of
$$f(t):=H(t)-\frac{1}{2}=
\begin{cases}
+\frac{1}{2},\quad t\gt 0 \\
-\frac{1}{2},\quad t\lt 0
\end{cases}$$
can be given by
$$f(t)=\frac{1}{\pi}\int_{0}^{+\infty} \frac{\sin \omega t}{\omega} d\omega \tag{1}$$
however, the function $f(t)$ does not satisfy the condition $\int_{-\infty}^{+\infty}|f(t)|dt<+\infty$ of the Fourier integral theorem and when one tries to compute its Fourier integral representation will see that $A(\omega)=0$ but $B(\omega)=\lim_{R\to+\infty}\frac{1}{\pi\omega}\sin\omega R$ which does not exist! So, here are my questions

How can I derive $(1)$? I heard that this can be derived by using the generalized functions but I have no idea what this really means. Can someone explain the main idea of this for me? Please put it simple for someone with little knowledge of elementary analysis! :)

A: Note that
$$f(t):=H(t)-\frac{1}{2}=
\begin{cases}
+\frac{1}{2},\quad t\ge 0 \\
-\frac{1}{2},\quad t\lt 0
\end{cases}$$
is essentially $\dfrac{1}{2}\mathrm{sgn}(t)$.
The Inverse Fourier Transform, in the limit, of $\dfrac{1}{\omega}$ is (some constant times) $\mathrm{sgn}(t)$.  Often, solving a(n Inverse) Fourier Transform in the limit does involve generalized functions, which are sequences of functions in a limit.  However, this particular Inverse Fourier Transform can be solved with a contour integration in the complex plane.
Starting with an integral similar to your integral (1), but which looks more like a standard Inverse Fourier Transform:
$$\begin{align*}g(t)&=-\frac{1}{2\pi i}\int_{-\infty}^{+\infty} \frac{e^{i \omega t}}{\omega} d\omega \tag{A}\\
\end{align*}$$
This integral, like your integral (1), has a problem with the infinite discontinuity of $\dfrac{1}{\omega}$ at $\omega = 0$.
To deal with that infinite discontinuity, rewrite the integral as
$$g(t) = -\dfrac{1}{2\pi i}\lim_{\epsilon \rightarrow 0}\left(\int_{-\infty}^{-\epsilon} \frac{e^{i \omega t}}{\omega} d\omega + \int_{+\epsilon}^{+\infty} \frac{e^{i \omega t}}{\omega} d\omega \right)$$
To solve the above expression, use the following contour integral
$$\int_{C} \dfrac{e^{i z t}}{z} dz$$
where the contour $C$ is a semicircle of radius $R$ in the complex plane, with its diameter along the real axis ($\omega$), and with a small indentation of radius $\epsilon$ at the origin.  The value of the contour integral is $0$, since there are no enclosed poles.
Breaking the contour integral into 4 segments:
$$\int_{-R}^{-\epsilon}\dfrac{e^{i\omega t}}{\omega}d\omega + \int_{\pi}^{0} i\epsilon e^{i\theta}\dfrac{e^{it\epsilon e^{i\theta}}}{\epsilon e^{i\theta}} d\theta + \int_{+\epsilon}^{+R}\dfrac{e^{i\omega t}}{\omega}d\omega + \int_{0}^{\pi} iR e^{i\theta}\dfrac{e^{itR e^{i\theta}}}{R e^{i\theta}} d\theta =0$$
Taking the limit as $R \rightarrow \infty$, the fourth integral goes to $0$.
Taking the limit as $\epsilon \rightarrow 0$, the second integral goes to $i\pi\, \mathrm{sgn}(t)$
This leaves
$$\lim_{\epsilon \rightarrow 0}\left(\int_{-\infty}^{-\epsilon}\dfrac{e^{i\omega t}}{\omega}d\omega + \int_{+\epsilon}^{+\infty}\dfrac{e^{i\omega t}}{\omega}d\omega \right)+ i\pi\, \mathrm{sgn}(t)=0$$
So
$$ g(t) = -\dfrac{1}{2\pi i}\lim_{\epsilon \rightarrow 0}\left(\int_{-\infty}^{-\epsilon}\dfrac{e^{i\omega t}}{\omega}d\omega + \int_{+\epsilon}^{+\infty}\dfrac{e^{i\omega t}}{\omega}d\omega \right) = \dfrac{1}{2}\mathrm{sgn}(t)$$
I'm not happy with that negative sign out front. I think I have a sign mistake.  When I manipulate my integral (A) to try and get to your integral (1) I end up with
$$\begin{align*}g(t)&=-\frac{1}{2\pi i}\int_{-\infty}^{+\infty} \frac{e^{i \omega t}}{\omega} d\omega\\
&= -\frac{1}{2\pi i}\int_{-\infty}^{+\infty} \frac{\cos(\omega t)}{\omega} +\frac{i\sin(\omega t)}{\omega} d\omega \\
&= -\frac{1}{2\pi i}\int_{-\infty}^{+\infty} \frac{i\sin(\omega t)}{\omega} d\omega \\
&= -\frac{1}{\pi}\int_{0}^{+\infty} \frac{\sin(\omega t)}{\omega} d\omega \\
\end{align*}$$
Which is close to your integral (1) except for the minus sign.

A: $\newcommand{\inner}[1]{\langle #1 \rangle}$
You have to view (1) in terms of Schwartz's distribution theory, c.f. http://web.abo.fi/fak/mnf/mate/kurser/fourieranalys/chap3.pdf for a brief overview. Key points needed here are:
1) The Dirac delta distribution $\delta$ (usually called a function, but it is not one) is a distribution such that for all test functions $\phi\in \mathcal{S}$ (the space of Schwartz function) we have $$\inner{\delta, \phi}=\int_\mathbb{R} \delta(t)\phi(t)dt=\phi(0).$$
2) We say a tempered distribution $F$ is induced by a function $f$ (which has to satisfy some suitability conditions conditions that we won't get into here) when we have for all test functions $\phi$:
$$F(\phi)=\inner{f, \phi} := \int_\mathbb{R} f(t) \phi(t)dt.$$
3) We defined the derivative of $F$ via the following:
$$F'(\phi):=\inner{f',\phi}=-\inner{f, \phi'}.$$ The second equality can be derived using integration by parts.
4) The Fourier transform of a distribution $F$ is defined by $$\widehat{F}(\phi)=\inner{\widehat{f}, \phi}=\inner{f, \widehat{\phi}}.$$
5) The Fourier transform derivative formulas hold.
Viewing the Heaviside function as a distribution, we have that $$\inner{H', \phi} = -\inner{H,\phi'} = -\int_\mathbb{R} H(t)\phi'(t)dt = -\int_0^\infty \phi'(t)dt = \phi(0) = \inner{\delta, \phi}.$$ Hence, the delta distribution is the derivative of the Heaviside function. More importantly in this context, it is then the derivative of the Heaviside function minus a half.
If we compute the Fourier transform of $\delta$ (using my favorite convention, and I would argue the correct convention)  we have
$$\widehat{\delta}(\gamma)=\int_\mathbb{R} \delta(t)e^{-2\pi i \gamma t}dt=\inner{\delta, e^{-2\pi i\gamma t}}=e^{-2\pi i \gamma 0}=1.$$
Using the Fourier derivative formulas for this convention, we then have
$$(H-1/2)\widehat{}(\gamma) = ((H-1/2)')\widehat{}\frac{1}{2\pi i \gamma} = \widehat{H'}(\gamma)\frac{1}{2\pi i \gamma}=\frac{\widehat{\delta}}{2\pi i \gamma}=\frac{1}{2\pi i \gamma}.$$
Applying the Fourier inversion formula leaves us with $$H(t)-1/2 = \int_\mathbb{R} \frac{e^{2\pi i \gamma t}}{2\pi i \gamma} d\gamma=\int_0^\infty \frac{e^{2\pi i \gamma t}-e^{-2\pi i \gamma t}}{2\pi i \gamma} d\gamma = \int_0^\infty \frac{\sin(2\pi \gamma t)}{\pi \gamma} d\gamma.$$ Substituting $\omega=2\pi \gamma$ yields your formula (1). To actually compute the integral in (1) you can do this using contour integrals.


text:
Q: Description of $\mathbb Z/p^2\mathbb Z$ as an extension of $\mathbb Z/p\mathbb Z$ The ring $\mathbb Z/p^2\mathbb Z$ has $\mathbb Z/p\mathbb Z$ as an ideal, with a quotient ring again isomorphic to $\mathbb Z/p\mathbb Z$. Is there a way to describe the structure of $\mathbb Z/p^2\mathbb Z$ based on this observation?
I tried writing elements of $\mathbb Z/p^2\mathbb Z$ as $kp+i$ with $0\leq k, i\leq p-1$. This representation is unique, and it's not difficult to get expressions for the representation of a sum and product of two elements expressed with that representation. But the problem is that we don't have $kp+i\equiv k'+pi'\mod p^2$ if and only if $k\equiv k'\mod p$ and $i\equiv i'\mod p$, so I can't see how to actually use this to describe the structure  of $\mathbb Z/p^2\mathbb Z$.

A: The ring $A=\mathbb Z/p^2\mathbb Z$ has an ideal $I=(p)$ which is nilpotent and, in fact, has square zero. The quotient $A/I$ is isomorphic to $\mathbb Z/p\mathbb Z$ and we therefore have what is sometimes called an infinitessimal extension of rings $$0\to I\to A\to A/I\to 0$$ There is a whole theory dealing with such extensions, and they are classified using MacLane cohomology (the original reference is [S. MacLane. Homologie des anneaux et des modules. Coll. Topologie Algébrique (1956), pp. 55–80 Louvain]

A: Forgive me for writing $\mathbb{Z}_n$ to mean $\mathbb{Z} / n \mathbb{Z}$ below.
The funny thing about the cyclic rings, namely $\mathbb{Z}$ and the rings $\mathbb{Z}_n, n \in \mathbb{N}$, is that their multiplicative structure is completely determined by their additive structure (together with the data of which element is $1$). In fact each of these rings is canonically isomorphic to the endomorphism ring of its underlying abelian group. More generally, if $R$ is a commutative ring and $R/I$ a quotient of it, then $R/I$ as an $R$-algebra is canonically isomorphic to the endomorphism $R$-algebra of $R/I$ as an $R$-module.
So everything you need to know about $\mathbb{Z}_{p^2}$ as a ring is contained in the data of $\mathbb{Z}_{p^2}$ as an abelian group, and so you can use the language of group extensions and cohomology. In fact abelian extensions of abelian groups are completely described by the Ext functor, and the fact that the extension
$$0 \to \mathbb{Z}_p \to \mathbb{Z}_{p^2} \to \mathbb{Z}_p \to 0$$
does not split reflects the fact that the group $\text{Ext}^1(\mathbb{Z}_p, \mathbb{Z}_p)$ is nonzero (in fact it's $\mathbb{Z}_p$ again).

A: The structure of the ring $\mathbb Z/p^2\mathbb Z$ is the same as the structure of the group $\mathbb Z/p^2\mathbb Z$ and both can be extracted from the canonical projection $\mathbb Z \to \mathbb Z/p^2\mathbb Z$ which has kernel $p^2\mathbb Z$.
As a group, $\mathbb Z/p^2\mathbb Z$ is cyclic and cannot be written as the product of two smaller groups.


text:
Q: How to navigate cursor with TabIndex by click on button in wpf? <Grid x:Name="LayoutRoot">
    <Button x:Name="BtnNavigateTabIndex" Content="NavigateTabIndex" Margin="152,200,0,190" HorizontalAlignment="Left" Width="120"/>
    <TextBox x:Name="TextBox_1" HorizontalAlignment="Left" Height="48" Margin="120,64,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="80"/>
    <TextBox x:Name="TextBox_2" HorizontalAlignment="Left" Height="48" Margin="120,128,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="80"/>
    <PasswordBox x:Name="PasswordBox_1" HorizontalAlignment="Left" Height="48" Margin="224,64,0,0" VerticalAlignment="Top" Width="72"/>
    <PasswordBox x:Name="PasswordBox_2" HorizontalAlignment="Left" Height="48" Margin="224,128,0,0" VerticalAlignment="Top" Width="72"/>
</Grid>

The design will will be like below.

If i click the button(NavigateTabIndex),The cursor should be navigate to TextBox or PasswordBox.
For EX: If you click the Tab Key in you Keyboard,the cursor would navigate.This is the scenario what i need .

A: In general there are a lot of gotchas with WPF focussing....some bugs even.
You need to understand the difference between Logical and Keyboard focus.

*

*http://msdn.microsoft.com/en-us/library/aa969768.aspx
When using FocusScopes you can use:
MoveFocus with a TraversalRequest(FocusNavigationDirection.Next)
to change the logical focus to the next item in the scope.
An alternative to using FocusScopes is to track the GotFocus/LostFocus events and manage it yourself.
Some more links:

*

*How to programmatically navigate WPF UI element tab stops?

*Move focus in response to keyboard events in XAML

*WPF FocusNavigationDirection, MoveFocus and Arrow keys

*Locating the first WPF tab stop

*http://www.codeproject.com/Articles/38507/Using-the-WPF-FocusScope

Ok here's some example code for you. I took the liberty to redesign your use of the Grid a bit, to follow more conventional layout practice.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication5
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnNavigateTabIndex_Click(object sender, RoutedEventArgs e)
        {
            UIElement focussedelement = FocusManager.GetFocusedElement(grid1) as UIElement;

            bool bmovedfocus = focussedelement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

            if (bmovedfocus)
            {
                UIElement withfocusnow = FocusManager.GetFocusedElement(grid1) as UIElement;

                if (withfocusnow == focussedelement) // focus didn't change! because end of focus group..need to put it back to the start
                {
                    TextBox_1.Focus();
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TextBox_1.Focus();
        }
    }
}

    <Window x:Class="WpfApplication5.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication5"
            Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
        <StackPanel>
            <Grid x:Name="grid1" FocusManager.IsFocusScope="True">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <TextBox Margin="10" Grid.Row="0" Grid.Column="0" x:Name="TextBox_1" HorizontalAlignment="Left" Height="48" TextWrapping="Wrap" VerticalAlignment="Top" Width="80"/>
                <PasswordBox Margin="10" Grid.Row="0" Grid.Column="1" x:Name="PasswordBox_1" HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="72"/>
                <TextBox Margin="10" Grid.Row="1" Grid.Column="0" x:Name="TextBox_2" HorizontalAlignment="Left" Height="48" TextWrapping="Wrap" VerticalAlignment="Top" Width="80"/>
                <PasswordBox Margin="10" Grid.Row="1" Grid.Column="1" x:Name="PasswordBox_2" HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="72"/>
                <Button FocusManager.IsFocusScope="True" Padding="20" HorizontalAlignment="Center" Grid.Row="2" Grid.ColumnSpan="2" x:Name="BtnNavigateTabIndex" Content="NavigateTabIndex"  Width="120" Click="BtnNavigateTabIndex_Click" />
            </Grid>
        </StackPanel>
    </Window>

A: This line of code should set you in the right direction:
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

where element is a UIElement (like one of your textboxes). This is an excerpt from the following post: Moving to next control on Enter keypress in WPF. And you put this code on the click event handler of the button...
By the way: discovering what the active UIElement / user control is can be done as described here.


text:
Q: Cleaning DataSets! Creating a new variable based on date range of another variable I have two data sets that need some cleaning for easier analysis and they both have to do something very similar. Let's start with data set A.
A looks like this:
ID  Test.Date   Test.Score

1   9/22/14        25
2   1/3/2015       50
3   3/17/2015      52
4   6/1/2015       56

So, what I need are 3 new variables that pull the score from Test.Score based on date ranges. One range will be 8/01/2014-11/01/2014, another 12/01/2014-3/25/2015, and the third 4/01/2015-6/30/2015. These correlate to Fall, Winter, and Spring data collections. So the new dataframe should look like this:
ID  Test.Date   Test.Score   Test.Fall   Test.Winter   Test.Spring

1   9/22/14        25           25
2   1/3/2015       50                        50
3   3/17/2015      52                        52
4   6/1/2015       56                                       56

Preferably NA's will fill the spots in the new variable columns if a particular score was not collected during that date range. Does this make sense?
Data set B is similar except it's got 3 dates per ID and 3 scores. So it looks like this:
 ID  Test.Date1   Test.Date2   Test.Date3   Test.Score1   Test.Score.2   Test.Score3

1   9/22/14       1/3/2015        6/1/2015      25            30            55
2   9/22/14       10/3/2015        6/1/2015      26            31            66
3   9/22/14       1/3/2015        6/1/2015      25            39            63
4   9/22/14       1/3/2015        6/1/2015      22            29            56

B needs to create 3 new columns called Test.Fall, Test.Winter, Test.Spring, and pull the values according to the same data range as above. Now, you may be wondering, why not just rename the test score columns? Because some participants took two tests within weeks of eachother (see sample ID #2). We need one test per Fall, Winter, Spring. So if Test.Date1 was in September, and Test.Date2 was October, that participant ID simply won't have a Test.Winter score.
Do I need to clarify anything?

A: library(dplyr)
library(lubridate)
library(tidyr)
library(stringi)

A =
  data_frame(
    ID = 1:4,
    Test.Date = c("9/22/2014", "1/3/2015", "3/17/2015", "6/1/2015") %>% mdy,
    Test.Score = c(25, 50, 52, 56))

classify = function(date_vector)
  ifelse(
    date_vector %>% between(mdy("8/01/2014"), mdy("11/01/2014")),
    "Fall",
    ifelse(
      date_vector %>% between(mdy("12/01/2014"), mdy("3/25/2015")),
      "Winter",
      ifelse(
        date_vector %>% between(mdy("4/01/2015"), mdy("6/30/2015")),
        "Spring",
        "Other"))) %>%
  paste("Test", ., sep = ".")

result.A =
  A %>%
  mutate(Season = classify(Test.Date)) %>%
  spread(Season, Test.Score) %>%
  select(-Test.Date) %>%
  left_join(A)

B =
  data_frame(
    ID = 1:4,
    Test.Date1 =
      c("9/22/14", "9/22/14", "9/22/14", "9/22/14") %>% mdy,
    Test.Date2 =
      c("1/3/2015", "10/3/2015", "1/3/2015 ", "1/3/2015 ") %>% mdy,
    Test.Date3 =
      c("6/1/2015", "6/1/2015", " 6/1/2015",  "6/1/2015") %>% mdy,
    Test.Score1 = c(25, 26, 25, 22),
    Test.Score2 = c(30, 31, 39, 29),
    Test.Score3 = c(55, 66, 63, 56))

result.B =
  B %>%
  gather(variable, value, -ID) %>%
  mutate(type =
           variable %>% stri_sub(6, -2),
         rep =
           variable %>% stri_sub(-1)) %>%
  select(-variable) %>%
  spread(type, value) %>%
  mutate(Date = as.POSIXct(Date, tz = "UTC", origin = origin),
         Season = classify(Date)) %>%
  group_by(ID, Season) %>%
  summarize(Score = mean(Score)) %>%
  spread(Season, Score)

A: Here's a solution to your data set A problem using base R
# Construct Test Data
mydata <- data.frame(ID = c(1:4),
                     Test.Date = c("9/22/14", "1/3/2015", "3/17/2015", "6/1/2015"),
                     Test.Score = c(25, 50, 52, 56))

# Format dates
mydata$Test.Date <- as.character(mydata$Test.Date)
mydata$newDate <- as.Date(mydata$Test.Date, "%m/%d/%y")
mydata$newDate[2:4] <- as.Date(mydata$Test.Date[2:4], "%m/%d/%Y")

#Classify Tests
mydata$Test.Fall = ifelse(mydata$newDate > "2014-08-01" & mydata$newDate < "2014-11-01", mydata$Test.Score, NA)
mydata$Test.Winter = ifelse(mydata$newDate > "2014-12-01" & mydata$newDate < "2015-03-25", mydata$Test.Score, NA)
mydata$Test.Spring = ifelse(mydata$newDate > "2015-04-01" & mydata$newDate < "2015-06-30", mydata$Test.Score, NA)

Your problem with data set B isn't exactly clear:

We need one test per Fall, Winter, Spring. So if Test.Date1 was in September, and Test.Date2 was October, that participant ID simply won't have a Test.Winter score.

If there are two test dates that fall within the Fall date range, then which test score should go in Test.Fall? The higher score? The more recent score? The average? Happy to update my answer when you provide that information.