text:
Q: Add additional individual IAM policy to serverless yaml to extend managed policy I have a managed policy that allows or read access to a kinesis stream (AWSLambdaKinesisExecutionRole), I am trying to add additional permissions to also allow write access to PutRecord and PutRecords on to the kinesis stream.
My serverless.yml currently looks like -
resources:
  Resources:
    kinesisFullAccessRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: kinesis-full-access-role
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        ManagedPolicyArns:
          - arn:aws:iam::aws:policy/service-role/AWSLambdaKinesisExecutionRole
        Policies:
          - PolicyName: kinesis-write-access
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - kinesis:PutRecord
                    - kinesis:PutRecords
                  Resource:
                    - "arn:<some_arn>:stream/inbound-message-stream-dev"

I am still getting a is not authorized to perform: kinesis:PutRecord on resource error. What am I doing wrong?

A: If your serverless is creating the IAM role by it self you should had that to the iamRoleStatements like shown here
but it could be easier to create an IAM role in aws console and manage that yourself, and use it like here


text:
Q: indexPath and table view error I'm constantly having this error and I can't fix it, could someone help me?

Here's the code:
 func prepare(for segue: UIStoryboardSegue, sender: Any?){
    if segue.identifier == "detail" {
        let viewController = segue.destination as! DetailNewsController

        if let  indexPath = tableView.indexPathForSelectedRow {
            viewController.news = DownloadManager.sharedInstance.localArra[(indexPath as NSIndexPath).row]

            let cella = self.tableView.cellForRow(at: indexPath) as! NewsCell

            self.zoomTransition.sourceView = cella

            viewController.newsImage = cella.imageNews.image

            self.tableView.deselectRow(at: indexPath, animated:true)
        }
    }
}

A: Apparently your tableView var, is not a UITableView instance, is a closure.
If You are sure that is a UITableView try clean your project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nginx: 413 entity too large - file does not reach the application I'm using Nginx and uwsgi with wsgi app. When I try to upload the image sometimes the application does not get the image and there used to be error 413 entity too large.
I fixed this issue by adding client_max_body_size 4M;and my Nginx conf looks something like:
//Add sample Nginx Server
//Block here

The error stopped showing but still the file does not reach the application. I don't understand it works on some computers and it dosent work on some.

A: If you're getting 413 Request Entity Too Large errors trying to upload, you need to increase the size limit in nginx.conf or any other configuration file . Add client_max_body_size xxM inside the server section, where xx is the size (in megabytes) that you want to allow.
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        client_max_body_size 20M;
        listen       80;
        server_name  localhost;

        # Main location
        location / {
            proxy_pass         http://127.0.0.1:8000/;
        }
    }
}

A: It means the max file size is larger than the upload size. See client_max_body_size
So try using instead of using a fixed value.
server {
     [...]
     client_max_body_size 0;
     [...]
}

A value of 0 will disable the max upload check, I'd recommend putting a fixed value such as 3M, 10M, etc... instead though.


text:
Q: How to avoid using namespace prefixes in Xaml I've started migrating company owned application from UWP 10 to WinUI (on NET5) using upgrade-assistant tool. Give or take, the most conflicts are gone, but the the nasty one remains in .xaml files. The underlying code can't be source-generated due to missing namespace prefixes:

<ResourceDictionary
    xmlns:xaml="clr-namespace:Windows.UI.Xaml;assembly=Windows"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Ifs.Uma.UI.Controls">

    <Style TargetType="local:Dialog">
        <Setter Property="Background" Value="#FFEDEDED" />
    </Style>

</ResourceDictionary>

I'm not sure if I'm missing some package references. Or if it's possible to just define them somewhere (XmlnsDefinitionAttribute is not available)? Is it even possible without going through hundreds of .xaml files and fixing all them manually or via find-replace?
For example, one of .csproj files with referenced packages below:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <OutputType>Library</OutputType>
    <RootNamespace>SomeUI</RootNamespace>
    <DefaultLanguage>en</DefaultLanguage>
    <CodeAnalysisRuleSet>..\FrameworkRules.ruleset</CodeAnalysisRuleSet>
    <AppxBundlePlatforms>x86|x64</AppxBundlePlatforms>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <WarningLevel>4</WarningLevel>
    <CodeAnalysisRuleSet>..\FrameworkRules.Release.ruleset</CodeAnalysisRuleSet>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <PropertyGroup>
    <NetStandardImplicitPackageVersion>2.0.3</NetStandardImplicitPackageVersion>
  </PropertyGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Update="Properties\AssemblyInfo.cs">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers" Version="0.3.330701">
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

<!-- I had to add those manually to get the code working -->
    <ItemGroup>
        <PackageReference Include="System.Runtime.InteropServices.WindowsRuntime" Version="4.3.0" />
        <PackageReference Include="System.Runtime.WindowsRuntime" Version="4.7.0" />
        <PackageReference Include="System.Runtime.WindowsRuntime.UI.Xaml" Version="4.7.0" />
        <Reference Include="Windows">
            <HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.winMD')">C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.winMD</HintPath>
        </Reference>
        <Reference Include="Windows.Foundation.FoundationContract">
            <HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.FoundationContract\4.0.0.0\Windows.Foundation.FoundationContract.winmd')">C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.FoundationContract\4.0.0.0\Windows.Foundation.FoundationContract.winmd</HintPath>
        </Reference>
        <Reference Include="Windows.Foundation.UniversalApiContract">
            <HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.UniversalApiContract\10.0.0.0\Windows.Foundation.UniversalApiContract.winmd')">C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.UniversalApiContract\10.0.0.0\Windows.Foundation.UniversalApiContract.winmd</HintPath>
        </Reference>
    </ItemGroup>
</Project>

I've just went an obvious way, made a simple UWP program to add prefixes and namespaces to those tags (just in case someone's interested):
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // 1. run the following command to make your .xaml files accessible to UWP:
            //    XCOPY <your_solution_dir>/*.xaml C:\Users\<you>\Pictures\XAML /E
            // 2. Delete \bin and \obj directories from there (optional)
            // 3. Add Pictures capability to your manifest (imho the easiest one to use)
            //    <Capabilities>
            //      <uap:Capability Name = "picturesLibrary" />
            //    </Capabilities>
            var assembly = typeof(ResourceDictionary).Assembly;
            var regulars = assembly
                .GetExportedTypes()
                .Where(type => typeof(DependencyObject).IsAssignableFrom(type) && type.IsClass)
                .Select(type => new { Namespace = type.Namespace, TypeName = type.Name, Prefix = type.Namespace.Split('.').Last().ToLowerInvariant() })
                .GroupBy(x => x.Prefix)
                .Select(x => new {
                    Regex = new Regex($"(</?)(?={string.Join("|", x.Select(n => n.TypeName))})"),
                    Replacements = x.Select(y => new Replacement(y.Namespace, y.Prefix)).First() })
                .ToDictionary(x => x.Regex, x => x.Replacements);
            var namespaceAttributes = new Regex("<(?<=[\b\\w\\d\\D]).*(xmlns)[^>]+", RegexOptions.Singleline);
            var picturesDirectory = KnownFolders.PicturesLibrary;
            var sourceDirectory = await picturesDirectory.GetFolderAsync("XAML");
            var xamlFiles = await GetXamlFilesAsync(sourceDirectory);
            var fixedFiles = 0;
            foreach (var xamlFile in xamlFiles)
            {
                var markup = await FileIO.ReadTextAsync(xamlFile);
                var matchedReplacements = new List<Replacement>();
                foreach (var replacer in regulars)
                {
                    if (replacer.Key.IsMatch(markup))
                    {
                        matchedReplacements.Add(replacer.Value);
                        markup = replacer.Key.Replace(markup, $"$&{replacer.Value.Prefix}:");
                    }
                }
                if (matchedReplacements.Count == 0) continue;
                var nsAttributes = namespaceAttributes.Match(markup);
                if (nsAttributes.Success && markup.Length > nsAttributes.Length)
                {
                    markup = nsAttributes.Result("$&" + Environment.NewLine +
                                string.Join(Environment.NewLine,
                                matchedReplacements.Where(replacement => !markup.Contains($"xmlns:{replacement.Prefix}")).Select(replacement =>
                                $"xmlns:{replacement.Prefix}=\"clr-namespace:{replacement.Namespace};assembly=Windows.Foundation.UniversalApiContract\"")))
                                + markup.Substring(nsAttributes.Length);
                }
                await FileIO.WriteTextAsync(xamlFile, markup);
                fixedFiles++;
            }
            await new Windows.UI.Popups.MessageDialog($"{fixedFiles} of {xamlFiles.Count} xaml files were fixed").ShowAsync();
        }

        async Task<IList<StorageFile>> GetXamlFilesAsync(StorageFolder topFolder)
        {
            var xamlFiles = new List<StorageFile>();
            var folders = await topFolder.GetFoldersAsync();
            foreach (var folder in folders)
            {
                xamlFiles.AddRange((await folder.GetFilesAsync()).Where(f => StringComparer.OrdinalIgnoreCase.Equals(f.FileType, ".xaml")));
                xamlFiles.AddRange(await GetXamlFilesAsync(folder));
            }
            return xamlFiles;
        }

        private readonly struct Replacement
        {
            public Replacement(string @namespace, string prefix)
            {
                Namespace = @namespace; Prefix = prefix;
            }
            public readonly string Namespace;
            public readonly string Prefix;
        }
    }

<xaml:ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Ifs.Uma.UI.Controls"
    xmlns:nav="using:Ifs.Uma.UI.Navigation"
xmlns:xaml="clr-namespace:Windows.UI.Xaml;assembly=Windows.Foundation.UniversalApiContract"
xmlns:controls="clr-namespace:Windows.UI.Xaml.Controls;assembly=Windows.Foundation.UniversalApiContract"
xmlns:shapes="clr-namespace:Windows.UI.Xaml.Shapes;assembly=Windows.Foundation.UniversalApiContract">

    <xaml:Style TargetType="local:PageHeader">
        <xaml:Setter Property="Height" Value="48" />
        <xaml:Setter Property="Background" Value="{ThemeResource IfsAppBackgroundBrush}" />
        <xaml:Setter Property="Template">
            <xaml:Setter.Value>
                <controls:ControlTemplate TargetType="local:PageHeader">
                    <controls:Grid Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
<!-- Grid and other controls -->
                    </controls:Grid>
                </controls:ControlTemplate>
            </xaml:Setter.Value>
        </xaml:Setter>
    </xaml:Style>

</xaml:ResourceDictionary>

It all went fine, but resulted in a message that type <controls:ControlTemplate /> does not support direct content. This type is pretty much within every .xaml file. TemplateBinding and other binding types also not found. Perhaps, it's not the way to fix the issue, there might be an SDK missing or something.


