pattern matching – OptionsPattern does not match rule with compound left hand side

OptionsPattern was introduced in Mathematica v6 so I have finally decided to give a try.

Look at this program:

Clear@foo;
foo(options : OptionsPattern()) := {options}
foo(k2 -> 3)
foo(Indexed(k, 2) -> 3)

out:

{k2 -> 3}
foo(Indexed(k, {2}) -> 3)

The rule with compound left hand side has not matched OptionsPattern().

You can replace Indexed by any function (Power, Subscript), it will be the same.

Now compare with old style option pattern:

Clear@foo;
foo(options___Rule) := {options}
foo(k2 -> 3)
foo(Indexed(k, 2) -> 3)

out:

{k2 -> 3}
{Indexed(k, {2}) -> 3}

Matching occurs in all cases.

Is there a bug in OptionsPattern?

Do we need to have a default clause in a compound switch statement in swift?

I run this swift code:

var planet = "Earth" 
switch planet {
  case "Earth", "Mercury", "Venus", "Mars":
    print("Terrestrial planet")
  case "Saturn", "Jupiter", "Uranus", "Neptune":
    print("Jovian planet")
  default:
    print("Unknown planet")
}

It runs perfectly.
But when I run this:

var planet = "Earth" 


switch planet {
  case "Earth", "Mercury", "Venus", "Mars":
    print("Terrestrial planet")
  case "Saturn", "Jupiter", "Uranus", "Neptune":
    print("Jovian planet")
}

I get this error:

