Awesome Cursor Rules Collection

Showing 1573-1584 of 2626 matches

TypeScript
INSTRUÇÕES E DOCUMENTAÇÃO DO PROJETO NEXUS

1. VISÃO GERAL
Você é especialista em React Native, TypeScript, Expo e desenvolvimento de aplicativos mobile.
O projeto Nexus tem como objetivo criar um App Gamificado Comunitário. Neste app, os usuários podem, por meio de um mapa com geolocalização, reportar problemas (ex.: torneira quebrada, poluição, luz queimada, banco quebrado, etc.). O objetivo é incentivar tanto a comunidade quanto autoridades (governo, etc.) a resolverem esses problemas, começando por um estudo de caso aplicado a uma Instituição de Ensino.
1.1 Funcionalidades-Chave
1. Mapa Interativo
o Localização atual do usuário.
o Possibilidade de inserir novos marcadores de problemas.
o Visualização de um Sheet com detalhes do problema ao clicar em um marcador.
2. Gamificação
o Pontos (XP) por interações (reportar problema, resolver problema, fazer check-in diário, responder feedback, etc.), gerenciados via Supabase.
o Animação de XP na tela (XPAnimation).
o Ranking de usuários (Leaderboard).
o Recompensas e níveis (com streak diário, check-in, badges, etc.).
3. Abas (Telas)
o Mapa
o Recompensas (inclui check-in diário, feedback e informações de níveis)
o Ranking
o Perfil
4. Lógica do Lado do Servidor (Supabase)
o As funções, triggers e armazenamento de dados de XP e check-in ficam majoritariamente no Supabase (chamadas a partir do app).

2. REGRAS PRINCIPAIS E CONDUTA GERAL
As regras e diretrizes abaixo são fundamentais para manter a clareza e consistência no desenvolvimento. Siga-as rigorosamente.
5. Não se desculpe e não agradeça.
6. Fale de forma humana e direta.
7. Siga exatamente o que for solicitado; não implemente nada fora do escopo pedido.
8. Verifique as informações antes de fazer alterações ou responder algo.
9. Preserve as estruturas de código existentes e a organização do projeto.
10. Forneça respostas concisas e relevantes.
11. Siga precisamente a intenção do usuário.
12. Mantenha o projeto organizado com a estrutura de diretórios e arquivos bem definida.
13. Use nomes significativos para arquivos, diretórios, funções e variáveis.
14. Evite acúmulo de arquivos desnecessários.
15. Sempre use colors.background, colors.border, colors.tint e afins (do tema dinâmico) em vez de colors.palette para manter a compatibilidade com o modo escuro.
16. Sempre que precisar de algum arquivo, solicite-o explicitamente ao usuário (caso ele não tenha enviado).
17. A estrutura ideal de cada screen deve ser uma pasta contendo components/, config/, hooks/, index.tsx, etc.
18. Usar componentes pré-existentes para manter a coesão visual, evitando duplicação de estilos em diferentes locais.
19. O usuário que reportou um problema não pode resolver o mesmo problema.
20. Stack do projeto:
o React Native
o Expo (com build nativa)
o TypeScript
o Boilerplate Ignite
o React Native Paper (componentes)
o Ícones: @expo/vector-icons
o Sheet: @gorhom/bottom-sheet
o Mapas e localização: @rnmapbox/maps
o Navegação: React Navigation
o Autenticação, Storage: @supabase/supabase-js
o Datas: date-fns
o ESLint

3. OBJETIVOS E FUNCIONALIDADES DO MVP
Título do TCC:
UMA SOLUÇÃO TECNOLÓGICA PARA APOIAR O DESENVOLVIMENTO DE CIDADES E COMUNIDADES SUSTENTÁVEIS: UM ESTUDO DE CASO APLICADO A UMA INSTITUIÇÃO DE ENSINO
Objetivo Geral:
Investigar como um aplicativo móvel open-source gamificado pode contribuir para engajar a comunidade na identificação e resolução de problemas sociais e ambientais, promovendo construção de ambientes mais sustentáveis.
3.1 Objetivo do Projeto
- Desenvolver uma versão inicial funcional do aplicativo que:
o Permita aos usuários reportar problemas na instituição educacional.
o Promova interação colaborativa.
o Engaje os usuários com elementos básicos de gamificação.
3.2 Funcionalidades Essenciais
1. Mapa Interativo
o Exibir marcadores dos problemas já reportados.
o Botão para criar novos problemas.
o Ao clicar em marcador, visualizar detalhes (título, descrição, categoria, imagem).
2. Reportar Problemas
o Formulário para título, descrição, categoria, upload/foto obrigatórios.
o A localização é selecionada no mapa ou gerada pela geolocalização do usuário.
3. Autenticação de Usuário
o Login via email/senha (Supabase).
o Registro e recuperação de senha.
4. Perfil do Usuário
o Foto de perfil, nome e estatísticas (XP, nível, streak).
o Histórico de problemas reportados/resolvidos, comentários, upvotes.
5. Gamificação
o Sistema de pontos (XP) para cada ação.
o Sistema de níveis (ex.: XP para subir de nível).
o Check-in diário (com streak e bonus) por meio de função no Supabase.
o Prêmios, badges (próximos níveis e recompensas futuras são ocultos).
6. Leaderboard (Ranking)
o Lista dos usuários ordenados por pontuação total.
o Destaque para o usuário atual (logado).
o Possibilidade de clicar no perfil de um usuário.
7. Aba de Recompensas
o Seção de check-in diário.
o Seção de feedback (perguntas do Supabase).
o Seção exibindo níveis atingíveis e badges já conquistadas.
8. Interação Colaborativa
o Comentários em problemas.
o Upvotes em problemas.
9. Design e Usabilidade
o Interface amigável.
o Feedback visual e mensagens de confirmação.
o Consistência visual e suporte a modo escuro.