text:
Q: EF Poco method unknown in LINQ To get a list of all unbalanced orders I have the following (simpliefied) Linq
var UnbalancedOrders = db.Orders.Where(x => x.TenantId == Transaction.TenantId && x.State == OrderStates.Placed && x.Balance() > 0);

Balance() is a method on the Order model calculating how much of the due amount is not paid yet.
When I run the code I get :
LINQ to Entities does not recognize the method 'Double Balance()' method, and this method cannot be translated into a store expression.

I understand that this does not work this way, but is there a workaround to actually use that method in an Linq statement ?
UPDATE
    public class Order : BasketBase, IModel, IMultiTenant
    {
        ...
        public double TotalPayments()
        {
            return Payments.Sum(x => x.Amount);
        }

        public double Balance()
        {
            return (TotalAmmount() - TotalPayments());
        }
}

FROM this SO-ISSUE I took the idea to first turn it into a list only using the part that can be translated to SQL and then apply the part that is not translatble to SQL.
var UnbalancedOrders = db.Orders.Where(x => x.TenantId == Transaction.TenantId && x.State == OrderStates.Placed).ToList().Where(x => x.Balance() > 0);

This seems to be working but does not look to be the best-practice : getting all the data from DB and filter a second time ?

A: You can just the reserved word let in LINQ syntax, like this:
from order in db.Orders
let totalPayments = order.Payments.Sum(x => x.Amount)
let totalAmmount = order.Payments.Sum(x => x.Amount) //duplicated totalPayment because IDK this formula
let balance = totalAmmount() - totalPayments
where order.TenantId == Transaction.TenantId && x.State == OrderStates.Placed && balance > 0
select order

If you don't want to duplicate the Balance formula, you can use a combination of using DTO and AutoMapper, like this:
public class Program
{
    private static void Main(string[] args)
    {
        Mapper.Initialize(configuration => configuration.AddProfile<OrderProfile>());

        using (var ctx = new Ctx())
        {
            ctx.Database.CreateIfNotExists();

            ctx.Orders.Add(new Order { Value = 100, OtherAdditionalValue = 1 });
            ctx.SaveChanges();
            ctx.Database.Log = Console.WriteLine;
            // this way works, but fetch all database first
            var orders = ctx.Orders.ToList().Where(x => x.Balance > 100);

            //this way works, but fetch only charges that has balance > 100
            var chargingsDtos = ctx.Orders.ProjectTo<OrderDTO>().Where(x => x.Balance > 100).ToList();
        }
    }
}

public class Ctx : DbContext
{
    public DbSet<Order> Orders { get; set; }
}

public class Order
{
    private static readonly Func<Order, decimal> CompiledBalance = BalanceExpression.Compile();
    public long Id { get; set; }
    public decimal Value { get; set; }
    public decimal OtherAdditionalValue { get; set; }
    public decimal Balance => CompiledBalance(this);

    public static Expression<Func<Order, decimal>> BalanceExpression
        => c => c.Value + c.OtherAdditionalValue;
}

public class OrderProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<Order, OrderDTO>()
              .ForMember(c => c.Balance, de => de.MapFrom(Order.BalanceExpression));
    }
}

public class OrderDTO
{
    public long Id { get; set; }
    public decimal Balance { get; set; }
}

And the SQL query output is this:
Opened connection at 09/12/2015 16:44:36 -03:00

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Value] AS [Value],
    [Extent1].[OtherAdditionalValue] AS [OtherAdditionalValue]
    FROM [dbo].[Orders] AS [Extent1]

-- Executing at 09/12/2015 16:44:36 -03:00

-- Completed in 0 ms with result: SqlDataReader

Closed connection at 09/12/2015 16:44:36 -03:00

Opened connection at 09/12/2015 16:44:36 -03:00

SELECT
    1 AS [C1],
    [Extent1].[Id] AS [Id],
    [Extent1].[Value] + [Extent1].[OtherAdditionalValue] AS [C2]
    FROM [dbo].[Orders] AS [Extent1]
    WHERE ([Extent1].[Value] + [Extent1].[OtherAdditionalValue]) > cast(100 as decimal(18))

-- Executing at 09/12/2015 16:44:36 -03:00

-- Completed in 1 ms with result: SqlDataReader

Closed connection at 09/12/2015 16:44:36 -03:00

As you can see, the line var orders = ctx.Orders.ToList().Where(x => x.Balance > 100); fetch all database, and other line, using Projection from AutoMapper include Where clause in SQL.
Using this you still have the Balance property in your model, but now you have the BalanceExpression that hold the expression to get the Balance value, and if you change it, it will work everywhere.

A: The final solution I went for :
var UnbalancedOrders = db.Orders.Where(x => x.TenantId == Transaction.TenantId && x.State == OrderStates.Placed).ToList().Where(x => x.Balance() > 0);

Just for reference some background info :
db.Orders.Where(x => x.TenantId == Transaction.TenantId && x.State == OrderStates.Placed).ToList()

Is Linq to EF and will be translated to SQL.
.Where(x => x.Balance() > 0)

Is Linq to entities hence methods of the POCO can be used.
CONTRA :
The ToList() is downloading the entire set to memory and then a second filtering on the list is done. Hence a lot of MEM and CPU usage.
PRO :
This solution is independant from anychanges in the Balance() method/formula. Hence will not introduce a bug if Balance() changes.

A: First create a VM and save the worked out Balance() in it so that all the calculations are done. LINQ does not work on computed values. Then use your LINQ statement
//The proposed VM. add fields as required

public class OrderVM
{
   public int OrderID {get;set;}  //Guessing this field as you hv not shown it
   public double TotalPayments{get;set;}

    public double Balance{get;set;}
}

// **** Add this below in another class
 :
 :
 :
//Note the calculated field is not a part of the LINQ I have removed it.
var allOrders = db.orders.ToList(var UnbalancedOrders = db.Orders.Where(x => x.TenantId == Transaction.TenantId && x.State == OrderStates.Placed ) //filter
List<OrderVM> listOrderVM= new List<OrderVM>();

foreach (var item in allOrders)
{
    OrderVM o = new OrderVM;
    o.OrderID = Item.OrderID
    // add more fields if u need them for the op.
    o.Balance = Item.Balance();
    o.TotalPayments = Item.TotalPayments();

    //You could do an IF here and add only those that are greater than zero...
    //But I am showing you how to use LINQ when you have a calculation.

    listOrderVM.Add(o);
 }

 var selectedOrders = listOrderVM.ToList(x=>x.Balance>0);

//selectedOrders will have all orders with balance > 0
//Now LINQ will work.


text:
Q: How can I align the columns of tables in Bash? I want to format text as a table. I tried echoing with a '\t' separator, but it was misaligned.
Desired output:
a very long string..........     112232432      anotherfield
a smaller string                 123124343      anotherfield

A: It's easier than you wonder.
If you are working with a separated-by-semicolon file and header too:
$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t

If you are working with an array (using tab as separator):
for((i=0;i<array_size;i++));
do

   echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv

done;

cat file.csv | column -t

A: awk solution that deals with stdin
Since column is not POSIX, maybe this is:
mycolumn() (
  file="${1:--}"
  if [ "$file" = - ]; then
    file="$(mktemp)"
    cat > "${file}"
  fi
  awk '
  FNR == 1 { if (NR == FNR) next }
  NR == FNR {
    for (i = 1; i <= NF; i++) {
      l = length($i)
      if (w[i] < l)
        w[i] = l
    }
    next
  }
  {
    for (i = 1; i <= NF; i++)
      printf "%*s", w[i] + (i > 1 ? 1 : 0), $i
    print ""
  }
  ' "$file" "$file"
  if [ "$1" = - ]; then
    rm "$file"
  fi
)

Test:
printf '12 1234 1
12345678 1 123
1234 123456 123456
' > file

Test commands:
mycolumn file
mycolumn <file
mycolumn - <file

Output for all:
      12   1234      1
12345678      1    123
    1234 123456 123456

See also:

*

*Using awk to align columns in text file?

*AWK: go through the file twice, doing different tasks

A: I am not sure where you were running this, but the code you posted would not produce the output you gave, at least not in the Bash version that I'm familiar with.
Try this instead:
stringarray=('test' 'some thing' 'very long long long string' 'blah')
numberarray=(1 22 7777 8888888888)
anotherfieldarray=('other' 'mixed' 456 'data')
array_size=4

for((i=0;i<array_size;i++))
do
    echo ${stringarray[$i]} $'\x1d' ${numberarray[$i]} $'\x1d' ${anotherfieldarray[$i]}
done | column -t -s$'\x1d'

Note that I'm using the group separator character (0x1D) instead of tab, because if you are getting these arrays from a file, they might contain tabs.

A: function printTable()
{
    local -r delimiter="${1}"
    local -r data="$(removeEmptyLines "${2}")"

    if [[ "${delimiter}" != '' && "$(isEmptyString "${data}")" = 'false' ]]
    then
        local -r numberOfLines="$(wc -l <<< "${data}")"

        if [[ "${numberOfLines}" -gt '0' ]]
        then
            local table=''
            local i=1

            for ((i = 1; i <= "${numberOfLines}"; i = i + 1))
            do
                local line=''
                line="$(sed "${i}q;d" <<< "${data}")"

                local numberOfColumns='0'
                numberOfColumns="$(awk -F "${delimiter}" '{print NF}' <<< "${line}")"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi

                # Add Header Or Body

                table="${table}\n"

                local j=1

                for ((j = 1; j <= "${numberOfColumns}"; j = j + 1))
                do
                    table="${table}$(printf '#| %s' "$(cut -d "${delimiter}" -f "${j}" <<< "${line}")")"
                done

                table="${table}#|\n"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]] || [[ "${numberOfLines}" -gt '1' && "${i}" -eq "${numberOfLines}" ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi
            done

            if [[ "$(isEmptyString "${table}")" = 'false' ]]
            then
                echo -e "${table}" | column -s '#' -t | awk '/^\+/{gsub(" ", "-", $0)}1'
            fi
        fi
    fi
}

function removeEmptyLines()
{
    local -r content="${1}"

    echo -e "${content}" | sed '/^\s*$/d'
}

function repeatString()
{
    local -r string="${1}"
    local -r numberToRepeat="${2}"

    if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
    then
        local -r result="$(printf "%${numberToRepeat}s")"
        echo -e "${result// /${string}}"
    fi
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true' && return 0
    fi

    echo 'false' && return 1
}

function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}

SAMPLE RUNS
$ cat data-1.txt
HEADER 1,HEADER 2,HEADER 3

$ printTable ',' "$(cat data-1.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+

$ cat data-2.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3

$ printTable ',' "$(cat data-2.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
+-----------+-----------+-----------+

$ cat data-3.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3
data 4,data 5,data 6

$ printTable ',' "$(cat data-3.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
| data 4    | data 5    | data 6    |
+-----------+-----------+-----------+

$ cat data-4.txt
HEADER
data