Planets.swift:4:1: error: switch must be exhaustive
switch planet {
^
Planets.swift:4:1: note: do you want to add a default clause?
switch planet {
^

So does the switch require a default case?
I tried the same without a compound, and it works.

postgresql – How to allow NULL in foreign keys of a compound primary key

I want to have NULLs in foreign keys of a compound primary key. This is an example of what I would expect to be valid data.

product_id variant_id
123-123 ABC
123-123 NULL
456-456 ABC

I cannot figure out why the following SQL in postgres gives NOT NULL violation constraint me when inserting NULL as variant_id.

CREATE TABLE IF NOT EXISTS inventory.price (
  product_id             UUID NOT NULL, -- this has to be always to a valid product
  variant_id             UUID,          -- this could be NULL
  amount                 MONEY NOT NULL,
  created_at             TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  -- Constraints
  CONSTRAINT inventory_price_pkey PRIMARY KEY (product_id, variant_id),
  CONSTRAINT inventory_price_inventory_product_fkey FOREIGN KEY (product_id)
    REFERENCES inventory.product (id) MATCH FULL,
  CONSTRAINT inventory_price_inventory_variant_fkey FOREIGN KEY (variant_id)
    REFERENCES inventory.variant (id) MATCH SIMPLE,
  CONSTRAINT inventory_price_amount_gt_0 CHECK (amount > '0'::money)
);

And the inspection to information_schema confirms the non-nullable constraint.

column_name column_default is_nullable data_type
product_id NULL NO uuid
variant_id NULL NO uuid
amount NULL NO money
created_at now() NO timestamp with time zone

dnd 5e – Does the Loadstone curse compound every use or only once?

The Loadstone description reads as follows (emphasis mine):

Curse. The stone is cursed, but its magical nature is hidden; detect magic doesn’t detect it. An identify spell reveals the stone’s true nature. If you use the Dash or Disengage action while the stone is on your person, its curse activates. Until the curse is broken with remove curse or similar magic, your speed is reduced by 5 feet, and your maximum load and maximum lift capacities are halved. You also become unwilling to part with the stone.

Unlike most cursed objects, this does not require any attunement. So just being on your person is enough. Since the character does not attune, there is a “trigger” to the curse. In this case, it is when the character uses the Dash or Disengage action. But Dash and Disengage are not one-time things like attunement. One or both can be done multiple times in a minute.

So does each trigger compound the curse, reduce speed and max capacities halved, or is the character cursed only the first time they perform that action and that’s it?

The spell doesn’t specify “the first time you…”, it just says “it activates”. But things can be activated repeatedly so that is not a disqualifier.

I could see a situation where, not knowing that the stone is the issue (since detect magic doesn’t show it as magical) a rogue keeps disengaging and dashing to get away from a foe until they are incapable of movement and are crushed by their own equipment.

19$ Compound token

Don’t have a Coinbase wallet? Join the Quiz and hit $ 19 for the grab you get in the Compound token, you can switch to what you want later! A simple question, a simple answer for which you get money! Invite others!

Check out:

delphi – CanI ask for feedback for my first Compound Component

I asked this Question in StackOverFlow (Delphi) and they suggested that I try here.

“Is there a site to submit my Delphi 7 coding to?
Hi I am learning how to build compound components. My latest works fine, but I am wondering if there is a site where I could submit my code and receive feedback.
I would like this feedback to offer better coding practices with explanations so I can learn”

I have access to the UK’s Royal Postcode Files and use these to help my local Charity’s IT dept. I split thi file in to over 1,000 files of 30,000 lines each.
In aanother folder I have A-Z index files. So the B.csv file contains all Postcodes beginning with B. the format of the file is Postcode, File reference ie

BA13 3PZ,file46.csv 

The idea of my component is for the user to type in a Postcode and get the address. My Component searches the 30,000,000 postcodes finds the correct one, the use then picks the correct address and the address is copied to the underlying external database. It works and is fast but as I want to improve I would be grateful for
any feedback good or bad.

unit BtnPost;

interface

uses Windows, WinTypes, WinProcs, Messages, SysUtils, Classes, Controls,
Forms, Graphics, Extctrls, Eedit, SevenButton, StdCtrls, Dialogs, ESBRtns,
DB, DBCtrls, ABSMain;

type
  TBtnPost = class(TPanel)
   private
    FOnCtrlBtnClick : TNotifyEvent;
    FOnHeightChange : TNotifyEvent;
    FOnAlistClick : TNotifyEvent;
    FFirst : String;
    FPost : string;
    FAddress : TDbMemo;
    FDset : TABSTable;
    FFilesPath : String;
    FIndexPath : String;
    FOnFirstChange : TNotifyEvent;
    FileList : TStringList;
    IndexList : TStringList;
    RawList : TStringList;
    procedure AutoInitialize;
    procedure AutoDestroy;
    function GetFirst : String;
    procedure SetFirst(Value : String);
    function GetPost : String;
    procedure SetPost(Value : String);
    function GetAddress : TDbMemo;
    procedure SetAddress(Value : TDbMemo);
    function GetDset : TABSTable;
    procedure SetDset(Value : TABSTable);
    function GetFilesPath : String;
    procedure SetFilesPath(Value : String);
    function GetIndexPath : String;
    procedure SetIndexPath(Value : String);
    
   protected
    CtrlBtn : TSevenButton;
    Alist : TListbox;
    procedure HeightChange(Sender : TObject); virtual;
    procedure Loaded; override;
    procedure Paint; override;
    procedure FirstChange(Sender : TObject); virtual;
    procedure H_CtrlBtnClick(Sender : TObject); virtual;
    procedure H_AlistClick(Sender : TObject); virtual;
    
   public
    procedure ListSort(LBox:TStrings);
    procedure FindPcode(astr:string);
    procedure MakeMemo(Num:integer);
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    
   published
    Aedit : TEedit;
    property Post : string read GetPost write SetPost;
    property Address : TDbMemo read GetAddress write SetAddress;
    property Dset : TABSTable read GetDset write SetDset;
    property OnCtrlBtnClick : TNotifyEvent read FOnCtrlBtnClick write FOnCtrlBtnClick;
    property OnAlistClick : TNotifyEvent read FOnAlistClick write FOnAlistClick;
    property OnHeightChange : TNotifyEvent read FOnHeightChange write FOnHeightChange;
    property OnFirstChange : TNotifyEvent read FOnFirstChange write FOnFirstChange;
    property OnDblClick;
    property OnDragDrop;
    property OnEnter;
    property OnExit;
    property OnKeyDown;
    property OnKeyPress;
    property OnKeyUp;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnResize;
    property First : String read GetFirst write SetFirst;
    property FilesPath : String read GetFilesPath write SetFilesPath;
    property IndexPath : String read GetIndexPath write SetIndexPath;

   end;
  
procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', (TBtnPost));
end;

procedure TBtnPost.AutoInitialize;
begin
  FileList := TStringList.Create;
  IndexList := TStringList.Create;
  RawList := TStringList.Create;
end;

procedure TBtnPost.AutoDestroy;
begin
  Aedit.Free;
  FileList.Free;
  IndexList.Free;
  RawList.Free;
end;

function TBtnPost.GetFilesPath : String;
begin
  Result := FFilesPath;
end;

procedure TBtnPost.SetFilesPath(Value : String);
begin
  FFilesPath := Value;
end;

function TBtnPost.GetIndexPath : String;
begin
  Result := FIndexPath;
end;

procedure TBtnPost.SetIndexPath(Value : String);
begin
  FIndexPath := Value;
end;

procedure TBtnPost.H_CtrlBtnClick(Sender : TObject);
begin
  if Assigned(FOnCtrlBtnClick) then
  FOnCtrlBtnClick(Sender);
  FPost:=Aedit.Text;
  FFirst:=LeftStr(FPost,1);
  SetFirst(FFirst);
  GetPost;
  FindPcode(Post);
  HeightChange(Self);
 invalidate;
end;

function TBtnPost.GetFirst : String;
begin
 Result := FFirst;
end;

procedure TBtnPost.SetFirst(Value : String);
begin
  FFirst := Value;
  FirstChange(self);
end;

function TBtnPost.GetPost : String;
begin
 Result := FPost;
end;

procedure TBtnPost.SetPost(Value : String);
begin
 FPost:= Value;
end;

function TBtnPost.GetAddress : TDbMemo;
begin
 Result := FAddress;
end;

procedure TBtnPost.SetAddress(Value : TDbMemo);
begin
 FAddress:= Value;
end;

function TBtnPost.GetDset : TABSTable;
begin
 Result := FDset;
end;

procedure TBtnPost.SetDset(Value : TABSTable);
begin
 FDset:= Value;
end;


procedure TBtnPost.FirstChange(Sender : TObject);
begin
  if Assigned(FOnFirstChange) then
  FOnFirstChange(Sender);
  if FIndexPath = '' then
    begin
      ShowMessage('No IndexPath. Closing...');
      Exit;
    end
  else
    begin
      IndexList.LoadFromFile(FIndexPath+FFirst+'.csv');
    end;
end;

constructor TBtnPost.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Aedit := TEedit.Create(Self);
  CtrlBtn := TSevenButton.Create(Self);
  Alist := TListBox.Create(Self);
  Alist.Parent := Self;
  Alist.Align:=alBottom;
  Alist.Height:=0;
  Aedit.Parent := Self;
  Aedit.CharCase:=ecUpperCase;
  Aedit.Visible:=True;
  Height:=30;
  BevelOuter:=bvNone;
  Alist.BorderStyle:=bsNone;
  Alist.BevelOuter:=bvNone;
  Alist.BevelInner:=bvNone;
  Alist.ItemHeight := 19;
  Width := 194;
  Caption := '';
  CtrlBtn.Parent:= Self;
  CtrlBtn.Caption:='Search';
  CtrlBtn.Width:= 64;
  CtrlBtn.Top:=1;
  CtrlBtn.OnClick:=H_ctrlbtnclick;
  Alist.OnClick := H_AlistClick;
  CtrlBtn.Left:=127;
  Visible:=True;
  Aedit.TabOrder:=0;
  AutoInitialize;
end;

procedure TBtnPost.HeightChange(Sender : TObject);
begin
  if Assigned(FOnHeightChange) then
  FOnHeightChange(Sender);
  if Height = 300 then
    begin
      Height:=30;
      Alist.height:=0;
    end
  else
    begin
      Height:=300;
      Alist.height:=Height-35
    end;
end;

procedure TBtnPost.H_AlistClick(Sender : TObject);
begin
  if Assigned(FOnAlistClick) then
  FOnAlistClick(Sender);
  MakeMemo(Alist.ItemIndex);
  HeightChange(Self);
end;

destructor TBtnPost.Destroy;
begin
  AutoDestroy;
  inherited Destroy;
end;

procedure TBtnPost.Loaded;
begin
  inherited Loaded;
end;

procedure TBtnPost.Paint;
begin
  inherited Paint;
end;

procedure TBtnPost.ListSort(LBox:TStrings);
var
  i,j, k, m, p1: Integer;
  slq:TStringList;
  a, b:string;
  function GetNPos(sStr: string; iNth: integer): integer;
  var
    sTempStr: string;
    iIteration: integer;
    iTempPos: integer;
    iTempResult: integer;
    sSubStr : string;
  begin
    result := 0;
    sSubStr:=',';
    if ((iNth < 1) or (sSubStr = '') or (sStr = '')) then exit;
    iIteration := 0;
    iTempResult := 0;
    sTempStr := sStr;
    while (iIteration < iNth) do
    begin
      iTempPos := Pos(sSubStr, sTempStr);
      if (iTempPos = 0) then exit;
      iTempResult := iTempResult + iTempPos;
      sTempStr := Copy(sStr, iTempResult + 1, Length(sStr) - iTempResult);
    inc(iIteration);
    end;
    result := iTempResult;
  end;
    function GetNum ( sChaine: String ): Integer ;
    var
      i: Integer ;
      s:string;
    begin
      Result := 0 ;
      for i := 1 to length( sChaine ) do
        begin
          if sChaine( i ) in ('0'..'9') then
          s:=s + sChaine( i ) ;
        end;
      Result:=StrToInt(s);
    end ;
begin
  slq:=TStringList.Create;  
  try
    slq.Sorted:=True;
    for k := LBox.Count-1 downto 0 do
      begin
        p1:=GetNPos(LBox(k),1);// GetNPos function adapted from Sam's(StackOverFlow) GetPositionofNthOccurence
        a:=LeftStr(LBox(k),1); //ESBRtns - left string up to 1st character
        b:=Copy(LBox(k),p1+1,1);
        if ((a(1) in ('A'..'Z')) or (b(1) in ('A'..'Z'))) then
          begin
            slq.Add(LBox(k));
            LBox.Delete(k);
          end;
      end;
    for i:=0 to LBox.Count-1 do
    for j:=i+1 to LBox.Count-1 do
      begin
        if GetNum(LBox(i)) > GetNum(LBox(j)) then
          begin
            LBox.Exchange(i,j);
          end;
      end;
    LBox.Text:=slq.Text+LBox.Text;
  finally
    slq.free;
  end;
end;

procedure TBtnPost.FindPcode(astr:string);
var
  sl:TStringList;
  slx:TStringList;
  x, y, z, ps, ct:Integer;
  s, t, q:string;
begin
  sl:=TStringList.Create;
  slx:=TStringList.Create;          
    try
      for x:= 0 to IndexList.Count-1 do
        begin
          if astr=LeftTillStr(IndexList(x),',') then sl.add(RightAfterChStr(IndexList(x),','));
        end;
    if sl.Count= 0 then
        begin
          ShowMessage('Postcode not found');
          Aedit.clear;
          Aedit.SetFocus;
          Exit;
        end;
    for y := 0 to sl.Count-1 do
      begin
        FileList.Clear;
        FileList.LoadFromFile(FilesPath+sl(y));
        for z := 0 to FileList.Count-1 do
          begin
            if Pos(astr,FileList(z))>0 then slx.Add(FileList(z));
          end;
      end;
    ListSort(slx);
    RawList.Clear;
    RawList.Text:=slx.Text;
    for x:= 0 to slx.Count-1 do
      begin
        s:=slx(x);
        ct:=0; q:='';
        repeat
          ps:=Pos(',',s);
          t:=LeftStr(s,ps-1);
          if ((t<>'') and (t<>' ')) then
            begin
              q:=q+t+' ';
              ct:=ct+1;
            end;
          Delete(s,1,ps);
        until ((ct=3) or (Length(s)<=1));
      alist.Items.Add(q);
    end;
    finally
      sl.Free;
      slx.Free;
    end;
end;

procedure TBtnPost.MakeMemo(Num:integer);
var
  s, w, z, Aline:string;
  sl:TStringList;
  x, acol, ps:Integer;
begin
  sl:=TStringList.Create;
  try
    s:=RawList(num);
    Aline:=s;
    sl.Text:=StringReplace(s,',',#13#10,(rfReplaceAll));
    x:=0;
    for x := sl.count - 1 downto 0 do
      begin
        if Trim(sl(x)) = '' then
        sl.Delete(x);
      end;
    x:=0;
      repeat
        if Length(sl(x))<7 then
          begin
          sl(x):=sl(x)+' '+sl(x+1);
            sl.Delete(x+1);;
            end;
          x:=x+1;
      until x=sl.Count-1;
    dset.Close;
    dset.EmptyTable;
    dset.Open;
    acol:=0;
    dset.Insert;
    dset.Edit;
    w:=Aline+',';
      repeat
          ps:=Pos(',',w);
          z:='';
          z:=LeftStr(w,ps-1);
          dset.Fields(acol).AsString:=z;
          Delete(w,1,ps);
          acol:=acol+1;
      until ((Length(w)<=1) or (acol=9));
    FAddress.Text:=sl.Text;
    SetAddress(FAddress);
    dset.Edit;
    dset.Post;
  finally
    sl.Free;
  end;
end;
end.

google sheets – How do I create a compound interest table where I can see each calculation indefinitely

I want to set up a compound interest table. I want to start with $15 and multiply by 1.0125 indefinitely. I want to be able to see the answer for each calculation (for example, I want to see what the answer is after 39 calculation, after 74 calculations, 22 calcualtions, etc..)

terminology – Compound variables? Is this the correct term?

I asked this yesterday in Cross-validated (the statistics equivalent of here) but got few views and no answers. So I thought that I would ask it here.

I am looking for a term to describe the concept of a multi-characteristic variable. Examples of this are a) vectors – have both magnitude and direction b) Olympic records – have both event (categorical) and measurement – particularly races which have set distances and record times c) cell identifiers – have both row and column d) coordinates – x, y and z, + other coordinate systems