4. ESTRUTURA DE PASTAS DO PROJETO
NEXUS/
├── .expo/
├── .vscode/
├── android/
├── app/
│   ├── components/
│   │   ├── Toggle/
│   │   ├── AutoImage.tsx
│   │   ├── Button.tsx
│   │   ├── Card.tsx
│   │   ├── CommentsModel.tsx
│   │   ├── EmptyState.tsx
│   │   ├── FeedbackCard.tsx
│   │   ├── FeedbackModal.tsx
│   │   ├── FeedbackSection.tsx
│   │   ├── Header.tsx
│   │   ├── Icon.tsx
│   │   ├── index.ts
│   │   ├── levelUpModal.tsx
│   │   ├── ListItem.tsx
│   │   ├── ListView.tsx
│   │   ├── ProblemComments.tsx
│   │   ├── ProblemUpvotes.tsx
│   │   ├── Screen.tsx
│   │   ├── Text.tsx
│   │   ├── TextField.tsx
│   │   ├── XPAnimation.tsx
│   ├── config/
│   │   ├── categories.ts
│   │   ├── rewards.ts
│   │   ├── feedback.ts
│   │   ├── config.base.ts
│   │   ├── config.dev.ts
│   │   ├── config.prod.ts
│   │   └── index.ts
│   ├── contexts/
│   │   ├── LevelUpContext.tsx
│   │   └── XPContext.tsx
│   ├── devtools/
│   ├── hooks/
│   │   ├── useProblems.ts
│   │   └── useProfile.tsx
│   ├── i18n/
│   ├── models/
│   │   ├── helpers/
│   │   │   ├── getRootStore.ts
│   │   │   ├── setupRootStore.ts
│   │   │   ├── useStores.ts
│   │   │   └── withSetPropAction.ts
│   │   ├── index.ts
│   │   ├── LocationStore.tsx
│   │   └── RootStore.ts
│   ├── navigators/
│   │   ├── AppNavigator.tsx
│   │   ├── index.ts
│   │   ├── MainNavigator.tsx
│   │   └── navigationUtilities.ts
│   ├── screens/
│   │   ├── _tests_/
│   │   ├── ErrorScreen/
│   │   ├── Map/
│   │   │   ├── hooks/
│   │   │   ├── components/
│   │   │   ├── config/
│   │   │   │   ├── mapStyles.ts
│   │   │   │   └── mapDefaults.ts
│   │   │   ├── constants.ts
│   │   │   ├── index.tsx
│   │   │   └── types.ts
│   │   ├── ProfileScreen/
│   │   │   ├── BadgeItem.tsx
│   │   │   ├── FeedbackCard.tsx
│   │   │   └── index.tsx
│   │   ├── PermissionScreen.tsx
│   │   ├── ProfileScreen.tsx
│   │   ├── RewardsScreen.tsx
│   │   ├── RewardsScreen/
│   │   │   └── LevelItem.tsx
│   │   ├── ScoreboardScreen.tsx
│   │   ├── SettingsScreen.tsx
│   │   ├── SignInScreen.tsx
│   │   ├── SignUpScreen.tsx
│   │   └── WelcomeScreen.tsx
│   │   └── index.ts
│   ├── services/
│   │   ├── api/
│   │   │   ├── problems.ts
│   │   │   ├── addUserAction.ts
│   │   │   └── index.ts
│   │   ├── auth/
│   │   │   ├── supabase.ts
│   │   │   └── useAuth.tsx
│   ├── stores/
│   ├── theme/
│   ├── types/
│   ├── utils/
│   │   ├── hooks/
│   │   │   └── useSignedUrl.ts
│   │   ├── storage/
│   │   │   ├── index.ts
│   │   │   └── sessionStorage.ts
│   │   ├── crashReporting.ts
│   │   ├── delay.ts
│   │   ├── formatDate.ts
│   │   ├── gestureHandler.native.ts
│   │   ├── gestureHandler.ts
│   │   ├── ignoreWarnings.ts
│   │   ├── openLinkInBrowser.ts
│   │   ├── useAppTheme.ts
│   │   ├── useHeader.ts
│   │   ├── useIsMounted.ts
│   │   └── useSafeAreaInsetsStyle.ts
│   ├── validation/
│   └── app.tsx
├── assets/
├── ignite/
├── node_modules/
├── plugins/
│   └── withSplashScreen.ts
├── types/
├── .cursorrules
├── .env
├── .gitignore
├── app.config.ts
├── app.json
├── babel.config.js
├── bun.lockb
├── eas.json
├── env.example
├── eslint.config.mjs
├── metro.config.js
├── package.json
└── tsconfig.json

5. DOCUMENTAÇÃO DE ESTRUTURAS, FUNÇÕES E SUPABASE
A seguir, temos a documentação mesclada sobre as tabelas, funções e triggers do Supabase. É fundamental para manter o backend alinhado com o aplicativo.
Observação: Todo código SQL está em TypeScript + @supabase/supabase-js ou em forma de scripts que devem rodar no Supabase.
5.1 Extensões Necessárias
create extension if not exists "uuid-ossp";
create extension if not exists postgis;
- uuid-ossp: Para geração de UUIDs.
- postgis: Para manipulação de dados geoespaciais.

5.2 Enum action_type
create type action_type as enum (
  'report_problem',
  'solve_problem',
  'daily_check_in',
  'feedback_response'
);
Enum que representa as ações do usuário que geram XP.

5.3 Tabela level_config
create table level_config (
  level integer primary key,
  xp_required integer not null,
  title text not null,
  description text,
  created_at timestamptz default now(),
  constraint valid_xp check (xp_required >= 0),
  constraint level_order check (level > 0)
);
- Define a configuração de níveis do usuário (XP necessária, título, descrição, etc.).
Inserindo dados iniciais na level_config
insert into level_config (level, xp_required, title, description) values
  (1, 0, 'Iniciante', 'Começando sua jornada'),
  (2, 100, 'Observador', 'Seus olhos estão atentos'),
  (3, 300, 'Cidadão Ativo', 'Participando ativamente'),
  (4, 600, 'Guardião da Cidade', 'Protegendo nossa comunidade'),
  (5, 1000, 'Líder Comunitário', 'Inspirando outros a ajudar'),
  (6, 1500, 'Agente de Mudança', 'Transformando a comunidade'),
  (7, 2100, 'Herói Local', 'Fazendo a diferença'),
  (8, 2800, 'Lenda da Cidade', 'Sua dedicação é inspiradora'),
  (9, 3600, 'Mestre Guardião', 'Um exemplo a ser seguido'),
  (10, 4500, 'Guardião Supremo', 'O mais alto nível de dedicação');

5.4 Tabela user_profiles
create table if not exists public.user_profiles (
  id uuid references auth.users on delete cascade primary key,
  username text not null unique,
  avatar_url text,
  current_xp integer default 0,
  current_level integer default 1,
  current_streak integer default 0,
  max_streak integer default 0,
  last_check_in timestamptz,
  problems_reported integer default 0,
  problems_solved integer default 0,
  created_at timestamptz default now(),
  updated_at timestamptz default now(),
  constraint valid_xp check (current_xp >= 0),
  constraint valid_level check (current_level > 0),
  constraint username_length check (char_length(username) >= 3)
);
- Mantém as informações de perfil (XP, nível, streak, etc.).
- Após a criação, adiciona-se chave estrangeira para level_config:
alter table public.user_profiles
add constraint fk_level foreign key (current_level) references level_config(level);
Função e Trigger para novos usuários
Função handle_new_user()
create or replace function handle_new_user()
returns trigger as $$
declare
  username_base text;
  final_username text;
  suffix integer := 1;
begin
  username_base := split_part(new.email, '@', 1);
  final_username := username_base;

  if length(final_username) < 3 then
    final_username := final_username || '_user';
  end if;

  while exists(select 1 from public.user_profiles where username = final_username) loop
    final_username := username_base || suffix;
    suffix := suffix + 1;
    if length(final_username) < 3 then
       final_username := username_base || '_user' || suffix;
    end if;
  end loop;

  insert into public.user_profiles (id, username)
  values (
    new.id,
    final_username
  );
  return new;
end;
$$ language plpgsql security definer;
Trigger on_auth_user_created
create trigger on_auth_user_created
  after insert on auth.users
  for each row execute function handle_new_user();

5.5 Tabela reported_problems
create table reported_problems (
  id uuid primary key default uuid_generate_v4(),
  title text not null,
  description text not null,
  category text not null,
  location geometry(Point, 4326) not null,
  image_url text,
  status text default 'active',
  reporter_id uuid not null references auth.users(id),
  solver_id uuid references auth.users(id),
  reported_at timestamptz default now(),
  solved_at timestamptz,
  updated_at timestamptz default now(),
  constraint different_solver check (solver_id is null or solver_id != reporter_id),
  constraint valid_status check (status in ('active', 'solved', 'invalid')),
  constraint valid_solved check (
    (status = 'solved' and solver_id is not null and solved_at is not null) or
    (status != 'solved' and solver_id is null and solved_at is null)
  )
);

5.6 Tabela action_rewards
create table action_rewards (
  action action_type primary key,
  xp_reward integer not null check (xp_reward >= 0),
  description text not null
);
Inserindo dados iniciais na action_rewards
insert into action_rewards (action, xp_reward, description) values
  ('report_problem', 50, 'Reportar um problema'),
  ('solve_problem', 100, 'Resolver um problema'),
  ('daily_check_in', 10, 'Check-in diário'),
  ('feedback_response', 25, 'Responder pesquisa de feedback');

5.7 Tabela user_actions
create table user_actions (
  id uuid primary key default uuid_generate_v4(),
  user_id uuid not null references auth.users(id),
  action action_type not null,
  xp_earned integer not null check (xp_earned >= 0),
  reference_id uuid references reported_problems(id),
  created_at timestamptz default now()
);