$ printTable ',' "$(cat data-4.txt)"
+---------+
| HEADER  |
+---------+
| data    |
+---------+

$ cat data-5.txt
HEADER

data 1

data 2

$ printTable ',' "$(cat data-5.txt)"
+---------+
| HEADER  |
+---------+
| data 1  |
| data 2  |
+---------+

REF LIB at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

A: To have the exact same output as you need, you need to format the file like this:
a very long string..........\t     112232432\t     anotherfield\n
a smaller string\t      123124343\t     anotherfield\n

And then using:
$ column -t -s $'\t' FILE
a very long string..........  112232432  anotherfield
a smaller string              123124343  anotherfield

A: Use the column command:
column -t -s' ' filename

A: printf is great, but people forget about it.
$ for num in 1 10 100 1000 10000 100000 1000000; do printf "%10s %s\n" $num "foobar"; done
         1 foobar
        10 foobar
       100 foobar
      1000 foobar
     10000 foobar
    100000 foobar
   1000000 foobar

$ for((i=0;i<array_size;i++));
do
    printf "%10s %10d %10s" stringarray[$i] numberarray[$i] anotherfieldarray[%i]
done

Notice I used %10s for strings.  %s is the important part.  It tells it to use a string.  The 10 in the middle says how many columns it is to be.  %d is for numerics (digits).
See man 1 printf for more info.

A: Just in case someone wants to do that in PHP, I posted a gist on GitHub:
https://gist.github.com/redestructa/2a7691e7f3ae69ec5161220c99e2d1b3
Simply call:
$output = $tablePrinter->printLinesIntoArray($items, ['title', 'chilProp2']);

You may need to adapt the code if you are using a PHP version older than 7.2.
After that, call echo or writeLine depending on your environment.

A: The below code has been tested and does exactly what is requested in the original question.
Parameters:
%30s Column of 30 char and text right align.
%10d integer notation, %10s will also work. \
stringarray[0]="a very long string.........."
# 28Char (max length for this column)
numberarray[0]=1122324333
# 10digits (max length for this column)
anotherfield[0]="anotherfield"
# 12Char (max length for this column)
stringarray[1]="a smaller string....."
numberarray[1]=123124343
anotherfield[1]="anotherfield"

printf "%30s %10d %13s" "${stringarray[0]}" ${numberarray[0]} "${anotherfield[0]}"
printf "\n"
printf "%30s %10d %13s" "${stringarray[1]}" ${numberarray[1]} "${anotherfield[1]}"
# a var string with spaces has to be quoted
printf "\n Next line will fail \n"
printf "%30s %10d %13s" ${stringarray[0]} ${numberarray[0]} "${anotherfield[0]}"

  a very long string.......... 1122324333  anotherfield
         a smaller string.....  123124343  anotherfield

A: column -t skips empty fields when a line starts with a delimiter character or when there are two or more consecutive delimiter characters:
$ printf %s\\n a,b,c a,,c ,b,c|column -s, -t
a   b  c
a   c
b   c

Therefore I use this awk function instead (it requires gawk because it uses arrays of arrays):
$ tab(){ awk '{if(NF>m)m=NF;for(i=1;i<=NF;i++){a[NR][i]=$i;l=length($i);if(l>b[i])b[i]=l}}END{for(h in a){for(i=1;i<=m;i++)printf("%-"(b[i]+n)"s",a[h][i]);print""}}' n="${2-1}" "${1+FS=$1}"|sed 's/ *$//';}
$ printf %s\\n a,b,c a,,c ,b,c|tab ,
a b c
a   c
  b c

A: if you data doesn't contain the equal sign ("=") anywhere in it, you can use that as a shell-friendly delimiter for column without having to escape anything -

*

*by modifying FS to be either a tab ("\t") plus any amount of spaces (" ") or tabs ("\t") on either side of it, or a contiguous chunk of 2 or more spaces, it also allows the input data to have any amount of single space within each field
 echo "${inputdata2}" |

 mawk NF=NF OFS== FS=' + |[ \t]*\t[ \t]*' |

 column -s= -t

a very long string..........  112232432  anotherfield
a smaller string              123124343  anotherfield

if the data does contain the equal sign, use a combo sep that's close to impossible to exist in typical data :

gawk -e NF=NF OFS='\301\372\5' FS=' + |[ \t]*\t[ \t]*' |

LC_ALL=C column -s$'\301\372\5' -t

a very long string..........  112232432  anotherfield
a smaller string              123124343  anotherfield

and if ur data only has 2 columns, and you have ballpark sense of how wide the first field is, you can use this \r trick for nice on-screen formatting (but those don't become runs of spaces if u need to send it down the pipe) :

# each \t is 8-spaces at console terminal

mawk NF=2 FS=' + |[ \t]*\t[ \t]*' OFS='\r\t\t\t\t'

a very long string..........    112232432
a smaller string                123124343


text:
Q: Trying to edit html table data with python data (ajax get method?) I am building a program for ranking people (don't ask) and I think I am facing a beginners issue- I have a desired value generated in python which I wish to make the content of an html table.
The table is a leader board, which is determined by finding the person with the highest score (obv). I have a list of the top 10 people, and I am now wishing to put that into an html table. Ideally, I would like this to edit the actual html file, so that when one user generates the table it will save it for the next. (I will change the generateTable function to be a button)
I have tried using beautiful soup with no luck, I read the documentation however I could not seem to find the solution.
Basically, I am just trying to call a python variable with ajax. I can do the reverse, however. I am new at programming if you can't tell.
I am running a python flask server on my local network, and I am using the google sheets api as a makeshift database.
server.py:
@app.route("/leader", methods=['POST'])
def leader():
    name_and_score = []
    length = int(changedata.next_available_row(2))
    for x in range(2,length):
        time.sleep(1.1)
        name_and_score.append((int(changedata.index(x,7)), str((changedata.index(x,1)))))
    print str(name_and_score) + ' <--- This is everybody'
    leaderboard = nlargest(10, name_and_score)
    return str(leaderboard) + ' <--- These are top 10'

leaderboard.html

<link rel="stylesheet" href="static/css/scoreboard.css">

Boys

    Name
    Score

     Person
    45000

     Person
    45000

     Person
    50000

Any help would be greatly appreciated in making a python variable the string in its respective cell in html.
str(leaderboard) looks like:  [(26316, 'Name'), (6250, 'Name'), (6667, 'Name'), (6250, 'Name'), (4545, 'Name'), (36364, 'Name'), (46154, 'Name')]

*

*I have omitted the names however they are distinct values.

A: Use json.dumps() instead of str(leaderboard) so you could parse it back in the HTML.
return make_response(json.dumps(leaderboard),200)

give your table some id:

...

Then, parse it and populate table:
function generateTable() {
    $.ajax({
        method: 'POST',
        url: "http://10.0.1.36:5000/leader",
        success: function(response) {
            console.log(response);
            try {
              let res = JSON.parse(response);
              let table = document.getElementById("myleaderboard");
              //clear table
              table.innerHTML = "";
              //populate
              for (let i = 0;i < res.length; i++) {
                 const tr = document.createElement("tr");
                 const td1 = document.createElement("td");
                 const td2 = document.createElement("td");
                 td1.innerHTML = res[i][0]; //score
                 td2.innerHTML = res[i][1]; //name
                 tr.appendChild(td1);
                 tr.appendChild(td2);
                 table.appendChild(tr);
              }
            } catch(e){}
         },
        error: function(response) {
            console.error(response)
        }
    });
}


text:
Q: Proving that a particular function belongs to a sheaf of functions I have the following exercise

Let $M,N$ be open subsets in $\mathbb{R}^{n}$ and let $\Psi:M\to N$ be a smooth map. Show that $\Psi$ defines a morphism of spaces ringed by smooth functions.

The definitions are the following:

A presheaf $\mathcal{F}$ of functions on a topological space $M$ is a collection of subrings $\mathcal{F}(U)\subset C(U)$ of the ring $C(U)$ of all functions on $U$, for each open subset $U\subset M$, such that the restriction of every $\gamma\in\mathcal{F}(U)$ to an open subset $U_{1}\subset U$ belongs to $\mathcal{F}(U_{1})$.
A sheaf $\mathcal{F}$ of functions on a topological space $M$ is a presheaf on $M$ such that the following condition is met. Let $\{U_{i}\}_{i\in I}$ be an open cover (possibly infinite) of an open subset $U\subset M$ and $f_{i}\in\mathcal{F}(U_{i})$ a family of functions defined on the open sets of the cover, compatible on the pairwise intersections: $$f_{i}\left.\right\vert_{U_{i}\cap U_{j}}=f_{j}\left.\right\vert_{U_{i}\cap U_{j}} $$
  for every pair $(U_{i},U_{j})$ of members of the cover. Then, there exists $f\in\mathcal{F}(U)$ such that $f_{i}$ is the restriction of $f$ to $U_{i}$ for all $i\in I$.
A ringed space $(M,\mathcal{F})$ is a a topological space equipped with a sheaf of functions.
A morphism $(M,\mathcal{F}_{M})\stackrel{\Psi}{\longrightarrow}(N,\mathcal{F}_{N})$ of ringed spaces is a continuous map such that, for every open subset $U\subset N$ and every function $f\in\mathcal{F}_{N}$, the function $f\circ\Psi$ belongs to the ring $\mathcal{F}_{M}(\Psi^{-1}(U))$.

I do not understand how to proof that a particular function (here, $f\circ\Psi$) belongs to some ring. Here, it is clear that $f\circ\Psi$ is smooth, as the composite of smooth functions. But what other conditions do I have to show? What does that mean to "belong to the ring $\mathcal{F}_{M}(\Psi^{-1}(U))$"?
The ring $\mathcal{F}(U)$ is equipped with which operations? I suppose they are usual addition and multiplication of functions. But I guess this exercise is not only about showing that $f\circ\psi^{-1}+g$ and $(f\circ\psi^{-1})\cdot g$ are both smooth functions in $\mathcal{F}_{M}(\Psi^{-1}(U))$ for any $g\in\mathcal{F}_{M}(\Psi^{-1}(U))$ for all open $U\subset N$.
To summarize my question: what do I need to show?


text:
Q: setTimeout in select box change event When I have autopostback set to true on a select box, why is the 'setTimeout' necessary in the onchange event?  Why isn't __doPostBack just called directly?
onchange="javascript:setTimeout('__doPostBack(\'ctl00$myselect\',\'\')', 0)"

A: From MSDN:
The JavaScript setTimeout method is used with the _doPostBack method to ensure that the user action completes before the postback occurs.

A: I was wondering the same thing - and I cynically thought the evasive MSDN explanation might mean  "working around a bug in IE".
It seems this is the case! There's a race hazard in the threads handling the "use action":
http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/958a24b7-775e-434b-9fd4-58f72ecbb759


text:
Q: Using JPQL for queries to an MS-Access database using UCanAccess driver When using

*

*JPA 2.1

*EclipseLink 2.5.2

*UCanAccess 4.0.4

We have the problem that the tables will get named with quotes ". This is because the underlying implementation is not really aware what dialect to use resulting in one incompatible to MSAccess. This then results in e.g. table annotations like @Table(name = "\"EMPLOYEE\"").
To solve this we have to include in orm.xml:
...
    <persistence-unit-defaults>
        <delimited-identifiers />
    </persistence-unit-defaults>
...

Now plain queries will work, but the use of JPQL in named queries will fail because the resulting SQL query will quote all column names:

[EL Warning]: 2019-06-02 21:14:27.818--UnitOfWork(2144282958)--Thread(Thread[main,5,main])--Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: Personen
Error Code: -5581
Call: SELECT "PersonId", "EMail", "Ansprechpartner", "Briefanrede", "Fax", "Name", "Ort", "PLZ", "Sortierung", "Straße", "Telefon" FROM "Personen"
Query: ReadAllQuery(name="Personen.findAll" referenceClass=Personen sql="SELECT "PersonId", "EMail", "Ansprechpartner", "Briefanrede", "Fax", "Name", "Ort", "PLZ", "Sortierung", "Straße", "Telefon" FROM "Personen"")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
    at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2738)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2691)
    at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:495)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
    at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:403)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1215)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1751)
    at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
    at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:469)
    at de.mebrach.jungebuehne.vorverkauf.PersonenService.loadAll(PersonenService.java:20)
    at Main.main(Main.java:20)