As can be seen, this term may or may not include relationships between the specified dimensions, but the “variable” lacks meaning without all its components.

Whilst “object”, borrowed from programming, may be used, this is perhaps too general for the application. I am looking for a term that falls between “object” and “variable”, where the relationships between the various elements are easily visualised/understood.

I thought that compound variable may fit the bill. But is that used for a different concept? If so, what would be a better term?

python – Distinguish between handwritten subtraction and compound fraction

I am working in a project name “Handwritten Math Evaluation”
SO what basically happen in this is that there are 11 classes of (0 – 9) and (+,-) each containing 50 clean handwritten digits in them. Then I trained a CNN model for it with 80 % of data used in training and 20 % using in testing of model which lead in a accuracy of 98.83 %. Here is the code for the architecture of CNN model :-

import pandas as pd 
import numpy as np 
import pickle 
np.random.seed(1212) 
import keras 
from keras.models import Model 
from keras.layers import *
from keras import optimizers 
from keras.layers import Input, Dense 
from keras.models import Sequential 
from keras.layers import Dense 
from keras.layers import Dropout 
from keras.layers import Flatten 
from keras.layers.convolutional import Conv2D 
from keras.layers.convolutional import MaxPooling2D 
from keras.utils import np_utils 
from keras import backend as K  
from keras.utils.np_utils import to_categorical 
from keras.models import model_from_json
import matplotlib.pyplot as plt
model = Sequential() 
model.add(Conv2D(30, (5, 5), input_shape =(28,28,1), activation ='relu')) 
model.add(MaxPooling2D(pool_size =(2, 2))) 
model.add(Conv2D(15, (3, 3), activation ='relu')) 
model.add(MaxPooling2D(pool_size =(2, 2))) 
model.add(Dropout(0.2)) 
model.add(Flatten()) 
model.add(Dense(128, activation ='relu')) 
model.add(Dense(50, activation ='relu')) 
model.add(Dense(12, activation ='softmax')) 
# Compile model 
model.compile(loss ='categorical_crossentropy', 
            optimizer ='adam', metrics =('accuracy')) 