5.8 Tabela feedback_questions
create table feedback_questions (
  id uuid primary key default uuid_generate_v4(),
  question text not null,
  type text not null default 'likert',
  active boolean default true,
  created_at timestamptz default now()
);
Inserindo dados iniciais na feedback_questions
insert into feedback_questions (question) values
  ('Os emblemas me motivam a participar mais'),
  ('O sistema de níveis influencia minha participação'),
  ('As recompensas me incentivam a usar o app diariamente'),
  ('A gamificação torna o app mais interessante'),
  ('Me sinto mais engajado com os elementos de gamificação');

5.9 Tabela feedback_responses
create table feedback_responses (
  id uuid primary key default uuid_generate_v4(),
  user_id uuid not null references auth.users(id),
  question_id uuid not null references feedback_questions(id),
  rating integer not null check (rating between 1 and 5),
  created_at timestamptz default now(),
  constraint one_response_per_question unique (user_id, question_id)
);

5.10 Tabela problem_upvotes
create table problem_upvotes (
  id uuid primary key default uuid_generate_v4(),
  problem_id uuid references reported_problems(id) on delete cascade,
  user_id uuid references auth.users(id) on delete cascade,
  created_at timestamptz default now(),
  constraint unique_upvote unique (problem_id, user_id)
);
- Cada usuário pode dar apenas 1 upvote por problema.

5.11 Tabela problem_comments
create table problem_comments (
  id uuid primary key default uuid_generate_v4(),
  problem_id uuid references reported_problems(id) on delete cascade,
  user_id uuid references auth.users(id) on delete cascade,
  comment text not null check (char_length(comment) >= 1),
  created_at timestamptz default now(),
  updated_at timestamptz default now()
);

5.12 Funções Importantes
validate_action_points()
create or replace function validate_action_points()
returns trigger as $$
begin
  if NEW.xp_earned != (
    select xp_reward
    from action_rewards
    where action = NEW.action
  ) then
    raise exception 'Pontos inválidos para a ação';
  end if;
  return NEW;
end;
$$ language plpgsql;
- Garante que xp_earned em user_actions seja o exato valor definido em action_rewards.

update_user_level()
create or replace function update_user_level()
returns trigger as $$
begin
  NEW.current_level := (
    select level
    from level_config
    where xp_required <= NEW.current_xp
    order by level desc
    limit 1
  );
  return NEW;
end;
$$ language plpgsql;
- Atualiza o nível do usuário com base no XP total.

update_updated_at()
create or replace function update_updated_at()
returns trigger as $$
begin
  NEW.updated_at = now();
  return NEW;
end;
$$ language plpgsql;
- Atualiza updated_at sempre que a linha é modificada.

get_profile_with_next_level(user_id uuid)
create or replace function get_profile_with_next_level(user_id uuid)
returns json as $$
declare
  user_profile public.user_profiles;
  next_level level_config;
begin
  select * into user_profile
  from public.user_profiles
  where id = user_id;

  select * into next_level
  from level_config
  where level > user_profile.current_level
  order by level asc
  limit 1;

  return json_build_object(
    'profile', user_profile,
    'next_level', next_level
  );
end;
$$ language plpgsql security definer;
- Retorna o perfil completo + próximo nível em formato JSON.

add_user_action(p_user_id uuid, p_action action_type, p_reference_id uuid default null)
create or replace function add_user_action(
  p_user_id uuid,
  p_action action_type,
  p_reference_id uuid default null
)
returns void as $$
declare
  v_reward integer;
begin
  select xp_reward into v_reward
  from action_rewards
  where action = p_action;

  insert into user_actions (user_id, action, xp_earned, reference_id)
  values (p_user_id, p_action, v_reward, p_reference_id);

  update public.user_profiles
  set current_xp = current_xp + v_reward,
      problems_reported = case when p_action = 'report_problem' then problems_reported + 1 else problems_reported end,
      problems_solved = case when p_action = 'solve_problem' then problems_solved + 1 else problems_solved end
  where id = p_user_id;
end;
$$ language plpgsql security definer;
- Registra a ação do usuário em user_actions, atualiza XP e contadores (problemas reportados/solucionados).

perform_daily_check_in(p_user_id uuid)
create or replace function perform_daily_check_in(
  p_user_id uuid
)
returns void as $$
declare
  v_last_check_in timestamptz;
  v_current_streak integer;
  v_max_streak integer;
  v_hours_since_last_check_in numeric;
begin
  select
    last_check_in,
    current_streak,
    max_streak
  into
    v_last_check_in,
    v_current_streak,
    v_max_streak
  from public.user_profiles
  where id = p_user_id
  for update;

  if v_last_check_in is not null then
    v_hours_since_last_check_in := extract(epoch from (now() AT TIME ZONE 'utc' - v_last_check_in AT TIME ZONE 'utc')) / 3600;
    if v_hours_since_last_check_in < 24 then
      raise exception 'Você precisa esperar 24 horas entre check-ins.';
    end if;
    v_current_streak := case
      when v_hours_since_last_check_in <= 48 then v_current_streak + 1
      else 1
    end;
  else
    v_current_streak := 1;
  end if;

  v_max_streak := greatest(coalesce(v_max_streak, 0), v_current_streak);

  update public.user_profiles
  set
    last_check_in = now(),
    current_streak = v_current_streak,
    max_streak = v_max_streak
  where id = p_user_id;

  perform add_user_action(p_user_id, 'daily_check_in');
end;
$$ language plpgsql security definer;
- Faz check-in diário (limite de 24h entre check-ins).
- Gera XP automaticamente chamando add_user_action.

get_problem_upvotes(problem_id uuid)
create or replace function get_problem_upvotes(problem_id uuid)
returns integer as $$
  select count(*)::integer
  from problem_upvotes
  where problem_upvotes.problem_id = $1;
$$ language sql security definer;
- Retorna a quantidade de upvotes em determinado problema.

has_user_upvoted(problem_id uuid, user_id uuid)
create or replace function has_user_upvoted(problem_id uuid, user_id uuid)
returns boolean as $$
  select exists(
    select 1
    from problem_upvotes
    where problem_upvotes.problem_id = $1
    and problem_upvotes.user_id = $2
  );
$$ language sql security definer;
- Retorna true se o usuário já upvotou o problema, caso contrário false.

5.13 Triggers
create trigger validate_action_points_trigger
  before insert on user_actions
  for each row
  execute function validate_action_points();

create trigger on_profile_xp_change
  before update of current_xp on public.user_profiles
  for each row execute function update_user_level();

create trigger update_reported_problems_timestamp
  before update on reported_problems
  for each row execute function update_updated_at();

create trigger update_user_profiles_timestamp
  before update on public.user_profiles
  for each row execute function update_updated_at();

create trigger update_problem_comments_timestamp
  before update on problem_comments
  for each row
  execute function update_updated_at();
- validate_action_points_trigger: chama validate_action_points antes de inserir em user_actions.
- on_profile_xp_change: chama update_user_level antes de atualizar current_xp.
- update_*_timestamp: chama update_updated_at antes de atualizar as respectivas tabelas.

5.14 Índices
create index problem_upvotes_problem_idx on problem_upvotes(problem_id);
create index problem_upvotes_user_idx on problem_upvotes(user_id);
create index problem_comments_problem_idx on problem_comments(problem_id);
create index problem_comments_user_idx on problem_comments(user_id);
create index problem_comments_created_idx on problem_comments(created_at desc);
- Otimizam consultas relacionadas a upvotes e comentários.

5.15 Views
problem_comments_with_profiles
create or replace view problem_comments_with_profiles as
select
  pc.*,
  up.username,
  up.avatar_url
from problem_comments pc
join public.user_profiles up on pc.user_id = up.id;
- Facilita a recuperação de comentários com dados básicos do autor (username, avatar).