Caused by: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: Personen

A: Include a trget-database property in persistence.xml:
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.AccessPlatformDelimiterConfig"/>

Add a new class to the class path:
package org.eclipse.persistence.platform.database;

public class AccessPlatformDelimiterConfig extends AccessPlatform {

    private static final long serialVersionUID = 7034590043310425678L;

    public AccessPlatformDelimiterConfig() {
        super();
        this.tableQualifier = "";
        this.startDelimiter = "[";
        this.endDelimiter = "]";
    }
}


text:
Q: Performing column operations in CASE WHEN statment condition in sql query I'm developing an application using vb.net2008 with database as msaccess. I've designed a table in database having columns IN_TIME and OUT_TIME in format HH:MM:SS . I want a result as TOT_TIME which will display difference between these two columns. I've written a query for this, now i'm facing a problem that i dont want to display result if IN_TIME is less than 8:00:00 AM else display result. I have used CASE WHEN but it didnt worked, help me out.
I've tried this so far
SELECT *
  (CASE WHEN LATE_LIMIT > '" + date3 + "'
   THEN ROUND(([PM_OUT]-[OVERIME_LIMIT]),2)
   ELSE 'N' )AS OverTime
FROM DTR_REC

A: You are missing a comma and an END case:
SELECT *
  ,(CASE WHEN LATE_LIMIT > '" + date3 + "'
   THEN ROUND(([PM_OUT]-[OVERIME_LIMIT]),2)
   ELSE 'N' END)AS OverTime
FROM DTR_REC

But I'm not sure if Access supports CASE statements. If not does this work:
SELECT *
  ,IIF(LATE_LIMIT > '" + date3 + "', ROUND(([PM_OUT]-[OVERIME_LIMIT]),2),'N') AS OverTime
FROM DTR_REC


text:
Q: Radius of curvature of $r=2 \cdot e^{3 \phi}$ I have to find the curvature of $r=2 \cdot e^{3 \phi}$
$\dfrac{\left[1+\left(\dfrac{d y}{d x}\right)^2\right]^{\frac 3 2}}{\dfrac{d^2 y}{d x^2}}$
$x=r\cdot cos(\phi)=2 \cdot e^{3 \phi}\cdot cos(\phi)$
$y=r\cdot sin(\phi)=2 \cdot e^{3 \phi}\cdot sin(\phi)$
$\dfrac{d x}{d \phi}=-2 e^{3 \phi}\cdot (sin(\phi) - 3 cos(\phi))$
$\dfrac{d y}{d \phi}=2 e^{3 \phi}\cdot (3 sin(\phi) + cos(\phi))$
$\dfrac{d y}{d x}=\dfrac{2 e^{3 \phi}\cdot (3 sin(\phi) + cos(\phi))}{-2 e^{3 \phi}\cdot (sin(\phi) - 3 cos(\phi))}
=\dfrac{-3 sin(\phi) - cos(\phi)}{sin(\phi) - 3 cos(\phi)}$
$\dfrac{d^2 y}{d \phi^2}=4 e^{3 \phi}\cdot (4 sin(\phi) + 3 cos(\phi))$
$\dfrac{d^2 y}{d ^2 x}=\dfrac{\dfrac{2 e^{3 \phi}\cdot (4 sin(\phi) - 3 cos(\phi))}{50}}{\dfrac{2 e^{3 \phi}\cdot (sin(\phi) + 3 cos(\phi))}{10}}=\dfrac{4 sin(\phi) - 3 cos(\phi)}{5\cdot (sin(\phi) + 3 cos(\phi))}$
now using the radius of curvature formula i find an incredibly complex formula:
$\rho=\dfrac{\left[1+\left(\dfrac{d y}{d x}\right)^2\right]^{\frac 3 2}}{\dfrac{d^2 y}{d x^2}}=\dfrac{\left[1+\left(\dfrac{3 sin(\phi) - cos(\phi)}{sin(\phi) + 3 cos(\phi)}\right)^2\right]^{\frac 3 2}}{\dfrac{4 sin(\phi) - 3 cos(\phi)}{5\cdot (sin(\phi) + 3 cos(\phi))}}$
I can't find a way to write this in a more human way.

A: It is easier to use the formula for curvature in terms of the function $r(\theta)$:

If a curve is defined in polar coordinates as $r(\theta)$, then its curvature is
  $$
    \kappa(\theta)
  = \frac{|r^2 + 2r'^2 - rr''|}{(r^2 + r'^2)^{3/2}}
$$
  where here the prime refers to the differentiation with respect to $\theta$.

The result is $e^{-3\theta}/(2\sqrt{10})$.

A: The curve $\gamma$ in question is a logarithmic spiral. From the selfsimilarity properties of these spirals it immediately follows that $\rho(\phi)=c r(\phi)$ for some constant $c$. The following (human) computations will confirm this fact.
I shall use the parametric representation
$$\gamma:\quad\phi\mapsto{\bf z}(\phi):=2e^{3\phi}(\cos\phi,\sin\phi)\ .$$One computes
$$\eqalign{{\bf z}'(\phi)&=2e^{3\phi}(-\sin\phi+3\cos\phi, \cos\phi+3\sin\phi)\cr   &=2\sqrt{10}e^{3\phi}\bigl(\cos(\phi+\alpha),\sin(\phi+\alpha)\bigr)\ ,\cr}$$
whereby $\alpha:=\arctan{1\over3}$. It follows that the arc length $\phi\mapsto s(\phi)$ along $\gamma$ satisfies
$$s'(\phi)=\bigl|{\bf z}'(\phi)\bigr|=2\sqrt{10}e^{3\phi}\ ,$$ whereas the forward tangent direction is given by
$$\theta(\phi)=\arg\bigl({\bf z}'(\phi)\bigr)=\phi+\alpha\ .$$
Now the curvature $\kappa$ is the turning speed of the tangent with respect to arc length, hence
$$\kappa(\phi)={d\theta\over ds}={\theta'(\phi)\over s'(\phi)}={1\over2\sqrt{10}}e^{-3\phi}\ ,$$
so that we finally obtain
$$\rho(\phi)={1\over\kappa(\phi)}=2\sqrt{10}e^{3\phi}\ .$$


text:
Q: With SQL 2017 -- does OPENJSON remove the escape sequences from the raw JSON data SQL proc consuming JSON payload from Web Service but the data was escaped before being received in the procedure.  I have a payload like this:
{
    "RES_NBR_ID": "00000056566",
    "RES_SCRIPT_NM": "Test Script",
    "RES_SCRIPT_ID": "jcet2",
    "RES_RESULT_GROUP_ID": 42622528,
    "RES_CREATED_BY_ID": "Jcccc",
    "RES_QUESTION_TXT": "asdf",
    "RES_ANSWER_TXT": "asdfa\"asfasf",
    "SORT_NBR": 4,
    "RES_QUESTION_ID": 4,
    "RES_DELETED_BY_ID": ""
}

You'll notice that the ANSWER_TXT is really asdfa"asfasf
The backslash was put in by the JSON.stringify function on the service
So will using OPENJSON like the following remove all stringfy sequences:
SELECT (SELECT MAX(RES_ID) FROM SCRT_RESULTS) + ROW_NUMBER() OVER(ORDER BY RES_QUESTION_TXT) AS RES_ID
,RES_NBR_ID
,RES_SCRIPT_NM
,RES_QUESTION_TXT
,RES_ANSWER_TXT
,RES_CREATED_BY_ID
,getdate() [RES_CREATED_DT]
,RES_DELETED_BY_ID
,getdate() [RES_DELETED_DT]
,RES_RESULT_GROUP_ID
,RES_SORT_NBR
,RES_SCRIPT_ID
,RES_QUESTION_ID
,getUTCdate() [RES_CREATED_UTC_DT]
 from openjson(@json_result)
WITH(
     RES_NBR_ID     varchar(16)
    ,RES_SCRIPT_NM          varchar(150)
    ,RES_SCRIPT_ID          varchar(5)
    ,RES_RESULT_GROUP_ID    bigint
    ,RES_CREATED_BY_ID      varchar(20)
    ,RES_QUESTION_TXT       varchar(2000)
    ,RES_ANSWER_TXT         varchar(2000)
    ,RES_SORT_NBR           int
    ,RES_QUESTION_ID        int
    ,RES_DELETED_BY_ID      varchar(20)

 )


text:
Q: How to solve this series $f(n) = f(n/2) + n$? Can I solve this as:
$f(n) = f(n/2) + n$
let find, $$f(n/2) = f(n/2/2) + n/2\\
  f(n/2) = f(n/4) + n/2$$
Now,
$$\begin{split}
f(n) &= f(n/4) + n/2 + n\\
f(n) &= f(n/8) + n/4 + n/2 + n
\end{split}$$
hence so on.
$$\vdots$$
Now, $n = 2^i$.
$$\begin{split}
f(2^i) &= f(2^i/2^i) + 2^i/2^{i-1} + 2^i/2^{i-2} + \cdots + 2^i\\
f(2^i) &= f(1) + 2^1 + 2^2 + \cdots + 2^i\\
f(2^i) &= 2^0 + 2^1 + 2^2 + \cdots + 2^i\\
f(2^i) &= 2^{i+1} - 1\\
f(2^i) &= 2^i\cdot 2^1 - 1\\
f(n) &= 2n - 1\\
f(2^k) &= f(2^{k-k}) + k\\
f(2^k) &= f(2^0) + k\\
 \cdots &= f(1) + k\\
 \cdots &= 1 + k
\end{split}$$
As we know
$$\begin{split}
n &= 2^k\\
\log (n) &= k \log(2)\\
k &= \log (n) / \log(2)\\
k &= \log_2 (n)\\
f(n) &= \log_2(n) + 1
\end{split}$$

A: At some point you need to have the value of say $f(1)$ or something. The classical way of solving this kind of questions would be to do as you did until:
$$ f(n) = f(1) + \sum_{i=0}^{k} \frac{n}{2^i}$$
where $2^k = n$. Then you should be able to solve the problem by computing $\sum_{i=0}^{k} \frac{n}{2^i}$ using geometric series.
In the case you $n$ is not a power of $2$, you must apply the reccurence formula until step $k$ with $\frac{n}{2^k} \le 1$, and the you must know what is the value of $f$ of say, interval $[0,1]$.

A: You've just given a recursion. A recursion needs have a base to be well defined. The base here could be the set of all $x \in (0.5, 1]$ (then any $x>0$ can be uniquely written as $2^kx_0$ for some $k\in\mathbb Z$ and $x_0\in (0.5,1]$).
So choose for one such $x_0$ a $y_0$ and define $f(x_0) := y_0$. Then suppose $n = 2^ky_0$. This gives the recursion
$$ f_0(0) = y_0 $$
$$ f_0(k) = f_0(k-1) + 2^ky_0 $$
Thus
$$ f_0(k) = y_0\left(\sum_{i=0}^k 2^k\right) = y_0(2^{k+1}-1)$$
If $n = y_02^k$ then $k = \log_2 n - \log_2{y_0}$. Also as $y_0\in(0.5,1]$ we have $\log_2y_0 \in (-1, 0]$. So $k = \lfloor \log_2 n \rfloor$, $y_0 = 2^{\{\log_2 n\}}$ (where $\{x\} := x - \lfloor x \rfloor$ is the fractional part).
Thus given any function $g:(0.5, 1]\to\mathbb R$ and the condition $f|{(0.5,1]} = g$ the solution to your recursion will be given by
$$ f(n) = g(2^{\{\log_2 n\}})(2^{\lfloor \log_2 n\rfloor + 1} - 1) $$
or alternatively using $g^*:(-1:0]\to\mathbb R$ with $g^*(x) := g(2^x)$ we get
$$ f(n) = g^*(\{\log_2 n\})(2^{\lfloor \log_2 n\rfloor + 1} - 1) $$

A: Given $$f(n) = f(n/2) + n$$ for all even integers $n\geq 2$, substitute the linear ansatz $f(n)= A n + B$ to yield
$$A n + B = A/2 n + B/2 + n.$$ Comparing coefficients of $n^1=n$ and of $n^0=1$ yields
the constraint equations $$A = A/2 + 1$$ and $$B=B/2$$ which are simultaneously solved only by $A=2$ and  $B=0$. So
$$f(n)=2n$$ is the only affine function satisfying the recurrence relation.
Similarly, the more general ansatz
$$f(n)= \sum_{k=0}^\infty A_k n^k$$ yields that all higher $A_k=0$ for $k\geq 2$.
Alternatively, one can assume there is a second solution $g(n)\neq f(n)$ for the appropriate $n$ and arrive at a contradiction. So
$$f(n)=2n$$ is the only solution.


text:
Q: Add a timer for every row added to dataGridView and remove it if row deleted I'm trying to add a timer for every row added to dataGridView and remove it if a row is deleted.
I cannot get the timer to run at all because of errors:
'System.Timers.Timer' does not contain a definition for 'Tick' and no extension method 'Tick' accepting a first argument of type 'System.Timers.Timer' could be found (are you missing a using directive or an assembly reference?)
The name 'myTimer_Tick' does not exist in the current context
This is an example of what I have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Data.OleDb;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Timers;

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    System.Timers.Timer myTimer = new System.Timers.Timer();
    myTimer.Interval = 30000;
    myTimer.Tick += new EventHandler(myTimer_Tick);
    myTimer.Enabled = true;
    myTimer.Start();
}

public void MyTimer_Tick(object sender, EventArgs e)
{
    MessageBox.Show("30 seconds scince you added a row");
}

private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
    //remove a timer here that corresponds to this row,
    //if row removed before timer elapsed
}