model.fit(X_train, y_train, epochs=1000)

Now each image in dataset is preprocesed as follows:-

import cv2
im = cv2.imread(path)
im_gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)
ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rects = (cv2.boundingRect(ctr) for ctr in ctrs)
rect = rects(0)
im_crop =im_th(rect(1):rect(1)+rect(3),rect(0):rect(0)+rect(2))
im_resize = cv2.resize(im_crop,(28,28))
im_resize = np.array(im_resize)
im_resize=im_resize.reshape(28,28)

I have made an evaluation function which solves simple expression like 7+8 :-

def evaluate(im):
    s = ''
    data = ()
    im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    ret, im_th = cv2.threshold(im_gray, 90, 255, cv2.THRESH_BINARY_INV)
    ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)(0))
    boundingBoxes = (cv2.boundingRect(c) for c in ctrs)
    look_up = ('0','1','2','3','4','5','6','7','8','9','+','-') 
    i=0
    for c in ctrs:
        rect = boundingBoxes(i)
        im_crop = im_th(rect(1):rect(1)+rect(3), rect(0):rect(0)+rect(2))
        im_resize = cv2.resize(im_crop,(28,28))
        im_resize = np.array(im_resize)
        im_resize = im_resize.reshape(28,28,1)
        data.append(im_resize)
        i+=1
    data = np.array(data)
    predictions = model.predict(data)
    i=0
    while i<len(boundingBoxes):
        rect = boundingBoxes(i)
        print(rect(2),rect(3))
        print(predictions(i))
        s += look_up(predictions(i).argmax())
        i+=1
    return s

I need help extending this thought for Compund fractions but the problem is that they are identical to subtraction sign when resized to (28 , 28) so I need help in distuingish between them.

This is my first Question so please tell if any detail is left.

algebra precalculus – Solving polynomials with compound angle formulae

Solve $64x^6-96x^4+36x^2-3=0$ (Hint: Consider expanding $cos 6theta$ in terms of $cos theta$)

To solve this exercise I can simply derive an identity using de-Moivre theorem then shuffle the equation around. It turns out that substituting $x=cos theta$ reduces the equation to $cos 6theta = frac{1}{2}$.

However, I’m wondering in the general case, is there any way to see this without the monster of a hint? In other words, given a polynomial, is there something I could look for in the coefficients that would make me think that deriving a compound angle formula may be a good idea?