5.16 Políticas de Segurança (RLS)
user_profiles
alter table public.user_profiles enable row level security;

create policy "Perfis visíveis para usuários autenticados"
  on public.user_profiles for select
  to authenticated
  using (true);

create policy "Usuários editam próprio perfil"
  on public.user_profiles for update
  to authenticated
  using (id = auth.uid());
reported_problems
alter table reported_problems enable row level security;

create policy "Problemas visíveis para usuários autenticados"
  on reported_problems for select
  to authenticated
  using (true);

create policy "Usuários podem reportar problemas"
  on reported_problems for insert
  to authenticated
  with check (reporter_id = auth.uid());

create policy "Usuários podem resolver problemas (incluindo os próprios)"
  on reported_problems for update
  to authenticated
  using (status = 'active')
  with check (
    solver_id = auth.uid() and
    status = 'solved'
  );

create policy "Criadores podem deletar problemas não resolvidos"
  on reported_problems for delete
  to authenticated
  using (
    reporter_id = auth.uid() and
    status = 'active'
  );
feedback_questions
alter table feedback_questions enable row level security;

create policy "Perguntas visíveis para todos"
  on feedback_questions for select
  to authenticated
  using (active = true);
feedback_responses
alter table feedback_responses enable row level security;

create policy "Usuários podem enviar respostas"
  on feedback_responses for insert
  to authenticated
  with check (user_id = auth.uid());

create policy "Usuários veem suas respostas"
  on feedback_responses for select
  to authenticated
  using (user_id = auth.uid());
problem_upvotes
alter table problem_upvotes enable row level security;

create policy "Usuários podem ver upvotes"
  on problem_upvotes for select
  to authenticated
  using (true);

create policy "Usuários podem dar upvote"
  on problem_upvotes for insert
  to authenticated
  with check (auth.uid() = user_id);

create policy "Usuários podem remover próprio upvote"
  on problem_upvotes for delete
  to authenticated
  using (auth.uid() = user_id);
problem_comments
alter table problem_comments enable row level security;

create policy "Usuários podem ver comentários"
  on problem_comments for select
  to authenticated
  using (true);

create policy "Usuários podem comentar"
  on problem_comments for insert
  to authenticated
  with check (auth.uid() = user_id);

create policy "Usuários podem editar próprios comentários"
  on problem_comments for update
  to authenticated
  using (auth.uid() = user_id);

create policy "Usuários podem deletar próprios comentários"
  on problem_comments for delete
  to authenticated
  using (auth.uid() = user_id);

5.17 Storage para Imagens de Problemas
insert into storage.buckets (id, name, public)
values ('problem-images', 'problem-images', false)
on conflict (id) do nothing;

create policy "Upload em pasta própria"
  on storage.objects for insert
  to authenticated
  with check (
    bucket_id = 'problem-images' and
    auth.uid()::text = (storage.foldername(name))[1]
  );

create policy "Visualização de imagens"
  on storage.objects for select
  to authenticated
  using (bucket_id = 'problem-images');
- Cria o bucket problem-images.
- Políticas que permitem somente upload em pasta própria.
- Visualização de imagens para usuários autenticados.

5.18 Uso com @supabase/supabase-js (Exemplos em TypeScript)
A seguir, exemplos de chamadas de funções:
Exemplo 1: get_profile_with_next_level
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

async function getUserProfileWithNextLevel(userId: string) {
  const { data, error } = await supabase.rpc('get_profile_with_next_level', {
    user_id: userId,
  });
  if (error) throw error;
  return data;
}
Exemplo 2: Registrar ação com add_user_action
async function reportProblem(userId: string, referenceId: string) {
  const { data, error } = await supabase.rpc('add_user_action', {
    p_user_id: userId,
    p_action: 'report_problem',
    p_reference_id: referenceId, // opcional
  });
  if (error) throw error;
  return data;
}
Exemplo 3: Check-in diário (perform_daily_check_in)
async function dailyCheckIn(userId: string) {
  const { data, error } = await supabase.rpc('perform_daily_check_in', {
    p_user_id: userId,
  });
  if (error) {
    if (error.message.includes('Você precisa esperar 24 horas')) {
      console.warn('Check-in diário ainda não está disponível.');
    }
    throw error;
  }
  return data;
}
Exemplo 4: Verificar upvotes (has_user_upvoted)
async function checkIfUserUpvoted(problemId: string, userId: string) {
  const { data, error } = await supabase.rpc('has_user_upvoted', {
    problem_id: problemId,
    user_id: userId,
  });
  if (error) throw error;
  return data; // true ou false
}
Exemplo 5: Contar upvotes (get_problem_upvotes)
async function countUpvotes(problemId: string) {
  const { data, error } = await supabase.rpc('get_problem_upvotes', {
    problem_id: problemId,
  });
  if (error) throw error;
  return data; // número de upvotes
}

6. CONSIDERAÇÕES FINAIS
- Segurança: Funções com security definer são executadas com privilégios do proprietário da função.
- RLS (Row-Level Security): As políticas definidas garantem acesso somente aos dados do próprio usuário ou dados públicos.
- Triggers: Centralizam a lógica de atualização de XP, níveis e timestamps, mantendo o código do app mais limpo.
- Validações: Restrições de integridade garantem que as ações e dados inseridos estejam coerentes com as regras de negócio (por exemplo, XP de cada ação).
Este documento serve como guia de referência para entender como funciona o esquema do banco de dados e as funções armazenadas no Supabase, garantindo a coerência com o App Nexus escrito em React Native + TypeScript.
bun
ejs
eslint
golang
javascript
nestjs
react
rest-api
+3 more

First seen in:

gabrielws/nexus

Used in 1 repository

C#
# 您是一位专注于可扩展网页开发的Angular、SASS和TypeScript专家。

## 核心原则

- 提供清晰、准确的Angular和TypeScript示例。
- 在适用的情况下使用不可变性和纯函数。
- 优先使用组件组合来增强模块化。
- 使用有意义的变量命名(例如isActive、hasPermission)。
- 使用kebab-case命名文件(例如user-profile.component.ts)。
- 对组件、服务和实用程序优先使用具名导出。
- 对UI用material design进行设计
- UI的设计应该符合现代审美

## TypeScript和Angular

- 用接口定义数据结构以确保类型安全。
- 避免使用any类型,充分利用类型系统。
- 代码应在网页端和移动端都能交互响应
- 组织文件:按导入、定义和实现的顺序排列内容。
- 使用模板字符串处理多行文本。
- 利用可选链操作符和空值合并操作符。
- 在适用情况下使用独立组件。
- 利用Angular的信号系统提高状态管理和响应式编程效率。
- 在组件、指令或服务逻辑中使用inject函数直接注入服务,以增强代码清晰度并减少样板代码。

## 文件命名约定

- 组件:*.component.ts
- 服务:*.service.ts
- 模块:*.module.ts
- 指令:*.directive.ts
- 管道:*.pipe.ts
- 测试:*.spec.ts
- 所有文件均使用kebab-case命名。

## 代码风格

- 使用单引号表示字符串字面量。
- 使用2个空格进行缩进。
- 保持代码整洁,无尾随空格。
- 使用const声明不可变变量。
- 使用模板字符串进行字符串插值。

## Angular特定指南

- 在模板中处理Observable时使用async管道。
- 对特性模块实现延迟加载。
- 确保语义化HTML和ARIA标签的可访问性。
- 使用延迟视图优化组件渲染,仅在需要时加载非关键视图。
- 使用Angular的信号系统提升响应式编程和状态管理效率。
- 使用NgOptimizedImage指令提高图片加载效率,改善性能并防止链接断开。

## 导入顺序

- Angular核心和常用模块
- RxJS模块
- 其他Angular模块
- 应用核心导入
- 共享模块导入
- 特定环境导入
- 相对路径导入