Thankyou for any help I may receive.

A: You should be using
System.Windows.Forms.Timer

Instead of
using System.Timers;

See here vs here

A: First, the System.Timer has no .Tick event. Use Timer.Elapsed instead:
myTimer.Elapsed += new EventHandler(MyTimer_Tick);

[EDIT: Replaced List with Dictionary]
You also need multiple timers and a way to keep the timer in scope. Using a Dictiory<DataGridViewRow, Timer> object declared at the class level:
private Dictionary<DataGridViewRow, System.Timers.Timer> timers = new Dictionary<DataGridViewRow, System.Timers.Timer>();

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    var myTimer = new System.Timers.Timer();
    myTimer.Interval = 30000;
    myTimer.Elapsed += new ElapsedEventHandler(MyTimer_Tick);
    myTimer.Enabled = true;

    // Potential bug source: If you programmatically add multiple rows at once,
    // a timer is only added to the first row
    timers.Add(dataGridView1.Rows[e.RowIndex], myTimer);
}

Now in the RowsRemoved event handler, you get the row index and remove it from the timers dictionary; eg, timers.RemoveAt(rowIndex).


text:
Q: How do I retrieve a image from a rss entry? I'm currently working on a news app and would really like to add a image to a table row of the image for the news article.
I have managed to parse everything else, it's just I can't parse the image url.
This is the code I used for striping the HTML from the feed.
.M file
- (NSString *)stringByStrippingHTML:(NSString *)inputString
{
NSMutableString *outString;

if (inputString)
{
    outString = [[NSMutableString alloc] initWithString:inputString];

    if ([inputString length] > 0)
    {
        NSRange r;

        while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        {
            [outString deleteCharactersInRange:r];
        }
    }
}

return outString;

}
.H file
- (NSString *)stringByStrippingHTML:(NSString *)inputString;

I'm quite new to xcode and code in general so I'm not familiar in this stuff.
I just can't figure out in parsing the url for the image.
This is the code for the tablerow appearance.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

cell.textLabel.numberOfLines=3;
cell.detailTextLabel.numberOfLines=4;

RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];

NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];

NSString * articleDescrptionString = [[[NSString alloc] init] autorelease];
articleDescrptionString = entry.articleDescription;

cell.textLabel.text = entry.articleTitle;

NSString *plainString = [self stringByStrippingHTML:entry.articleDescription ];

cell.imageView.image = [UIImage imageNamed: entry.articleImageUrl];

//NSString *rangedString = [plainString substringToIndex:249];  //0 to 249 makes it 250 characters

//cell.detailTextLabel.text = articleDescrptionString;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@", articleDateString, plainString];

//UIImage *theImage = [UIImage imageWithContentsOfFile:entry.articleImageUrl];
//cell.imageView.image = theImage;

return cell;
}

Any code I've commented out is currently not used at the moment at it's not used.

A: You need to Load the Image into a NSData object first...
NSURL *imgURL = [NSURL URLWithString:entry.articleImageUrl];
NSData *imgData = [NSData dataWithContentsOfURL:imgURL];
cell.imageView.image = [UIImage imageWithData:imgData];

But you will have to do it asynchronously, because if you do it without a lazy image load you TableView will be stocking while scrolling...


text:
Q: Difference between gzip -d and zcat I was wondering what the difference is when decompressing using gzip -d and zcat.
Sometimes when I try gzip -d it says unknown suffix -- ignored. However, zcat works perfectly.

A: The zcat equivalent using gzip is gzip -dc, and when used that way, it doesn't care about the file extension. Both variants decompress their input and output the result to their standard output.
gzip -d on the other hand is intended to decompress a file, storing the uncompressed contents in another file. The output file's name is calculated from the input's, by removing its extension; files whose extension doesn't match one of those handled by gzip are ignored. The documentation says that

gunzip takes a list of files on its command line and replaces each file whose name ends with .gz, -gz, .z, -z, or _z (ignoring  case)  and  which  begins with the correct magic number with an uncompressed file without the original extension.
         gunzip also recognizes the special extensions .tgz and .taz as shorthands for .tar.gz and .tar.Z respectively.

Files with no extension, or any other extension, are ignored, producing the message you see:

unknown suffix — ignored


text:
Q: Best place to insert JavaScript within a HTML document
Possible Duplicate:
Where is the best place to put

Then again, having your script inline within the page, you can have it where you want.  Within the headsection of the page, it loads beforehand, and therefore can pre-process if needed.  If you have it let's say during the body portion of the page, it will load with the normal flow of the page.
Having everything on the same file, I would have the script in the head and, if needed, call functions afterwards in the body.
Hope this helps.
edit
Keep in mind that the main goal should be readability and re-usability of your code.  Therefore, whatever makes this happen in the most efficient way, I would have to say is the best way.

A: Putting


text:
Q: installing another language fonts in Lubuntu I want to type in another language(nepalese to be specific) in abiword or libre office in Lubuntu. I am new to linux so hoping for help

A: Note: These screenshots are outdated and need to be updated. I don't have lubuntu and can't get access to it. If anyone would like to take updated screenshots and edit them into this post, that would be greatly appreciated. Until then (if it happens), the screenshots will stay as 10.04 ones.
Adding a keyboard language

*

*Navigate to System → Preferences → Keyboard.

*In the Keyboard Preferences dialog, select the Layouts tab, and click Add.

*You can select a country and then choose an language and keyboard variant.  Note that some countries, such as the United States, may show several languages.  Once you've made your selection, you can preview it on the sample keyboard displayed below the menu.

Alternately, on the second tab, select a language and then choose a variant.  Click Add when you've made your selection.

*Now you'll notice that there are two languages listed in the Keyboard Preferences, and they're both ready to use immediately.  You can add more if you wish, or close the dialog.

Switching between languages
Manually

*

*When you have multiple input languages installed, you'll notice a new icon in your system tray on the top right. It will show the abbreviation of the country and/or language name that is currently selected. Click the icon to change the language.

*Right-click the dialog to view available languages (listed under Groups), open the Keyboard Preferences dialog again, or show the current layout.

*If you select Show Current Layout you'll see a window with the keyboard preview we saw previously when setting the keyboard layout.  You can even print this layout preview out to help you remember a layout if you wish.

Shortcuts

*

*By default, you can switch input languages in Ubuntu from the keyboard by pressing both ALT keys together.  Many users are already used to the default ALT + Switch combination to switch input languages in Windows, and we can add that in Ubuntu.  Open the keyboard preferences dialog, select the Layout tab, and click Options.

*Click the plus sign beside Key(s) to change layout, and select ALT+SHIFT. Click Close, and you can now use this familiar shortcut to switch input languages.