## 错误处理与验证

- 在服务和组件中使用正确的错误处理。
- 使用自定义错误类型或工厂。
- 实现Angular表单验证或自定义验证器。

## 关键约定

- 使用Angular的依赖注入系统和inject函数进行服务注入。
- 注重重用性和模块化。
- 遵循Angular的风格指南。
- 按照Angular的最佳实践进行优化。
- 关注Web Vitals的优化,如LCP、INP和CLS。

## 参考 请参考Angular官方文档获取组件、服务和模块的最佳实践。
angular
c#
css
dockerfile
golang
html
sass
shell
+1 more
Hendryshi/BilliardClubParisien

Used in 1 repository

HTML
# Jekyll/Sass Front-end Development Expert

You are a Senior Front-end Developer and Expert in Jekyll, Sass, HTML, CSS, and modern UI/UX practices. You are methodical, provide detailed answers, and have excellent reasoning skills. You provide accurate, factual, and well-thought-out answers.

### Core Principles
- Follow user requirements carefully and precisely
- Plan step by step - describe your plan in detailed pseudocode
- Confirm and then write code
- Write code following best practices, DRY principle, bug-free and fully functional
- Prioritize readable and maintainable code
- Implement all requested functionality
- Leave no TODOs or incomplete parts
- Ensure code is complete and thoroughly verified
- Include all necessary imports and use proper naming
- Be concise and minimize unnecessary text
- If there's doubt about the correct answer, mention it
- If you don't know the answer, admit it instead of guessing

### Development Environment
Work with the following technologies:
- Jekyll
- Sass/SCSS
- Liquid Template
- HTML
- CSS
- JavaScript (when necessary)
- Markdown

### Implementation Guidelines
Follow these rules when writing code:

#### Jekyll
- Use collections whenever possible for structured content
- Organize content in _includes and _layouts modularly
- Use front matter consistently for metadata
- Implement data files (_data) for reusable content

#### Sass
- Use 7-1 architecture for file organization
- Implement mixins for reusable code
- Use variables for consistent values (colors, typography, etc)
- Apply nesting moderately (maximum 3 levels)
- Follow BEM naming convention for CSS classes

#### HTML
- Maintain proper semantics
- Implement accessibility attributes
- Use Jekyll includes for reusable components
- Keep consistent indentation

#### Performance
- Minify assets when possible
- Optimize images
- Use lazy loading for images
- Implement cache-busting
- Reduce HTTP requests

#### Recommended File Structure
```
.
├── _data/
├── _includes/
├── _layouts/
├── _posts/
├── _sass/
│   ├── abstracts/
│   ├── base/
│   ├── components/
│   ├── layout/
│   ├── pages/
│   ├── themes/
│   └── vendors/
├── assets/
│   ├── css/
│   ├── js/
│   └── images/
└── _config.yml
```
css
html
java
javascript
nestjs
ruby
sass
scss

First seen in:

gabrielcano-git/wind

Used in 1 repository

Shell
{
  "rules": {
    "context_initialization": {
      "description": "プロジェクトコンテキストの初期化",
      "steps": [
        "以下のファイルを順番に読み込み、プロジェクトの文脈を理解する:",
        "1. .notes/README.md - ドキュメント構成の説明",
        "2. .notes/00_project/overview.md - プロジェクトの目的と要件",
        "3. .notes/00_project/structure.md - プロジェクト構造定義",
        "4. .notes/10_tasks/list.md - タスク一覧と進捗",
        "5. .notes/20_meetings/notes.md - ミーティング記録",
        "6. .notes/10_tasks/templates/order.md - タスク指示書テンプレート"
      ],
      "file_roles": {
        ".notes/README.md": "ドキュメント体系の全体像と使用方法",
        ".notes/00_project/overview.md": "プロジェクトの目的、スコープ、要件の定義",
        ".notes/00_project/structure.md": "プロジェクトの物理的構造と各要素の説明",
        ".notes/10_tasks/list.md": "タスクの管理と進捗状況の追跡",
        ".notes/20_meetings/notes.md": "ミーティングでの決定事項と進捗報告",
        ".notes/10_tasks/templates/order.md": "個別タスクの実行指示書の標準フォーマット"
      }
    },
    "documentation_driven": {
      "description": "ドキュメント駆動開発の原則",
      "enabled": true,
      "workflow": [
        {
          "phase": "計画",
          "steps": [
            ".notes/00_project/overview.md でプロジェクトの目的と要件を確認",
            ".notes/10_tasks/list.md で関連するタスクの依存関係を確認",
            ".notes/00_project/structure.md でコードの配置場所を確認"
          ]
        },
        {
          "phase": "実装",
          "steps": [
            ".notes/10_tasks/templates/order.md に基づいてタスクを文書化",
            ".notes/20_meetings/notes.md の決定事項を参照",
            ".notes/10_tasks/list.md に実装中の変更を記録"
          ]
        },
        {
          "phase": "レビュー",
          "steps": [
            ".notes/00_project/overview.md の要件との整合性確認",
            ".notes/00_project/structure.md の規約との整合性確認",
            ".notes/20_meetings/notes.md に変更内容を記録"
          ]
        }
      ]
    },
    "project_tracking": {
      "description": "プロジェクト追跡と目標の整合性",
      "enabled": true,
      "rules": [
        {
          "description": "ドキュメント更新の優先順位:",
          "files": [
            {
              "path": ".notes/10_tasks/list.md",
              "timing": "タスクステータスの変更時",
              "priority": "high"
            },
            {
              "path": ".notes/20_meetings/notes.md",
              "timing": "決定事項発生時",
              "priority": "high"
            },
            {
              "path": ".notes/00_project/overview.md",
              "timing": "要件や仕様の変更時",
              "priority": "medium"
            },
            {
              "path": ".notes/00_project/structure.md",
              "timing": "構造変更時",
              "priority": "medium"
            }
          ]
        }
      ]
    },
    "operational_protocol": {
      "description": "タスクへのアプローチ方法",
      "before_action": [
        ".notes/00_project/structure.md でのディレクトリ構造の確認",
        ".notes/00_project/overview.md の要件確認",
        "既存の類似ファイルの有無の確認",
        ".notes/10_tasks/list.md でのタスク分析",
        ".notes/10_tasks/templates/order.md に基づくタスク文書化"
      ],
      "during_action": [
        ".notes/10_tasks/list.md の進捗更新",
        ".notes/20_meetings/notes.md への記録",
        "コードレビューコメントの記録"
      ],
      "after_action": [
        "ドキュメントの更新確認",
        "変更の影響範囲の文書化",
        ".notes/00_project/structure.md の更新"
      ]
    },
    "safety_requirements": [
      "ドキュメントと実装の一貫性を維持",
      "変更履歴の明確な記録",
      "セキュリティ考慮事項の遵守",
      "既存ファイルの編集前の確認事項",
      {
        "description": "ファイル編集の安全性確保",
        "steps": [
          "1. 編集対象のディレクトリ構造の確認",
          "2. 既存の類似ファイルの検索",
          "3. 編集すべき既存ファイルの特定",
          "4. 新規ファイル作成の必要性の検証"
        ],
        "validation": [
          "ディレクトリ構造が .notes/00_project/structure.md と一致していることを確認",
          "類似の機能や目的を持つファイルが存在しないことを確認",
          "新規ファイル作成が本当に必要か、既存ファイルの修正で対応可能でないかを確認"
        ],
        "warnings": [
          "安易な新規ファイル作成は重複や整合性の問題を引き起こす可能性がある",
          "既存ファイルの修正を優先し、新規作成は最後の手段とする"
        ]
      }
    ],
    "priorities": [
      {
        "source": ".notes/",
        "weight": 1.0,
        "description": "ドキュメントの整合性を最優先"
      }
    ],
    "modes": {
      "base": {
        "description": "定例タスク用"
      },
      "enhanced": {
        "description": "複雑な問題に対応するため"
      }
    },
    "project_directives": {
      "name": "[project_name]",
      "ai_first": true,
      "prompt_templates": {
        "setup": {
          "description": "プロジェクトの初期設定",
          "template": "@project setup\n目的: [目的]\n\n手順:\n1. プロジェクト概要の定義\n2. 開発環境の構築\n3. 初期タスクの作成"
        },
        "task": {
          "description": "タスクの作成",
          "template": "@task create\nタスク: [タスク名]\n説明: [説明]\n優先度: [high/medium/low]\n担当者: [@username]"
        },
        "code": {
          "description": "コードの生成",
          "template": "@code generate\n機能: [機能名]\n入力:\n  - [入力1]\n  - [入力2]\n出力: [期待される出力]\n制約:\n  - [制約1]\n  - [制約2]"
        },
        "test": {
          "description": "テストの生成",
          "template": "@test generate\n対象: [機能名]\nシナリオ:\n  - [ケース1]\n  - [ケース2]\n期待結果:\n  - [結果1]\n  - [結果2]"
        },
        "review": {
          "description": "コードレビュー",
          "template": "@code review\n対象: [ファイル]\n観点:\n  - コードの品質\n  - パフォーマンス\n  - セキュリティ\n  - テストカバレッジ"
        }
      }
    }
  }
}
shell

First seen in:

ctake3/cursorrules

Used in 1 repository

C
Considerations
• The IP and port to which the client must connect and the server must
listen are passed as a parameter.
• It can be assumed that the format of the input parameters will always
be correct. However, must check if the number of parameters is correct.
• The port assigned to the client and server is the one assigned to the
group.
• The client is guaranteed to always enter an input followed by a return
(\n).
• The server manages who is the winner, clients must only save and
display the board distribution.
• The communication between client and server must be carried out
following the guidelines of the frames indicated in the statement.
• The output of the program must be similar to that of the statement (see
execution examples).
• The use of “system” or “popen” or analogous functions of the same
family is not allowed.
• The use of global variables must be reduced to the minimum possible to
make the program work correctly.
• All input and output must be done with file descriptors, the use of printf,
scanf, FILE*, getchar, or similar is not allowed.
• It must be compiled using the –Wall, –Wextra and -lpthread flags.
• Any practice that contains warnings will be directly discarded.
• All resources must be released.
• A single “S5.c” file must be delivered that will have the names and logins
of the group members commented. Otherwise, the practice will not be
corrected.
• You may use the client you made last session. However, the correction
will be made with the one provided / last session solution.

Guardian of Enigmas
In the vast ocean of data in the digital world, a legendary treasure known as "The
Code Chest" has been hidden on a mysterious island protected by the server
Guardian of Enigmas. This server challenges all navigators (clients) who seek to
uncover the encoded secrets within the chest. Each challenge they overcome
brings them closer to the treasure, revealing coordinates piece by piece.
Your goal is to build a server in C that functions as the guardian of the chest,
challenging clients with cultural, logical, and mathematical riddles. The server
must handle multiple connections simultaneously, provide challenges, validate
responses, offer hints, and track the progress of each clientseparately. This server
must be able to:
- Initiate and Manage Connections: Listen on the port and accept multiple
incoming connections.
- Load Challenges: Read a set of challenges from a text file (challenges.txt)
upon startup and keep them in memory for users to check.
- Dynamic Interaction: Respond to challenge requests, receive responses,
provide hints, and display progress.
Keep in mind the client you already implemented the client, so you understand
the type of requests you’ll be receiving. These were:
1. Receive Current Challenge: The server will receive a “1\n” and the it must send
the corresponding challenge to the client extracted from the file.
2. Send Response to Challenge: The server will receive a “2\n” followed by
“<answer>\n”. The server must verify the response to the corresponding
challenge extracted from the file.
3. Request Hint: The server will receive a “3\n” and must send a hint for the
challenge corresponding to the client extracted from the file.
4. View Current Mission Status: The server will receive a “4\n” and must then
inform how many challenges remain, and if all are completed, provide the
coordinates of the chest. (This includes tracking each client: which challenge they
are on and how many they have left to finish).
5. Terminate Connection and Exit: The server will rec

Structure of the "challenges.txt" file:
Question1|Answer1&Hint\n
Question2|Answer2&Hint\n
Question3|Answer3&Hint\n
c
golang
KorszunKarol/operating_systems

Used in 1 repository

JavaScript
/**
 * Does It ARM Project Rules
 * Customized AI behavior for maintaining app compatibility database
 */
module.exports = {
    // Core project settings
    project: {
        name: 'doesitarm',
        type: 'astro',
        packageManager: 'pnpm',
        nodeVersion: '>=22'
    },

    // Code style preferences
    style: {
        indentSize: 4,
        maxLineLength: 72,
        quotes: 'single',
        semicolons: false
    },

    // Testing configuration 
    testing: {
        framework: 'vitest',
        pattern: 'test/**/*.test.js',
        coverage: true
    },

    // Documentation rules
    docs: {
        // Write comments as user stories instead of implementation details
        commentStyle: 'userStory',
        jsdoc: {
            required: true,
            params: true,
            returns: true
        }
    },

    // Function patterns
    functions: {
        // Prefer options object for 2+ params
        preferOptionsObject: true,
        
        // Always use named exports except for pages
        exports: 'named',
        
        // Functional components only
        reactComponents: 'functional'
    },

    // Variable naming
    naming: {
        // Avoid generic names
        forbidden: [
            'base64',
            'text',
            'data',
            'item',
            'content'
        ],
        
        // Prefer descriptive names
        preferred: {
            'base64': '*Base64',
            'text': '*Text',
            'data': '*Data',
            'content': '*Content'
        }
    },

    // Search functionality rules
    search: {
        // Stork search configuration
        stork: {
            version: '1.6.0',
            indexPath: 'static/search-index.st',
            tomlPath: 'static/stork.toml'
        }
    },

    // Build process
    build: {
        // Files to ignore
        ignore: [
            'node_modules',
            'dist',
            '.cache',
            '.DS_Store'
        ],
        
        // Required environment variables
        requiredEnv: [
            'PUBLIC_URL',
            'PUBLIC_API_DOMAIN',
            'COMMITS_SOURCE',
            'GAMES_SOURCE'
        ]
    },

    // Deployment configurations
    deployment: {
        platforms: ['netlify', 'vercel'],
        netlify: {
            buildCommand: 'pnpm run netlify-build',
            publishDir: 'dist/',
            functions: {
                directory: 'dist/functions',
                bundler: 'esbuild'
            },
            environment: {
                NPM_FLAGS: '--no-optional',
                CI: '1'
            }
        },
        vercel: {
            buildCommand: 'pnpm run vercel-build',
            distDir: 'static',
            buildSteps: [
                'test-prebuild',
                'build-lists-and-api', 
                'test-postbuild-api'
            ],
            github: {
                silent: true
            }
        }
    }
} 
astro
bun
css
esbuild
html
javascript
netlify
npm
+8 more

First seen in:

ThatGuySam/doesitarm

Used in 1 repository

JavaScript
# Cursor Rules for Chrome Extension Development

You are an expert in Chrome extension development, JavaScript, HTML, CSS, and Chrome APIs.

**Code Style and Structure**
- Write concise, technical JavaScript code (ES6+) with accurate examples.
- Use functional programming patterns; avoid classes unless necessary.
- Prefer modular architecture to enhance maintainability and reusability.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure extension files: manifest.json, background scripts, content scripts, popup HTML/JS/CSS, options page (if needed).

**Naming Conventions**
- Use camelCase for variable and function names (e.g., `getUserData`, `isExtensionActive`).
- Use PascalCase for constructor functions and classes.
- Use uppercase with underscores for constants (e.g., `MAX_RETRY_ATTEMPTS`).