Extra Option - LED Indicator
If your keyboard supports LED indicators, then you can add this feature to notify you when you're using a different input method.
The layout options dialog offers many more neat keyboard shortcuts and options. One especially neat option was the option to use a keyboard LED to show when we're using the alternate keyboard layout. I selected the ScrollLock light since it's hardly used today, and now it lights up when we're using our other input language.

Credits
All credit goes to HowToGeek


text:
Q: Cycling through tmux panes I am having trouble intuitively cycling through tmux panes. I use mod-n and mod-p, but I don't like having to execute 2 keypresses.
Recently, I discovered https://github.com/christoomey/vim-tmux-navigator, which works great for navigating tmux splits. Is there a solution for making navigating tmux panes as intuitive (preferably for a Vim user)?

A: Add the following to your ~/.tmux.conf. The -n option  means it is not necessary to use the prefix key (which I assume is the first of the two key presses you're talking about).
bind-key -n M-n next-window
bind-key -n M-p previous-window

Run tmux source ~/.tmux.conf to apply.


text:
Q: BluetoothSocket Timeout or readline timeout I am currently working on an application that talks to a serial device via bluetooth.  I have it implemented in a way that opens the connection to the bluetooth device.  It seems like it connects fine.  When it performs the reader.readline() it seems like it hangs.  It never comes back.  The device itself comes back with the following when it responds.
RD,97,101,100,41613,3000,3,0,153,153,4120,161,4,0,97,102,103,220,20,493,4568,3
000,100,0,100,5,
which is what I am expecting back.  However I need to time out the reader.rea
package com.clarke.android.smartflow;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.http.util.EncodingUtils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.xyx.android.activity.Main;
import com.xyx.android.errors.ErrorService;
import com.xyx.android.events.EventDeviceDetail;

public class SmartFlowService {

    private static final String CLASSTAG = SmartFlowService.class.getSimpleName();
    private static final String DEVICE_NAME = "FireFlyBP"; //FireFlyBP-70D0

    private static BluetoothSocket bluetoothSocket;
    private static BufferedWriter writer = null;
    private static BufferedReader reader = null;
    private static BluetoothAdapter bluetoothAdapter;
    private static BluetoothDevice bluetoothDevice = null;
    private static boolean isConnected = false;
    static Handler mSendHandler = new Handler();

    private InputStream mmInStream;

    //private final OutputStream mmOutStream;

    private static ArrayList<SmartFlowListener> listeners = new ArrayList<SmartFlowListener>();

    public static void addSmartFlowListener(SmartFlowListener listener) {
        listeners.add(listener);
    }

    public static void removeSmartFlowListener(SmartFlowListener listener) {
        listeners.remove(listener);
    }

    private static void fireSmartFlowEvent(EventDeviceDetail eventDeviceDetail) {
        SmartFlowEvent smartFlowEvent = new SmartFlowEvent(SmartFlowService.class, eventDeviceDetail);
        for (Iterator<SmartFlowListener> iterator = listeners.iterator(); iterator.hasNext(); ) {
            SmartFlowListener listener = iterator.next();
            listener.onSmartFlowEvent(smartFlowEvent);
        }
    }

    public static void connect() throws Exception {
        Log.d(Main.LOGTAG, CLASSTAG +" connect");

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        for (Iterator<BluetoothDevice> iterator = pairedDevices.iterator(); iterator.hasNext(); ) {
            BluetoothDevice bd = iterator.next();
            Log.d(Main.LOGTAG, CLASSTAG +" found device "+ bd.getName());
            if (bd.getName().startsWith(DEVICE_NAME)) {
                Log.d(Main.LOGTAG, CLASSTAG +" using device "+ bd.getName() +" "+ bd.getBluetoothClass().toString());
                bluetoothDevice = bd;
            }
        }

        if (bluetoothDevice != null) {
            //socket = bd.createRfcommSocketToServiceRecord(java.util.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            Method m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            bluetoothSocket = (BluetoothSocket)m.invoke(bluetoothDevice, Integer.valueOf(1));
            bluetoothSocket.connect();
            isConnected = true;
        } else {
            throw new Exception("Could not find bluetooth device");
        }
    }

    public static String sendR() throws Exception {

        return send("R");
    }

    public static String sendS(Integer targetRate, Integer pcOffCode) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("S,");
        if (targetRate != null) {
            sb.append(targetRate);
            sb.append(",");
        }
        if (pcOffCode != null) {
            sb.append(pcOffCode);
        }
        sb.append("\r\n");
        return send(sb.toString());
    }

    public static String send(String request) throws Exception {
        Log.d(Main.LOGTAG, CLASSTAG +" send");
        String response = null;
        InputStream mmInStream;
        StringBuilder swriter = new StringBuilder();
        //int swriter = 0;

        try {
            connect();
            if (isConnected) {
                writer = new BufferedWriter(new OutputStreamWriter(bluetoothSocket.getOutputStream()));
                reader = new BufferedReader(new InputStreamReader(bluetoothSocket.getInputStream()));

                writer.write(request);
                writer.flush();

                response = reader.readLine();
                // Keep listening to the InputStream while connected
                fireSmartFlowEvent(new EventDeviceDetail(response));
                Log.d(Main.LOGTAG, CLASSTAG +" send "+ response);
                Log.d(Main.LOGTAG, CLASSTAG +" send "+ response);
                bluetoothSocket.close();
                isConnected=false;
            } else {
                throw new Exception("No Bluetooth connection");
            }
            //bluetoothSocket.close();

        } catch (Exception e) {
            Log.e(Main.LOGTAG, CLASSTAG +" send", e);
            fireSmartFlowEvent(new EventDeviceDetail(e));
            isConnected = false; //force a reconnection retry
            throw e;
        }
        return response;
    }

    public static void close() {
        Log.d(Main.LOGTAG, CLASSTAG +" close");
        try
        {
            if (writer != null) { writer.close(); }
            if (reader != null) { reader.close(); }
            if (bluetoothSocket != null) { bluetoothSocket.close(); }
            isConnected = false;
        }
        catch (Throwable t)
        {
            Log.d(Main.LOGTAG, CLASSTAG +" close", t);
            ErrorService.log(t);
        }
    }
}


text:
Q: Passing data to child component but getting undefined after onChanges Can anybode answer, why after passing data to childs component, this.rows becomes and passed data become undefined
parent component:
this.report$ = this.finInfoClient.getFinancialOperationsReport(params);

<app-financial-operations-grid [data]="rep.operations"
(gridItemSelected)="itemSelected($event)">
</app-financial-operations-grid>

child component:
@Input() data: FinancialOperation[];
rows: FinancialOperation[] | null;
get root(): FinancialOperation[] {return this.rows.filter(d => d.parentId === undefined || d.parentId === null);}
ngOnChanges(changes: SimpleChanges) {
   if (changes['data']) {
       this.rows = this.data;
   }
}

and after onChanges completed all local variables become undefined

A: Try like this:
ngOnChanges(changes: SimpleChanges) {
   const dataChange = changes.data;

   if (dataChange != undefined ) {
     this.rows = dataChange.currentValue
   }
}

A: Your report is a stream. You might need to pass your report.operations to child component with async pipe too.
Like this:
<app-financial-operations-grid [data]="(report$ | async).operations"
...


text:
Q: Invalid request error while creating customer in Stripe I am working on a payment gateway using Stripe API. I had split the card element into three elements as: cardnumer, cvc and cardExpiry. I have created the token using only cardnumber element and I am trying to create the customer in stripe.
I am getting an error as :
Request req_vL0Z2mkBIrhu7N: Invalid object
 /home/nishant/Development/ecommerce/project/shop/views.py in order_view

                source = request.POST['stripeToken']

     …

▶ Local vars
/home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_resources/abstract/createable_api_resource.py in create

            response, api_key = requestor.request("post", url, params, headers)

     …

▶ Local vars
/home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in request

            resp = self.interpret_response(rbody, rcode, rheaders)

     …

▶ Local vars
/home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in interpret_response

                self.handle_error_response(rbody, rcode, resp.data, rheaders)

     …

▶ Local vars
/home/nishant/Development/venv/lib/python3.6/site-packages/stripe/api_requestor.py in handle_error_response

            raise err

     …

▶ Local vars

Here is my payment.html:
 var stripe = Stripe('pk_test_nnGYKgpxl7AmicqNbcoGIMqQ008d6IpXgw');

  // Create an instance of Elements.
  var elements = stripe.elements();

  var style = {
    base: {
      color: '#32325d',
      fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
      fontSmoothing: 'antialiased',
      fontSize: '16px',
      '::placeholder': {
        color: '#aab7c4'
      }
    },
    invalid: {
      color: '#fa755a',
      iconColor: '#fa755a'
    }
  };

  // Create an instance of the card Element.
  **var cardnumber = elements.create('cardNumber', {     **
    classes : {
      base : "form-control",
      focus : "green",
      invalid : "error",
    },
    style : style
  });

   ** var cvc = elements.create('cardCvc', {      **
    classes : {
      base : "form-control",
      focus : "green",
      invalid : "error",
    },
    style : style
  });

   ** var exp = elements.create('cardExpiry',{     **
        classes : {
          base: "form-control",
          invalid : "error",
        },
      style : style
    });
  // Add an instance of the card Element into the `card-element` <div>.
  cardnumber.mount('#cardnumber');         **
  cvc.mount('#cardcvc');                   **
  exp.mount('#cardexpiry');                **

  // Handle real-time validation errors from the card Element.
  cardnumber.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  cvc.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  exp.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
      displayError.textContent = event.error.message;
    } else {
      displayError.textContent = '';
    }
  });

  // Handle form submission.
  var form = document.getElementById('payment-form');
  form.addEventListener('submit', function(event) {
    event.preventDefault();

    stripe.createToken(cardnumber).then(function(result) {          ***
      if (result.error) {
        // Inform the user if there was an error.
        var errorElement = document.getElementById('card-errors');
        errorElement.textContent = result.error.message;
      } else {
        // Send the token to your server.
        stripeTokenHandler(result.token);
      }
    });
  });

  // Submit the form with the token ID.
  function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
  }

My views.py is creating customer as:
stripe.Customer.create(
            name = request.POST['name'],
            email = request.POST['email'],
            address = request.POST['address'],
            source = request.POST['stripeToken']
            )

I am new to stripe. How can I resolve this?

A: Try passing the address as a dictionary instead of a flat string [1]:
stripe.Customer.create(
  description="My First Test Customer (created for API docs)",
  address = {'line1': 'one two three'}
)

Hope that helps!
[1] https://stripe.com/docs/api/customers/create?lang=python#create_customer-address