**JavaScript Usage**
- Use modern JavaScript (ES6+) features, ensuring compatibility with the minimum supported Chrome version.
- Implement proper error handling and input validation.
- Use async/await for asynchronous operations when possible.

**Chrome Extension Manifest**
- Use the latest manifest version (v3) unless there's a specific need for v2.
- Properly declare permissions, host permissions, and content security policy.
- Use declarative net request instead of the webRequest API where possible.

**Extension Architecture**
- Separate concerns between background scripts, content scripts, and popup scripts.
- Use message passing for communication between different parts of the extension.
- Implement proper state management using Chrome's storage API.

**User Interface and Styling**
- Create intuitive and responsive UI for popup and options pages.
- Use CSS frameworks sparingly to keep the extension lightweight.
- Implement dark mode support for better user experience.

**Performance Optimization**
- Minimize resource usage in background scripts.
- Use event pages instead of persistent background pages when possible.
- Optimize content scripts to minimize impact on web page performance.

**Security Practices**
- Implement content security policies to prevent XSS attacks.
- Use Chrome's identity API for secure authentication.
- Sanitize and validate all user inputs.

**API Usage**
- Utilize Chrome extension APIs effectively (e.g., chrome.tabs, chrome.storage, chrome.runtime).
- Implement proper error handling for Chrome API calls.
- Use Chrome's alarms API for scheduling tasks instead of setInterval.

**Development Process**
1. Start by outlining the extension's functionality and required components.
2. Create the manifest.json file with necessary permissions and configurations.
3. Develop background scripts for core functionality and event handling.
4. Create content scripts for page manipulation (if required).
5. Design and implement popup UI and functionality.
6. Develop options page for user-configurable settings (if needed).
7. Implement message passing between different components.
8. Write necessary CSS for styling popup and options pages.
9. Test the extension thoroughly in different scenarios.

**Internationalization**
- Use Chrome's i18n API for multi-language support.
- Externalize user-facing strings in _locales folder.

**Testing and Debugging**
- Use Chrome's developer tools for debugging (especially the dedicated panels for service workers and extensions).
- Implement unit tests using frameworks like Jest.
- Perform cross-browser testing if aiming for compatibility with other Chromium-based browsers.

**Publishing**
- Prepare a detailed description, screenshots, and promotional tiles for the Chrome Web Store.
- Create a privacy policy and terms of service if handling user data.
- Follow Chrome Web Store's best practices and policies for successful submission.

**Example Extensions**
You can reference these example extensions:
1. A simple ad-blocker
2. A productivity timer with notifications
3. A custom new tab page
4. A password generator and manager

**Post-Development**
Follow Chrome Extension documentation and best practices from the official Google Developers site for up-to-date information.
golang
html
java
javascript
jest
less

First seen in:

deepc0py/wwwllm

Used in 1 repository

Python
<general_rules>
Best Practices for writing code:
* DRY and SOLID Principles: Keep the code modular, maintainable, and efficient.
* Readability and Maintainability: Keep the code concise and readable, add comments to explain complex logic.
* Declarative and Functional: Prefer declarative configurations, functional paradigms, and immutability to ensure predictable behavior.
* Error Handling and Security: Ensure the code is secure with proper error handling mechanisms.
</general_rules>

<working_with_llms>
When calling Large Language Models (LLMs), you should use the package `appl` to build the application (The name on `pypi` is `applang`, so it should be installed with `pip install -U applang`).

When working with LLMs, you should have clear format instructions to guide the LLMs to generate the desired output, and have appropriate parser to parse the output into the desired format. The format should be designed clear and easy to parse, consider using format like markdown's code block.

You should add `stream=True` for tasks that require LLMs to generate a large amount of text.
</working_with_llms>

<explain_appl>
APPL is a package that integrates prompts of LLMs into the code.
- `@ppl` is a decorator that marks a function as a prompt function, the function cannot be a coroutine (async function).
- Grow your prompt by calling `grow()`, a implicit newline is added between each component. When being asked to be implicit, you can remove the `grow()` function and leave the content inside `grow` as it is, APPL will automatically add the `grow()` function for you during runtime.
- The docstring of the `@ppl` function will not be counted as a part of the prompt by default. If that part is meant to be the system prompt, you can specified that using `@ppl(docstring_as="system")`.
- The `gen` function is a wrapper around `litellm.completion`, it returns a future object, it will automatically takes the prompt captured so far as the prompt for the LLM. See the example below for more details. Note that you do not need to wrap `gen` in AIRole() scope to call it for generation.
- You can use `with role:` to specify the role of the message, for example `with AIRole():` to specify the prompt growed in the scope as the assistant message. The default scope is `user`.
- To get the result of `gen` immediately, use `str()` to convert it to a string. Otherwise, it is a `Generation` object where you can take the `result` attribute to get the result.
- Try to delay the time you get the result of `gen` as much as possible, so that the code can be more parallelized. See the example below for more details.
- When writing multi-line prompt, it is recommended to `grow` the prompt multiple times to utilize the implicit compositor that adds a newline between each component. This way provides a better control over the prompt where you can easily comment out parts of the prompt. But you can also use multi-line string with indentation aligning with the code (it will be dedented similar to docstring before being used in the code).

<example>

```python
from appl import AIRole, gen, grow, ppl
from appl.const import NEWLINE


@ppl(ctx="copy")  # copy the context (prompt) from caller, so that the prompt in different runs are independent
def get_answer(question: str):
    grow(question)  # grow the prompt by appending the question
    # do not need with AIRole() scope here, `gen` is not bind to any role
    return gen()  # run llm generation with the current prompt, return as a future object


@ppl  # marks APPL function
def answer_questions(quotation: str, questions: list[str]):
    grow("Extract the name of the author from the quotation below and answer questions.")
    grow(quotation)  # append to the prompt
    with AIRole():  # the prompt inside this scope will be used as the assistant message
        grow("The name of the author is") # specify the prefix
        response = gen(stop='.') # each stop sequence must contain non-whitespace, could not be '\n' only.
        grow(response)  # append the response to the prompt
    return [get_answer(q) for q in questions]  # parallelize calls, result contains a list of futures


quotation = '"Simplicity is the ultimate sophistication." -- Leonardo da Vinci'
questions = [
    "In what era did the author live?",
    "What is the most famous painting of the author?",
]
for ans in answer_questions(quotation, questions):
    print(ans) # print the result of the future
```

The prompt and output for the three `gen` calls will looks like:

Prompt:
```yaml
- User:
    Extract the name of the author from the quotation below and answer questions.
    "Simplicity is the ultimate sophistication." -- Leonardo da Vinci
- Assistant:
    The name of the author is 
```
Output: Leonardo da Vinci.

Prompt:
```yaml
- User:
    Extract the name of the author from the quotation below and answer questions.
    "Simplicity is the ultimate sophistication." -- Leonardo da Vinci
- Assistant:
    The name of the author is Leonardo da Vinci.
- User:
    In what era did the author live?
```
Output: Renaissance era.

Prompt:
```yaml
- User:
    Extract the name of the author from the quotation below and answer questions.
    "Simplicity is the ultimate sophistication." -- Leonardo da Vinci
- Assistant:
    The name of the author is Leonardo da Vinci.
- User:
    What is the most famous painting of the author?
```
Output: Mona Lisa.

The two questions are answered in parallel, since the generation are future objects until being evaluated by `str` or printing, so the main process is not blocked by the LLM.
</example>

<example>
You are encouraged to use `response_format` to specify the format of the response to be a pydantic model.

```python
from pydantic import BaseModel
from appl import gen, grow, ppl

class Response(BaseModel):
    answer: int
    # Note: dict type is not supported yet by openai, but can be used for anthropic models.

@ppl
def get_answer(question: str):
    grow(question)
    # you should use `response_obj` to get the result when using response_format equals to a pydantic model
    return gen(response_format=Response).response_obj


print(get_answer("1+1=?"))
```

The result will be: `answer=2`
</example>
<example>
You can use `records()` to return the prompt captured so far in this function. This can be useful to modularize the prompts.
For the system prompt, the example illustrates two ways to add it.

```python
from appl import SystemMessage, gen, grow, ppl, records

@ppl
def subprompt():
    grow(f"Hello, {name}!")
    return records() # return the prompt growed in the current function so far

@ppl
def hello1(name: str):
    grow(SystemMessage("You are a helpful assistant.")) # one way to add system prompt
    grow(subprompt())
    return gen()

@ppl(docstring_as="system")
def hello2(name: str):
    """You are a helpful assistant."""
    grow(subprompt())
    return gen()

print(hello1("APPL"))
print(hello2("APPL"))
```
The prompt for both `gen` calls in `hello1` and `hello2` will looks like:
```yaml
- System:
    You are a helpful assistant.
- User:
    Hello, APPL!
```

</example>

<example>
You can use compositors to build the prompt, which specify the indexing, indentation, and separation between different parts of the prompt (growed by `grow()`) inside its scope. Some useful compositors include: Tagged, NumberedList.
The Tagged wraps the content inside with opening and closing tag, and NumberedList indexes each single prompt part.
You are encouraged to use Tagged to wrap contents to make the prompt more readable.

```python
from appl import ppl, gen, grow
from appl.compositor import NumberedList, Tagged


@ppl
def guess_output(hints: list[str], inputs: str):
    grow("Guess the output of the input.")
    with Tagged("hints"):
        with NumberedList():
            grow("First hint")
            grow(hints)  # list will be captured one by one

    with Tagged("inputs"):
        grow(inputs)

    grow("What's the output of the input?")

    return gen()

print(guess_output(["The output involves addition", "The output is a single number"], "1, 2, 3"))
```

The prompt will looks like:
```yaml
- User:
    Guess the output of the input.
    <hints>
    1. First hint
    2. The output involves addition
    3. The output is a single number
    </hints>
    <inputs>
    1, 2, 3
    </inputs>
    What's the output of the input?
```

</example>

<best_practices>
Though you can call LLMs to generate one thing at a time, you are encouraged to combine them into a single call with proper formatting and parsing (or using pydantic model as `response_format`) to reduce cost. For example, when being asked to generate a person's name and age:
```python
class Person(BaseModel):
    name: str
    age: int

# you should NOT do this
@ppl
def wrong_way_to_get_name_and_age():
    grow("Generate a person's name and age.")
    grow("name:")
    name = gen()
    grow(name)
    
    grow("age:")
    age = gen()
    grow(age)
    return Person(name=name, age=age) # could generate in wrong format

# you could do this
@ppl
def parse_to_get_name_and_age() -> Person:
    grow("Generate a person's name and age.")
    grow("Response in JSON format wrapped in ```json and ```, with name and age fields.")
    response = gen()
    # omit the code to use `regex` and `json.loads` to parse the response into a dict
    person: Person = parse_response(response)
    return person

# or this (generally more recommended, you do not need to include format instructions in the prompt)
@ppl
def pydantic_to_get_name_and_age() -> Person:
    grow("Generate a person's name and age.")
    return gen(response_format=Person).response_obj
```
</best_practices>

</explain_appl>
html
less
openai
python
shell
solidjs

First seen in:

appl-team/appl

Used in 1 repository

Python
    你是一位数据分析、可视化和Jupyter Notebook开发的专家,专注于Python库如pandas、matplotlib、seaborn和numpy。

    核心原则:
    - 编写简洁、技术性的响应,并提供准确的Python示例。
    - 优先考虑数据分析工作流程的可读性和可重复性。
    - 在适当的情况下使用函数式编程;避免不必要的类。
    - 优先使用向量化操作而不是显式循环以提高性能。
    - 使用能反映数据内容的描述性变量名。
    - 遵循Python的PEP 8风格指南。

    数据分析和处理:
    - 使用pandas进行数据处理和分析。
    - 尽可能使用方法链进行数据转换。
    - 使用loc和iloc进行明确的数据选择。
    - 利用groupby操作进行高效的数据聚合。

    可视化:
    - 使用matplotlib进行低级绘图控制和自定义。
    - 使用seaborn进行统计可视化,获得美观的默认效果。
    - 创建信息丰富且视觉吸引人的图表,包含适当的标签、标题和图例。
    - 使用适当的配色方案,并考虑色盲可访问性。

    Jupyter Notebook最佳实践:
    - 使用markdown单元格构建清晰的章节结构。
    - 使用有意义的单元格执行顺序以确保可重复性。
    - 在markdown单元格中包含解释性文本,记录分析步骤。
    - 保持代码单元格的重点突出和模块化,便于理解和调试。
    - 使用魔法命令如%matplotlib inline进行内联绘图。

    错误处理和数据验证:
    - 在分析开始时实施数据质量检查。
    - 适当处理缺失数据(填充、删除或标记)。
    - 对容易出错的操作使用try-except块,特别是在读取外部数据时。
    - 验证数据类型和范围以确保数据完整性。

    性能优化:
    - 在pandas和numpy中使用向量化操作以提高性能。
    - 利用高效的数据结构(如对低基数字符串列使用分类数据类型)。
    - 考虑使用dask处理超出内存的数据集。
    - 分析代码以识别和优化瓶颈。

    依赖项:
    - pandas
    - numpy
    - matplotlib
    - seaborn
    - jupyter
    - scikit-learn(用于机器学习任务)

    关键约定:
    1. 以数据探索和汇总统计开始分析。
    2. 创建可重用的绘图函数以保持可视化的一致性。
    3. 清晰记录数据来源、假设和方法论。
    4. 使用版本控制(如git)跟踪笔记本和脚本的变更。

    参考pandas、matplotlib和Jupyter的官方文档以获取最佳实践和最新API。
css
html
javascript
python

First seen in:

2606531498/pybox

Used in 1 repository

HTML
This is an interactive web article about the Kalman Filter, an algorithm which is used extensively in everything from robotics to neuroscience to estimate the state of time-varying systems. At its core, the Kalman Filter is a marriage of Probability first-principles with Linear Systems theory. Both of these topics are beautiful and make a lot of intuitive sense, but it is not easy to see that if your first exposure is to the full matrix equations of the Kalman Filter. The goal of this project is to break the Kalman Filter down into its subcomponents and use interactive elements to create a concise, intuitive explanation that is approachable for all levels of experience.

There are four primary interactive elements for this article. The user is able to:
- Hover with the mouse over each symbol/expression in the algorithm and get an explanation of what that term represents, and how it makes sense in terms of probability first-principles.This will make it easier to see the layers of interpretation that each term contains (from definitions to intuition), and arrange them spatially. This is an improvement over reading paragraphs of derivations and then referring back to the algorithm to see how they're incorporated in the intimidating matrix equations.
- Manually type in the desired naming convention, or click buttons to change between pre-set naming conventions. All of the variables will be provided in a table with a description of their role, but the user will have control over what symbols should be used to represent each variable, and these choices will propagate to the entire article. This will make it easier to match the description in this article to other sources.
- Drag the values in each matrix with the mouse, and visualize the effect in a plot that contains the Gaussian distributions of the current state estimate, current measurement, and the combined estimate using the Kalman Gain. There will be multiple examples: a 1D cart with LiDAR, and a 2D example of altitude estimation with a rocket.
- See the plot of how the Kalman Filter performs over time (with a 95% confidence interval) in light of the changes the user made to the different matrices.
css
express.js
golang
html
javascript
arthurlovekin/interactive_kalman_filter

Used in 1 repository