A: You could also use the API like so:
export const createStripeCustomer = (customerInfo) => {
    const address = customerInfo.address;
//The next line is for mapping the address as a key value
    const addressString = `address[line1]=${address.streetAndNumber}&address[city]=${address.city}&address[country]=${address.country}&address[postal_code]=${address.postalCode}`;
    const metadataString = `metadata[businessNumber]=${customerInfo.businessNumber}&metadata[manager]=${customerInfo.managerName}`
    const bodyToEncode = {
        email: customerInfo.email,
        name: customerInfo.salonName,
        phone: customerInfo.phoneNumber
    };
    const encodedBody = new URLSearchParams(bodyToEncode).toString() + `&${addressString}&${metadataString}`;
    return doPostUrlEncoded('https://api.stripe.com/v1/customers', encodedBody);
}

const doPostUrlEncoded = (url: string, body: string) => {
    return fetch(url, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            Authorization: 'Bearer ' + STRIPE_API_KEY
        },
        body: body
    }).then(function (response) {
        return response.json();
    }).catch(function (error) {
        console.error('Error:', error);
    });
}


text:
Q: Limit of $f_n(x) = n\log(\frac{nx+1}{nx-1})$ and its uniform covergence Let $f_n(x) = n\log(\frac{nx+1}{nx-1})$. What is the pointwise limit of $f_n$ for $x \in[1,\infty]$? Is it uniformly convergent?
$$\lim_{n\longrightarrow \infty}n\log(\frac{nx+1}{nx-1})=\lim_{n\longrightarrow \infty}\frac{\log\left(\frac{x+\frac{1}{n}}{x-\frac{1}{n}}\right)}{\frac{1}{n}}\stackrel{H}{=}\lim_{n\longrightarrow \infty}\frac{\frac{-2x}{n^2}\frac{1}{(x-\frac{1}{n})(x+\frac{1}{n})}}{\frac{-1}{n^2}}=\lim_{n\longrightarrow \infty}\frac{2x}{(x-\frac{1}{n})(x+\frac{1}{n})}=\frac{2}{x}$$
Is that correct? And how to check uniform covergence? I would really like not to search for $\sup$ of $|n\log(\frac{nx+1}{nx-1}) - \frac{2}{x}|$...

A: Looks right to me. The supremum check is pretty easy here. Note that,
\begin{align}
g(x) &:= \frac 2x - n\log(\frac{nx+1}{nx-1}) \\
&= \frac 2x - n\log(nx+1) + n\log(nx-1) \\
\implies g'(x) &= -\frac 2{x^2} - \frac {n^2}{nx+1} + \frac {n^2}{nx-1} \\
&= -\frac 2{x^2} + \frac {2n^2}{(nx+1)(nx-1)} \\
&= -\frac 2{x^2} + \frac {2n^2}{n^2x^2-1} \\
&= -\frac 2{x^2} + \frac {2}{x^2-\frac 1{n^2}} \\
&\geq 0
\end{align}
So $g(x)$ is monotonic and approaches it's supremum at an endpoint. It's pretty clear that $\lim_{x\to\infty}g(x)=0$, so $\sup_{x\in[1,\infty)}|g(x)| = |g(1)| = |2-n\log(\frac{n+1}{n-1})| \underset{n\to\infty}{\longrightarrow} 0$

A: Your pointwise limit is correct (you could have checked that with Wolfram Alpha or such). I haven't checked it in full detail, the derivatives in the L'Hopital's rule step look like they might have a small error (one that goes away as $n \to \infty$, however).
To justify uniformity, you can compute the limit in a different way entirely. If we bring the $n$ inside the logarithm and do long division, then we get
$$\log \left ( \left ( \frac{nx+1}{nx-1} \right )^n \right ) = \log \left ( \left ( 1 + \frac{2}{nx-1} \right )^n \right ) = \log \left ( \left ( 1 + \frac{1}{n} \frac{2}{x-1/n} \right )^n \right ) $$
You may recognize the way I've written the inside as converging to $\exp(2/x)$. So if you know how to show that $\left ( 1 + x/n \right )^n$ converges uniformly (on compact sets) to $\exp(x)$, then you can argue that the logarithm is uniformly continuous on $[1,\infty)$ to finish the problem.


text:
Q: Browser service in sql server clustering Straightforward this one - when failing over from one sql server 2008 node to another, should the browser service be running on the passive node ? At the moment, on attempting to failover, a an error is produced saying that certain clustering related dlls can't be found. The dlls are present, I just wondered whether this browser service was stopping access.

A: There really isn't a short answer because there are a few hidden questions in the question.
A few thoughts to help here:
1.) The Browser service is not cluster aware, so it generally would be just running on each node. The browser is really used to handle incoming connections to a SQL instance. When you don't have a fixed port, are using named instances and in other situations the browser handles the "finding" of the instance a client desires to connect to. So if you have it running on the active node and it is being used to direct connections, I would make sure it is automatic and running on each node.
2.) That said the browser shouldn't prevent DLLs from being found or take any part in preventing or allowing a failover. So the issue you are having with failing over is most likely not related to the browser but something else. Instead you should be looking at things like - Have you failed over before? Is this a new install of a second node? Have there been any required restarts missed on that node? Did the install throw up any errors? Are there issues in the clustering logs? Can you post the exact error you are receiving? Have you searched for that exact error?


text:
Q: Javascript: Run a script depending on which button is clicked Can someone enlighten me on this please. I was trying to implement a simple Javascript function. The idea is, to run a conditional script depending on which button is clicked. Can't seem to figure this out:

<form id="form1" onSubmit="whichButton();">
<button id="btn1">Button 1</button>

<button id="btn2">Button 2</button>

<button id="btn3">Button 3</button>

<button id="btn4">Button 4</button>

</form>

Thanks in advance!

A: You want to add onclick handlers to the button tags:

<form id="form1" >
<button id="btn1" onclick="whichButton(this)">Button 1</button>

<button id="btn2" onclick="whichButton(this)">Button 2</button>

<button id="btn3" onclick="whichButton(this)">Button 3</button>

<button id="btn4" onclick="whichButton(this)">Button 4</button>

</form>

EDIT:
To run different code based on which button was clicked, use an IF statement similar to your original post, which I've edited above.  // you can take that alert out, or move into each if/else if scope.

A: Pass the from to your function, then find the active element:
<form id="form1" onSubmit="whichButton(this);">
    Buttons...
</form>

And the JavaScript:
function whichButton(form) {
    var clicked = form.querySelector(":active");
    switch(clicked.id) {
    case "btn1":
        // do stuff
        break;
    // add more cases
    }
}

Note that I'm not certain about this, but I've tested it and it seems to work. Note that IE7 and older do not support :active, I have no idea how to make this work in those older versions.
EDIT: Here's a Fiddle to demonstrate.

A: You can try with jQuery the following:

<form>
<button class="btn">Button 1</button>

<button class="btn">Button 2</button>

<button class="btn">Button 3</button>

<button class="btn">Button 4</button>

</form>

A: Use AJAX to get the scripts, insert them somewhere in the DOM and use initialize() to run them.
$.get('js/script1.js', function(data) {
    $('#dummydiv').html(data);
    initialize();
});


text:
Q: Python Merge line from two different files into one list I am trying to build a list from lines from two different files.
File1.txt
['2.02', '-3.88', '15.25']
['4.40', '-2.36', '14.97']
['5.44', '0.34', '7.34']
['5.76', '0.41', '7.60']
['5.35', '0.19', '13.95']

File2.txt
['P1']
['P2']
['P3']
['P4']
['P5']

desirable output
['2.02', '-3.88', '15.25', 'P1']
['4.40', '-2.36', '14.97', 'P2']
['5.44', '0.34', '7.34', 'P3']
['5.76', '0.41', '7.60', 'P4']
['5.35', '0.19', '13.95', 'P5']

I tried to simple add lines
combined = open('file1.txt').readlines() + open('line2.txt').readlines()

output
["['2.02', '-3.88', '15.25']\n", "['4.40', '-2.36', '14.97']\n", "['5.44', '0.34', '7.34']\n", "['5.76', '0.41', '7.60']\n", "['5.35', '0.19', '13.95']\n", 'P1\n', 'P2\n', 'P3\n', 'P4\n', 'P5\n']

I also wrote a function which tries to merge both in a third file file3.txt
def combiner():
with open("file1.txt", 'r') as file1:
    with open('file2.txt', 'r') as file2:
        with open('file3.txt',"w") as file3:
            clines = file1.readlines()
            plines = file2.readlines()
   #Write to third file
            for i in range(len(clines)):
                line = clines[i].strip() + plines[i]
                file3.write(line)

But it still writes in 2 different Lists
cat file3.txt
['2.02', '-3.88', '15.25']['P1']
['4.40', '-2.36', '14.97']['P2']
['5.44', '0.34', '7.34']['P3']
['5.76', '0.41', '7.60']['P4']
['5.35', '0.19', '13.95']['P5']

The best would be a function which return such a list.

A: Even though the lines in the files resemble lists, you're actually treating them as strings.  You can use ast.literal_eval to evaluate the strings into lists, combine them, and then write them to the other file
from ast import literal_eval

def combiner(infile1, infile2, outfile):
    with open(infile1) as f1, open(infile2) as f2, open(outfile, 'w+') as f3:
        f1_lists = (literal_eval(line) for line in f1)
        f2_lists = (literal_eval(line) for line in f2)
        for l1, l2 in zip(f1_lists, f2_lists):
            f3.write(str(l1+l2) + '\n')  # This could also be print(l1+l2, file=f3)

A: Using pandas
import ast

df1 = pd.read_csv(file1, sep='\n', header=None, names=['data'])
df2 = pd.read_csv(file2, sep='\n', header=None, names=['data'])

parse = lambda d: d.transform(ast.literal_eval)

df1['data'] = parse(df1.data)
df2['data'] = parse(df2.data)

Then just
df1 + df2

    data
0   [2.02, -3.88, 15.25,  P1]
1   [4.40, -2.36, 14.97,  P2]
2   [5.44, 0.34,  7.34,   P3]
3   [5.76, 0.41,  7.60,   P4]
4   [5.35, 0.19,  13.95,  P5]


text:
Q: How to Earth (ground electrically) my laptop My computer zaps me with strong zaps which can get quite annoying.  So I need a way to Earth (ground electrically)my laptop.
Is there any danger (for me or my laptop) in connecting a crocodile clip from my laptop case to the earthing (ground) wire at the wall (Spanish wall socket) and will that solve the problem?

A: There are two possibilities here.
One is that you are building up a static charge when walking across your carpet, sliding off of or onto your chair... something like that. When you touch metal on the laptop you are discharging that static charge. Does it happen more than once? If not, it's this sort of issue. The laptop is already providing a ground, so adding a grounding wire won't help.
What should help is grounding yourself to something else, preferably something with a high-resistance path to ground, before touching the laptop. Discharging through the resistance will cause it to happen gradually, so you won't feel the spark. One megohm or so is a good choice (this is typically what's in the anti-static grounding straps). If you don't know what that means, get a friend with good electronics construction knowledge to help you.
The other possibility is that the AC adapter of the laptop is "leaking" AC onto the laptop's chassis. If you feel it every time you touch whatever it is that you're touching, it is this sort of problem. This is an extremely dangerous situation, and it will not get better on its own. The cure is to replace the AC adapter... Preferably before you ever use the laptop again.

A: Jamie Hanrahan gave an excellent answer but I think there is another possibility apart from what he described.  It seems that many people have zapping issues with their laptops and the zaps seem to be more than just static.  See this page for a lot of examples
From that same page, a user responded with the following (and I quote):

"If you have the laptop in your lap, and if you are wearing shorts,
the areas of your legs that are in contact with the screws will feel
uncomfortably tingly - like there are pins being poked into the
surface of your skin, but not deeply. The sweatier you are, the more
galvanic reaction (the more it hurts). This is NOT a power supply
problem, so getting another DC power supply is not going to cure the
matter.
What this is, is the AC voltage that is sinked to ground through a
number of circuits that rely on higher voltages stepped up through DC
to DC converters (see:
http://en.wikipedia.org/wiki/DC-to-DC_converter). Displays take higher
voltages to operate. An oscillator converts the laptop's DC voltage to
AC, steps up the voltage, rectifies it, then filters it. This is the
residual AC voltage from that process. It is a byproduct of
miniaturization and not having enough space for adequate shielding or
having an adequate groundplane. You become part of the ground and
might be a better ground than the rest of the device.
As the OP stated, 48 mA is usually not enough to disrupt your heart's
electrical activity, but it is a big discomfort. At first, I used a
book under the laptop. Then I took some black electrical tape and put
it over each of the screws on the bottom of my Dell. It works, but
then, the laptop also gets hot. That's another issue."

Connecting a crocodile clip between my network cable and a ground did fix the problem...HOWEVER AS MENTIONED BY OTHERS, YOU SHOULD NEVER MESS WITH ELECTRICITY WITHOUT PROFESSIONAL HELP.  For example, if the AC adapter is leaking AC (as suggested by Jamie) and you touch the crocodile clip, YOU COULD BE ELECTROCUTED.
Here is a page describing similar ways to ground your laptop.  AGAIN, ALTHOUGH IT MAY APPEAR SAFE, IT CAN BE VERY DANGEROUS TO EXPERIMENT WITH THESE DESCRIBED METHODS WITHOUT PROFESSIONAL HELP.


text:
Q: How to use an If-statement whilst looping through multiple rows Is it possible to use two different cell ranges in an if-statement and then have a result of that if-statement inserted into another range?
Code:
If Range("H3:H26").Value > Range("K3:K26") Then Range("N3:N26").Value = "Over"
ElseIf Range("H3:H26").Value < Range("K3:K26") Then Range("N3:N26").Value = "Under"
ElseIf Range("H3:H26").Value = Range("K3:K26") Then Range("N3:N26").Value = "Good"
Else: Range("N3:N26") = "No"
End If

I understand why having a two different ranges in an if-statement wouldn't work but I'm trying to find a way to have this code work without having multiple if statements for different rows

A: You cannot use comparison operators with arrays in VBA. When you do Range.Value with a multicell range, you are creating a 2D array. Comparison Operators like > and < only work with individual values, not with arrays of values in VBA.
You need to loop through the rows, checking each cell from H3:H26 and K3:K26 as individual values.
Sub Example()
    Dim i As Long
    For i = 3 To 26
        If Cells(i, "H").Value > Cells(i, "K").Value Then
            Cells(i, "N").Value = "Over"
        ElseIf Cells(i, "H").Value < Cells(i, "K").Value Then
            Cells(i, "N").Value = "Under"
        ElseIf Cells(i, "H").Value = Cells(i, "K").Value Then
            Cells(i, "N").Value = "Good"
        Else
            Cells(i, "N").Value = "No"
        End If
    Next
End Sub

You can use an If Statement or the much cleaner looking Select Case statement
Sub ExampleLoop()
    Dim i As Long
    For i = 3 To 26
        Select Case Cells(i, "H").Value
        Case Is > Cells(i, "K").Value
            Cells(i, "N").Value = "Over"
        Case Is < Cells(i, "K").Value
            Cells(i, "N").Value = "Under"
        Case Cells(i, "K").Value
            Cells(i, "N").Value = "Good"
        Case Else
            Cells(i, "N").Value = "No"
        End Select
    Next
End Sub

You could also not need to loop or use any if statement by making use of the IF formula in excel.
Sub ExampleFormula()
    Range("N3:N26").Formula = "=IFERROR(IF(H3>K3,""Over"",IF(H3<K3,""Under"",""Good"")),""No"")"
End Sub

A: Compare Two Columns

Usage (The Calling Procedure(s))
Sub TestSimple()

    Dim ws As Worksheet: Set ws = ActiveSheet 'improve!
    Dim rg As Range: Set rg = ws.Range("K3:N26")
    CompareTwoColumns rg, 1, 4, 7, "Over", "Good", "Under", "No"

End Sub

Sub TestChecks()

    Dim ws As Worksheet: Set ws = ActiveSheet 'improve!
    Dim rg As Range: Set rg = ws.Range("K3:N26")

    Dim Compared As Boolean
    Compared = CompareTwoColumns(rg, 1, 4, 7, "Over", "Good", "Under", "No")

    If Not Compared Then Exit Sub

    MsgBox "The comparison finished successfully.", vbInformation

End Sub

Help (The Called Procedures)

*

*The first one is actually a method written as a function utilized in the TestChecks procedure.

*The second is called only by the first.

Function CompareTwoColumns( _
    ByVal SourceRange As Range, _
    ByVal FirstColumn As Long, _
    ByVal SecondColumn As Long, _
    ByVal DestinationColumn As Long, _
    ByVal StringGT As String, _
    ByVal StringEQ As String, _
    ByVal StringLT As String, _
    ByVal StringElse As String) _
As Boolean
    Const ProcName As String = "CompareTwoColumns"
    On Error GoTo ClearError

    Dim rg As Range
    ' Source
    Set rg = SourceRange.Columns(FirstColumn)
    Dim fData() As Variant: fData = GetColumnRange(rg)
    ' Compare
    Set rg = SourceRange.Columns(SecondColumn)
    Dim sData() As Variant: sData = GetColumnRange(rg)
    ' Destination
    Set rg = SourceRange.Columns(DestinationColumn)
    Dim rCount As Long: rCount = rg.Rows.Count
    Dim dData() As String: ReDim dData(1 To rCount, 1 To 1)

    Dim fValue As Variant
    Dim sValue As Variant
    Dim r As Long
    Dim dString As String

    For r = 1 To rCount
        fValue = fData(r, 1)
        sValue = sData(r, 1)
        If VarType(fValue) = vbDouble Then
            If VarType(sValue) = vbDouble Then
                Select Case fValue
                    Case Is > sValue: dString = StringGT
                    Case sValue: dString = StringEQ
                    Case Is < sValue: dString = StringLT
                End Select
            End If
        End If
        If Len(dString) = 0 Then
            dData(r, 1) = StringElse
        Else
            dData(r, 1) = dString
            dString = vbNullString
        End If
    Next r

    SourceRange.Columns(DestinationColumn).Value = dData
    CompareTwoColumns = True

ProcExit:
    Exit Function
ClearError:
    MsgBox "' Run-time error '" & Err.Number & "':" & vbLf & vbLf _
        & Err.Description, vbCritical, ProcName
    Resume ProcExit
End Function

Function GetColumnRange( _
    ByVal rg As Range, _
    Optional ByVal ColumnNumber As Long = 1) _
As Variant
    If rg Is Nothing Then Exit Function
    If ColumnNumber < 1 Then Exit Function
    If ColumnNumber > rg.Columns.Count Then Exit Function

    With rg.Columns(ColumnNumber)
        If rg.Rows.Count = 1 Then
            Dim Data As Variant: ReDim Data(1 To 1, 1 To 1): Data(1, 1) = .Value
            GetColumnRange = Data
        Else
            GetColumnRange = .Value
        End If
    End With

End Function


text:
Q: WP-DEPLOY : Cannot Push database So I've been trying to set up Wp-Deploy for about 3 weeks now :(
I have a digitalocean droplet that I am using for staging and was able to finally get my local environment to deploy the files to the server, however, I cannot get the database commands to work. When I try and backup the database I get the following output
    dixon@Sphinx /var/www/html $ bundle exec cap staging db:backup
00:00 db:backup_name
      01 mkdir -p /var/www/vhosts/thedixonbuilds.com/httpdocs/shared/db_backups
    ✔ 01 root@<ip address> 1.748s
      02 wp db export - | gzip > /var/www/vhosts/thedixonbuilds.com/httpdocs/shared/db_backups/20190210165609.sql.gz
      02 /usr/bin/env:
      02 'wp'
      02 : No such file or directory
      02
    ✔ 02 root@<ip address> 0.244s
      Downloading db_backups/20190210165609.sql.gz 100.0%
      03 rm /var/www/vhosts/thedixonbuilds.com/httpdocs/shared/db_backups/20190210165609.sql.gz
    ✔ 03 root@<ip address> 0.228s

and when I try and run the db:push
00:00 db:backup_name
      01 mkdir -p /var/www/vhosts/thedixonbuilds.com/httpdocs/shared/db_backups
    ✔ 01 root@<ip address> 1.399s
      02 mkdir -p db_backups
    ✔ 02 dixon@localhost 0.003s
      03 wp db export - | gzip > db_backups/20190210170146.sql.gz
    ✔ 03 dixon@localhost 0.271s
      Uploading db_backups/20190210170146.sql.gz 100.0%
      04 gzip -c -d /var/www/vhosts/thedixonbuilds.com/httpdocs/shared/db_backups/20190210170146.sql.gz | wp db import -
      04 bash: wp: command not found
(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as root@138.68.14.196: gzip exit status: 127
gzip stdout: Nothing written
gzip stderr: bash: wp: command not found

Caused by:
SSHKit::Command::Failed: gzip exit status: 127
gzip stdout: Nothing written
gzip stderr: bash: wp: command not found
/var/www/html/lib/capistrano/tasks/db.rake:148:in `block (4 levels) in <top (required)>'
/var/www/html/lib/capistrano/tasks/db.rake:147:in `block (3 levels) in <top (required)>'
Tasks: TOP => db:push
(See full trace by running task with --trace)

I'm not sure how capistrano achieves the database manipulation or what usr/bin/env  is supposed to contain. Can anyone help me with some leads?
Thanks!

A: Both of those failed for the same reason. Did you not see the errors?
Here they are:
      02 /usr/bin/env:
      02 'wp'
      02 : No such file or directory

And:
gzip stderr: bash: wp: command not found

Both times, your script is trying to run the wp command, but it is not installed or not in your PATH. You need to install it first, and second make sure your PATH is set correctly.