hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7982b35995d4443d95ac6c33f6be2fcf331cb382
| 2,545
|
php
|
PHP
|
src/Repository/ServiceRepository.php
|
GlobalEmergency/apuntate-back
|
5e2effba498d5293d93e6bf91ce44f1ced920fb0
|
[
"MIT"
] | 6
|
2021-12-13T10:01:14.000Z
|
2022-01-07T21:13:18.000Z
|
src/Repository/ServiceRepository.php
|
GlobalEmergency/apuntate-back
|
5e2effba498d5293d93e6bf91ce44f1ced920fb0
|
[
"MIT"
] | null | null | null |
src/Repository/ServiceRepository.php
|
GlobalEmergency/apuntate-back
|
5e2effba498d5293d93e6bf91ce44f1ced920fb0
|
[
"MIT"
] | 1
|
2022-01-07T20:55:03.000Z
|
2022-01-07T20:55:03.000Z
|
<?php
namespace App\Repository;
use App\Entity\Service;
use Carbon\Carbon;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Service|null find($id, $lockMode = null, $lockVersion = null)
* @method Service|null findOneBy(array $criteria, array $orderBy = null)
* @method Service[] findAll()
* @method Service[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ServiceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Service::class);
}
public function findBetweenDates(\DateTime $dateStart, \DateTime $dateEnd){
return $this->createQueryBuilder('s')
->andWhere('s.dateStart BETWEEN :start AND :end')
->setParameter('start', $dateStart->format('Y-m-d H:i'))
->setParameter('end', $dateEnd->format('Y-m-d H:i'))
->orderBy('s.dateStart', 'ASC')
// ->setMaxResults(10)
->getQuery()
->getResult()
;
}
// /**
// * @return Service[] Returns an array of Service objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('s')
->andWhere('s.exampleField = :val')
->setParameter('val', $value)
->orderBy('s.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Service
{
return $this->createQueryBuilder('s')
->andWhere('s.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
public function findNexts(\DateTime $date = null, bool $prev=false)
{
if(is_null($date)){
$date = Carbon::now();
}elseif($date instanceof \DateTime) {
$date = Carbon::instance($date);
}
if($prev){
$date->subDays(15);
}
return $this->createQueryBuilder('s')
->andWhere('s.dateStart > :date')
->setParameter('date', $date)
->orderBy('s.dateStart', 'ASC')
->getQuery()
->getResult()
;
}
public function save(Service $service)
{
$this->_em->persist($service);
$this->_em->flush($service);
}
}
| 27.663043
| 101
| 0.552456
|
72d2caa46877f3f63162d3997c78c89ac6e36cba
| 55,260
|
cs
|
C#
|
Sistema/Sistema/factura2.cs
|
sanfernand0/Facturacion
|
7ab2893ff9551d8afb60a1c3da4b0ae18f6ecb8c
|
[
"MIT"
] | null | null | null |
Sistema/Sistema/factura2.cs
|
sanfernand0/Facturacion
|
7ab2893ff9551d8afb60a1c3da4b0ae18f6ecb8c
|
[
"MIT"
] | null | null | null |
Sistema/Sistema/factura2.cs
|
sanfernand0/Facturacion
|
7ab2893ff9551d8afb60a1c3da4b0ae18f6ecb8c
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Sistema
{
public partial class factura2 : Form
{
OleDbConnection conexion = new OleDbConnection(Program.GGG.conectar);
AutoCompleteStringCollection clientes = new AutoCompleteStringCollection();
DataTable dt = new DataTable("Inventario");
double subtotal, totaltotal, descuentobd, ISV, subtotal2;
double descuentototal;
int cantidad = 0;
double precio = 0;
double precio1;
string prefijo;
string numero_factura;
string numero_factura2;
int siguiente;
bool exento;
string grupo, marca, codigo, descripcion;
int cantidadfactura;
double preciofactura;
public factura2()
{
InitializeComponent();
actualizar();
textBox4.Text = DateTime.Now.ToShortDateString();
textBox1.Text = "Consumidor Final";
comboBox2.Text = "Contado";
textBox1.Focus();
textBox9.Clear();
limpiar();
cargarclientes();
label12.Text = "Usuario: " + Program.usuario;
obtenerDescuento();
obtenerDatos();
dataGridView2.Columns[4].FillWeight = 300;
checkBox4.Checked = true;
}
public void actualizar()
{
try
{
conexion.Open();
OleDbDataAdapter data = new OleDbDataAdapter("SELECT id, grupo, marca, codigo, descripcion, aplicacion, referencia, bodega1, tienda1, precio1, precio2, exento as Exento FROM inventario ORDER BY id ASC", conexion);
data.Fill(dt);
dataGridView2.DataSource = dt;
dataGridView2.Columns[9].DefaultCellStyle.Format = "N2";
dataGridView2.Columns[10].DefaultCellStyle.Format = "N2";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void obtenerDescuento()
{
try
{
conexion.Open();
OleDbCommand comando = new OleDbCommand("SELECT descuento from datos", conexion);
OleDbDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
descuentobd = Convert.ToDouble(reader.GetInt32(0));
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void obtenerDatos()
{
try
{
conexion.Open();
OleDbCommand comando = new OleDbCommand("SELECT cai, rango, fecha_limite from datos", conexion);
OleDbDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
Program.cai = Convert.ToString(reader.GetString(0));
Program.rango = Convert.ToString(reader.GetString(1));
Program.fecha_limite = Convert.ToDateTime(reader.GetDateTime(2));
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void cargarclientes()
{
try
{
conexion.Open();
OleDbCommand comando = new OleDbCommand("SELECT *FROM clientes ORDER BY Cliente ASC", conexion);
OleDbDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
clientes.Add(reader.GetString(1));
}
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteCustomSource = clientes;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void limpiar()
{
Program.codigo = "";
Program.descripcion = "";
Program.precio1 = 0;
Program.precio2 = 0;
Program.tienda1 = 0;
Program.bodega1 = 0;
Program.grupo = "";
Program.marca = "";
}
private void button4_Click(object sender, EventArgs e)
{
this.Dispose();
this.Close();
}
private void button5_Click(object sender, EventArgs e)
{
try
{
fmrAgregarCliente r = new fmrAgregarCliente();
r.FormClosed += new FormClosedEventHandler(factura_FormClosed);
r.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
try
{
if (checkBox1.Checked)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("codigo like '%{0}%'", textBox9.Text);
dataGridView2.DataSource = dv.ToTable();
}
else
if (checkBox2.Checked)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("grupo like'%{0}%'", textBox9.Text);
dataGridView2.DataSource = dv.ToTable();
}
else
if (checkBox3.Checked)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("marca like'%{0}%' ", textBox9.Text);
dataGridView2.DataSource = dv.ToTable();
}
else
if (checkBox4.Checked)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("grupo like'%{0}%' OR marca like'%{0}%' OR descripcion like'%{0}%' OR codigo like '%{0}%' OR referencia like '%{0}%' OR aplicacion like '%{0}%'", textBox9.Text);
dataGridView2.DataSource = dv.ToTable();
}
else
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("grupo like'%{0}%' OR marca like'%{0}%' OR descripcion like'%{0}%' OR codigo like '%{0}%' OR referencia like '%{0}%' OR aplicacion like '%{0}%'", textBox9.Text);
dataGridView2.DataSource = dv.ToTable();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
try
{
subtotal = 0;
ISV = 0;
totaltotal = 0;
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox9.Focus();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
subtotal += Convert.ToDouble(row.Cells[4].Value);
}
ISV = Program.ISV * subtotal;
totaltotal = subtotal + ISV;
textBox7.Text = ISV.ToString("N2");
textBox8.Text = totaltotal.ToString("N2");
textBox6.Text = subtotal.ToString("N2");
} catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.Rows.Count > 0)
{
if (dataGridView1.Rows[dataGridView1.CurrentRow.Index].Selected == true)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
subtotal = 0;
ISV = 0;
totaltotal = 0;
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox9.Focus();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
subtotal += Convert.ToDouble(row.Cells[4].Value);
}
ISV = Program.ISV * subtotal;
totaltotal = subtotal + ISV;
textBox7.Text = ISV.ToString("N2");
textBox8.Text = totaltotal.ToString("N2");
textBox6.Text = subtotal.ToString("N2");
}
else
{
dataGridView1.ClearSelection();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
int contador = 0;
///// Se establece el tipo de Fuente
Font Fuente = new Font("Verdana", 7);
Font Fuente_Factura = new Font("Verdana", 7);
//titulo
Font fuente_titulo = new Font("Verdana", 14, FontStyle.Bold);
Font fuente_titulo2 = new Font("Verdana", 9, FontStyle.Bold);
///// Se establece el Color de Fuente
Brush Brocha = Brushes.Black;
///// Se establece las cordenadas
int Y = 75;
//se genera el cuadro de la fecha y #cotizacion
e.Graphics.DrawRectangle(Pens.Black, 580, 15, 215, 80);
e.Graphics.DrawString("Factura: " + numero_factura2, new Font("Verdana", 8), Brocha, 580, 15);
e.Graphics.DrawString("Fecha: " + textBox4.Text, new Font("Verdana", 9), Brocha, 580, 35);
//e.Graphics.DrawLine(Pens.Black, 450, 385, 450, 400);
e.Graphics.DrawString("Vendedor: " + Program.usuario, new Font("Verdana", 9), Brocha, 580, 55);
//cuadritos de contado credito checkbox
e.Graphics.DrawString("Contado: ", Fuente, Brocha, 580, 75);
e.Graphics.DrawString("Credito: ", Fuente, Brocha, 680, 75);
e.Graphics.DrawRectangle(Pens.Black, 645, 75, 15, 15);
e.Graphics.DrawRectangle(Pens.Black, 745, 75, 15, 15);
if (comboBox2.Text == "Contado")
{
e.Graphics.DrawString("\u221A", Fuente, Brocha, 645, 75);
}
else
{
e.Graphics.DrawString("\u221A", Fuente, Brocha, 745, 75);
}
//fin del cuadro fecha cotizacion
//se genera el cuadro de los articulos
//e.Graphics.DrawRectangle(Pens.Black, 20, 120, 780, 12);
e.Graphics.DrawLine(Pens.Black, 20, 171, 800, 171);
e.Graphics.DrawRectangle(Pens.Black, 20, 120, 780, 275);
//lineas verticales
e.Graphics.DrawLine(Pens.Black, 150, 160, 150, 335);
e.Graphics.DrawLine(Pens.Black, 550, 160, 550, 335);
e.Graphics.DrawLine(Pens.Black, 630, 160, 630, 335);
e.Graphics.DrawLine(Pens.Black, 710, 160, 710, 335);
//e.Graphics.DrawRectangle(Pens.Black, 20, 175, 560, 285);
//e.Graphics.DrawRectangle(Pens.Black, 20, 175, 630, 285);
//e.Graphics.DrawRectangle(Pens.Black, 20, 175, 720, 285);
//e.Graphics.DrawRectangle(Pens.Black, 20, 175, 780, 285);
//se genera el cuadro de los totales
e.Graphics.DrawRectangle(Pens.Black, 20, 335, 780, 15);
e.Graphics.DrawRectangle(Pens.Black, 20, 350, 780, 15);
e.Graphics.DrawRectangle(Pens.Black, 20, 365, 780, 15);
e.Graphics.DrawRectangle(Pens.Black, 20, 380, 780, 15);
e.Graphics.DrawRectangle(Pens.Black, 20, 395, 780, 15);
e.Graphics.DrawRectangle(Pens.Black, 20, 410, 780, 40);
//se genera el cuadro de la nota
e.Graphics.DrawRectangle(Pens.Black, 20, 453, 780, 30);
//linea vertical que divide nro de orden
e.Graphics.DrawLine(Pens.Black, 400, 410, 400, 450);
//firma del cliente
e.Graphics.DrawLine(Pens.Black, 35, 435, 350, 435);
e.Graphics.DrawString("Nombre Y Firma del Cliente", Fuente, Brocha, 80, 435);
e.Graphics.DrawString("N° De Orden De Compra Exenta: ", Fuente, Brocha, 410, 410);
e.Graphics.DrawString("N° Constancia De Registro De Exoneración: ", Fuente, Brocha, 410, 425);
e.Graphics.DrawString("N° Registro De La SAG: ", Fuente, Brocha, 410, 438);
e.Graphics.DrawString("ORIGINAL - CLIENTE COPIA 1 - OBLIGADO TRIBUTARIO EMISOR COPIA 2", Fuente, Brocha, 20, 453);
e.Graphics.DrawString("\"La factura es beneficio de todos, exijala\"", Fuente, Brocha, 580, 453);
e.Graphics.DrawString("**Nota: No se aceptan cambios ni devoluciones en productos electricos**", new Font("Verdana", 5), Brocha, 20, 463);
e.Graphics.DrawString("**Nota: No se aceptan cambios con facturas al credito**", new Font("Verdana", 5), Brocha, 20, 473);
//e.Graphics.DrawRectangle(Pens.Black, 20, 465, 780, 35);
//e.Graphics.DrawLine(Pens.Black, 20, 482, 825, 482);
//e.Graphics.DrawLine(Pens.Black, 250, 465, 250, 482);
//e.Graphics.DrawLine(Pens.Black, 450, 465, 450, 482);
//e.Graphics.DrawLine(Pens.Black, 640, 465, 640, 482);
//e.Graphics.DrawLine(Pens.Black, 450, 482, 450, 500);
e.Graphics.DrawString(Program.GGG.empresa, fuente_titulo, Brocha, 188, 25);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
//muestra el logo
Bitmap logo = Sistema.Properties.Resources.logo;
e.Graphics.DrawImage(logo, 10, 5, 170, 110);
e.Graphics.DrawString("" + Program.GGG.direccion, Fuente, Brocha, 190, 60);//Direccion
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("RTN: " + Program.GGG.RTN + " Correo: " + Program.GGG.correo, Fuente, Brocha, 190, 75);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Tel: " + Program.GGG.telefono_empresa, Fuente, Brocha, 190, 90);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Codigo", Fuente, Brocha, 20, 159);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Descripcion", Fuente, Brocha, 160, 159);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Cantidad", Fuente, Brocha, 550, 159);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Precio", Fuente, Brocha, 630, 159);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Total", Fuente, Brocha, 710, 159);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
//e.Graphics.DrawLine(Pens.Black, 20, 196, 823, 196);
//se genera el cuadro de los clientes
e.Graphics.DrawRectangle(Pens.Black, 20, 120, 780, 40);
//linea vertical que divide el cuadro de clientes
e.Graphics.DrawLine(Pens.Black, 400, 120, 400, 170);
// e.Graphics.DrawRectangle(Pens.Black, 399, 110, 426, 40);
e.Graphics.DrawString("Cliente: " + textBox1.Text, Fuente, Brocha, 20, 120);
e.Graphics.DrawString("Rango: " + Program.rango, Fuente, Brocha, 400, 120);
e.Graphics.DrawString("RTN: " + textBox2.Text, Fuente, Brocha, 20, 132);
e.Graphics.DrawString("Fecha Limite De Emision: " + Program.fecha_limite.ToShortDateString(), Fuente, Brocha, 400, 132);
e.Graphics.DrawString("Dirección: " + textBox3.Text, Fuente, Brocha, 20, 144);//Direccion
e.Graphics.DrawString("CAI: " + Program.cai, Fuente, Brocha, 400, 144);
//cuadritos de contado credito checkbox
//e.Graphics.DrawString("Contado: ", Fuente, Brocha, 190, 110);
//e.Graphics.DrawString("Credito: ", Fuente, Brocha, 290, 110);
//e.Graphics.DrawRectangle(Pens.Black, 240, 110, 15, 15);
//e.Graphics.DrawRectangle(Pens.Black, 340, 110, 15, 15);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Far;
//se genera el cuadro de los articulos
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (contador <= 16)
{
string codigo = row.Cells[0].Value.ToString();
string descripcion = row.Cells[2].Value.ToString();
int cantidad = Convert.ToInt32(row.Cells[3].Value);
double precio = Convert.ToDouble(row.Cells[4].Value);
double total2 = Convert.ToDouble(row.Cells[5].Value);
e.Graphics.DrawString(codigo, Fuente, Brocha, 23, Y);
e.Graphics.DrawString(descripcion, Fuente, Brocha, 160, Y);
e.Graphics.DrawString(cantidad.ToString(), Fuente, Brocha, 590, Y);
e.Graphics.DrawString(precio.ToString("N2"), Fuente, Brocha, 710, Y, stringFormat);
e.Graphics.DrawString(total2.ToString("N2"), Fuente, Brocha, 780, Y, stringFormat);
Y = Y + 10;
}
}
//e.Graphics.DrawString("Desc Otorgados: ", Fuente, Brocha, 23, 351);
//e.Graphics.DrawString("" + textBox5.Text, Fuente, Brocha, 23, 366);
//Y = Convert.ToInt32(Y + Fuente.GetHeight());
//imprime descuento
e.Graphics.DrawString("Rebajas Otorgadas.", Fuente, Brocha, 23, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 110, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Importe Exento L.", Fuente, Brocha, 120, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 205, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 120, 335, 120, 365);//linea vertical
e.Graphics.DrawString("Importe Gravado L.", Fuente, Brocha, 210, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 310, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 210, 335, 210, 365);//linea vertical
e.Graphics.DrawString("Importe Exonerado L.", Fuente, Brocha, 310, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 420, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 310, 335, 310, 365);//linea vertical
e.Graphics.DrawString("ISV 18% L.", Fuente, Brocha, 440, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 510, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 420, 335, 420, 365);//linea vertical
e.Graphics.DrawString("Importe gravado 18% L.", Fuente, Brocha, 510, 336);
e.Graphics.DrawString("" + "0.00", Fuente, Brocha, 640, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 510, 335, 510, 365);//linea vertical
e.Graphics.DrawString("Importe gravado 15% L.", Fuente, Brocha, 640, 336);
e.Graphics.DrawString("" + textBox6.Text, Fuente, Brocha, 780, 351, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 640, 335, 640, 365);//linea vertical
e.Graphics.DrawString("Total L.", Fuente, Brocha, 23, 366);
e.Graphics.DrawString("" + (subtotal + subtotal2).ToString("N2"), Fuente, Brocha, 110, 381, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawString("Descuentos Otorgados L.", Fuente, Brocha, 120, 366);
e.Graphics.DrawString(textBox5.Text, Fuente, Brocha, 250, 381, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 120, 365, 120, 395);//linea vertical
e.Graphics.DrawString("Sub-Total L.", Fuente, Brocha, 300, 366);
e.Graphics.DrawString(textBox6.Text, Fuente, Brocha, 420, 381, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 260, 365, 260, 395);//linea vertical
e.Graphics.DrawString("ISV 15% L.", Fuente, Brocha, 500, 366);
e.Graphics.DrawString(textBox7.Text, Fuente, Brocha, 610, 381, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 440, 365, 440, 395);//linea vertical
e.Graphics.DrawString("Total a Pagar L.", Fuente, Brocha, 660, 366);
e.Graphics.DrawString(textBox8.Text, Fuente, Brocha, 780, 381, stringFormat);
Y = Convert.ToInt32(Y + Fuente.GetHeight());
e.Graphics.DrawLine(Pens.Black, 610, 365, 610, 395);//linea vertical
//e.Graphics.DrawString("ISV: ", Fuente, Brocha, 630, 336);
//e.Graphics.DrawString("" + textBox7.Text, Fuente, Brocha, 630, 351);
//Y = Convert.ToInt32(Y + Fuente.GetHeight());
//e.Graphics.DrawLine(Pens.Black, 630, 335, 630, 365);//linea vertical
//e.Graphics.DrawString("Total: ", Fuente, Brocha, 710, 336);
//e.Graphics.DrawString("" + textBox8.Text, Fuente, Brocha, 710, 351);
//Y = Convert.ToInt32(Y + Fuente.GetHeight());
//e.Graphics.DrawLine(Pens.Black, 710, 335, 710, 365);//linea vertical
//total en letras
Conv r = new Conv();
e.Graphics.DrawString("Total en Letras: " + r.enletras(textBox8.Text), Fuente, Brocha, 23, 395);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void numFactura()
{
try
{
conexion.Open();
if (dataGridView1.Rows.Count > 0)
{
OleDbCommand comando200 = new OleDbCommand("SELECT MAX(prefijo) FROM datos", conexion);
prefijo = Convert.ToString(comando200.ExecuteScalar());
OleDbCommand comando9 = new OleDbCommand("SELECT MAX(factura) FROM datos", conexion);
numero_factura = Convert.ToString(comando9.ExecuteScalar());
if (Convert.ToInt32(numero_factura) >= 1 && Convert.ToInt32(numero_factura) <= 9)
{
string n = "0000000";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 10 && Convert.ToInt32(numero_factura) <= 99)
{
string n = "000000";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 100 && Convert.ToInt32(numero_factura) <= 999)
{
string n = "00000";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 1000 && Convert.ToInt32(numero_factura) <= 9999)
{
string n = "0000";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 10000 && Convert.ToInt32(numero_factura) <= 99999)
{
string n = "000";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 100000 && Convert.ToInt32(numero_factura) <= 999999)
{
string n = "00";
numero_factura2 = prefijo + n + numero_factura;
}
if (Convert.ToInt32(numero_factura) >= 1000000 && Convert.ToInt32(numero_factura) <= 999999)
{
string n = "0";
numero_factura2 = prefijo + n + numero_factura;
}
siguiente = Convert.ToInt32(numero_factura) + 1;
string update2 = "UPDATE datos set factura = '" + siguiente + "' WHERE Id=" + 1 + "";
OleDbCommand comando2 = new OleDbCommand(update2, conexion);
comando2.ExecuteNonQuery();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void insertVentas()
{
try
{
conexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
grupo = Convert.ToString(row.Cells[8].Value);
}
catch
{
grupo = "";
}
try
{
marca = Convert.ToString(row.Cells[9].Value);
}
catch
{
marca = "";
}
try
{
codigo = Convert.ToString(row.Cells[0].Value);
}
catch
{
codigo = "";
}
try
{
descripcion = Convert.ToString(row.Cells[2].Value);
}
catch
{
descripcion = "";
}
try
{
cantidadfactura = Convert.ToInt32(row.Cells[3].Value);
}
catch
{
cantidadfactura = 0;
}
try
{
preciofactura = Convert.ToDouble(row.Cells[4].Value);
}
catch
{
preciofactura = 0;
}
int codigo5 = 1;
OleDbCommand comando20 = new OleDbCommand("SELECT MAX(id) FROM ventas", conexion);
if(comando20.ExecuteScalar() != DBNull.Value)
{
codigo5 = Convert.ToInt32(comando20.ExecuteScalar());
codigo5 = codigo5 + 1;
}
if (Convert.ToBoolean(row.Cells[6].Value))
{
string insert3 = "INSERT INTO ventas VALUES (@id, @fecha, @numero_factura, @grupo, @marca, @codigo, @descripcion, @cantidad, @precio, @cliente, @rtn, @vendedor, @cai, @rango, @fecha_limite, @tipo, @fecha_anulacion, @isv)";
OleDbCommand comando7 = new OleDbCommand(insert3, conexion);
comando7.Parameters.AddWithValue("@id", codigo5);
comando7.Parameters.AddWithValue("@fecha", textBox4.Text);
comando7.Parameters.AddWithValue("@numero_factura", numero_factura);
comando7.Parameters.AddWithValue("@grupo", grupo);
comando7.Parameters.AddWithValue("@marca", marca);
comando7.Parameters.AddWithValue("@codigo", codigo);
comando7.Parameters.AddWithValue("@descripcion", descripcion);
comando7.Parameters.AddWithValue("@cantidad", cantidadfactura);
comando7.Parameters.AddWithValue("@precio", preciofactura);
comando7.Parameters.AddWithValue("@cliente", textBox1.Text);
comando7.Parameters.AddWithValue("@rtn", textBox2.Text);
comando7.Parameters.AddWithValue("@vendedor", Program.usuario);
comando7.Parameters.AddWithValue("@cai", Program.cai);
comando7.Parameters.AddWithValue("@rango", Program.rango);
comando7.Parameters.AddWithValue("@fecha_limite", Program.fecha_limite);
comando7.Parameters.AddWithValue("@tipo", comboBox2.Text);
comando7.Parameters.AddWithValue("@fecha_anulacion", "00");
comando7.Parameters.AddWithValue("@isv", 0);
comando7.ExecuteNonQuery();
}
else
{
string insert3 = "INSERT INTO ventas VALUES (@id, @fecha, @numero_factura, @grupo, @marca, @codigo, @descripcion, @cantidad, @precio, @cliente, @rtn, @vendedor, @cai, @rango, @fecha_limite, @tipo, @fecha_anulacion, @isv)";
OleDbCommand comando7 = new OleDbCommand(insert3, conexion);
comando7.Parameters.AddWithValue("@id", codigo5);
comando7.Parameters.AddWithValue("@fecha", textBox4.Text);
comando7.Parameters.AddWithValue("@numero_factura", numero_factura);
comando7.Parameters.AddWithValue("@grupo", grupo);
comando7.Parameters.AddWithValue("@marca", marca);
comando7.Parameters.AddWithValue("@codigo", codigo);
comando7.Parameters.AddWithValue("@descripcion", descripcion);
comando7.Parameters.AddWithValue("@cantidad", cantidadfactura);
comando7.Parameters.AddWithValue("@precio", preciofactura);
comando7.Parameters.AddWithValue("@cliente", textBox1.Text);
comando7.Parameters.AddWithValue("@rtn", textBox2.Text);
comando7.Parameters.AddWithValue("@vendedor", Program.usuario);
comando7.Parameters.AddWithValue("@cai", Program.cai);
comando7.Parameters.AddWithValue("@rango", Program.rango);
comando7.Parameters.AddWithValue("@fecha_limite", Program.fecha_limite);
comando7.Parameters.AddWithValue("@tipo", comboBox2.Text);
comando7.Parameters.AddWithValue("@fecha_anulacion", "00");
comando7.Parameters.AddWithValue("@isv", Program.ISV);
comando7.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
public void rebajar()
{
try
{
conexion.Open();
foreach (DataGridViewRow factura in dataGridView1.Rows)
{
int cantidad;
int cantidadinventario;
int idinventario;
cantidad = Convert.ToInt32(factura.Cells[3].Value);
cantidadinventario = Convert.ToInt32(factura.Cells[11].Value);
idinventario = Convert.ToInt32(factura.Cells[10].Value);
int resta = cantidadinventario - cantidad;
string update = "UPDATE inventario set bodega1 = '" + resta + "' WHERE id= " + idinventario + "";
OleDbCommand comando55 = new OleDbCommand(update, conexion);
comando55.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0 && textBox8.Text != "")
{
if (comboBox2.Text == "Contado")
{
try
{
numFactura();
insertVentas();
rebajar();
//para insertar en ventas
//para rebajar las cantidades de inventario
printDocument1.Print();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
if (comboBox2.Text == "Credito")
{
numFactura();
rebajar();
insertVentas();
//para insertar en ventas
//para rebajar las cantidades de inventario
printDocument1.Print();
try
{
conexion.Open();
int codigo = 1;
OleDbCommand comando22 = new OleDbCommand("SELECT MAX(Id) FROM ingresos", conexion);
if (comando22.ExecuteScalar() != DBNull.Value)
{
codigo = Convert.ToInt32(comando22.ExecuteScalar());
codigo = codigo + 1;
}
string insert = "INSERT INTO ingresos VALUES (@Id, @fecha, @numero_factura, @cliente, @monto, @tipo, @recibo, @fechaRecibo, @montoRecibo, @notaCredito, @fechaNotaCredito, @montoNotaCredito)";
OleDbCommand comando21 = new OleDbCommand(insert, conexion);
comando21.Parameters.AddWithValue("@id", codigo);
comando21.Parameters.AddWithValue("@fecha", textBox4.Text);
comando21.Parameters.AddWithValue("@numero_factura", numero_factura);
comando21.Parameters.AddWithValue("@cliente", textBox1.Text);
comando21.Parameters.AddWithValue("@monto", textBox8.Text);
comando21.Parameters.AddWithValue("@tipo", comboBox2.Text);
//comando21.Parameters.AddWithValue("@recibo", "");
//comando21.Parameters.AddWithValue("@fechaRecibo", textBox4.Text);
//comando21.Parameters.AddWithValue("@montoRecibo", "");
//comando21.Parameters.AddWithValue("@notaCredito", "");
//comando21.Parameters.AddWithValue("@fechaNotaCredito", textBox4.Text);
//comando21.Parameters.AddWithValue("@montoNotaCredito", "");
comando21.ExecuteNonQuery();
this.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
}
else
{
MessageBox.Show("Nada que imprimir", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
conexion.Open();
if (e.KeyValue== (char)Keys.Enter)
{
e.Handled = true;
if (textBox1.Text == "Consumidor Final")
{
textBox9.Focus();
}
else
{
OleDbCommand comando = new OleDbCommand("SELECT *FROM clientes", conexion);
OleDbDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
if (textBox1.Text == reader.GetString(1))
{
try
{
textBox2.Text = reader.GetString(8);
}
catch
{
textBox2.Text = "Error";
}
try
{
textBox3.Text = reader.GetString(2);
}
catch
{
textBox3.Text = "Error";
}
if (reader.GetBoolean(9) == true)
{
comboBox2.Items.Add("Credito");
}
else
{
comboBox2.Items.Remove("Credito");
}
}
}
textBox2.Focus();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
textBox3.Focus();
}
}
private void comboBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
textBox3.Focus();
}
}
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
textBox9.Focus();
}
}
public void cargarClick(object sender, EventArgs e)
{
cargar();
}
public void cargar()
{
try
{
try
{
Program.id = Convert.ToInt32(dataGridView2.CurrentRow.Cells[0].Value);
}
catch
{
Program.id = 0;
}
try
{
Program.tienda1 = Convert.ToInt32(dataGridView2.CurrentRow.Cells[7].Value);
}
catch
{
Program.tienda1 = 0;
}
try
{
Program.grupo = Convert.ToString(dataGridView2.CurrentRow.Cells[1].Value);
}
catch
{
Program.grupo = "";
}
try
{
Program.marca = Convert.ToString(dataGridView2.CurrentRow.Cells[2].Value);
}
catch
{
Program.marca = "";
}
try
{
Program.codigo = Convert.ToString(dataGridView2.CurrentRow.Cells[3].Value.ToString());
}
catch
{
Program.codigo = "";
}
try
{
Program.descripcion = Convert.ToString(dataGridView2.CurrentRow.Cells[4].Value.ToString());
}
catch
{
Program.descripcion = "";
}
try
{
Program.precio1 = Convert.ToDouble(dataGridView2.CurrentRow.Cells[9].Value);
}
catch
{
Program.precio1 = 0.00;
}
try
{
exento = Convert.ToBoolean(dataGridView2.CurrentRow.Cells[11].Value);
}
catch
{
}
int rowEscribir = dataGridView1.Rows.Count;
if (dataGridView1.Rows.Count < 13)
{
dataGridView1.Rows.Add(1);
dataGridView1.Focus();
dataGridView1.Rows[rowEscribir].Cells[0].Value = Program.codigo;
dataGridView1.Rows[rowEscribir].Cells[1].Value = 0.00;
dataGridView1.Rows[rowEscribir].Cells[2].Value = Program.descripcion;
dataGridView1.Rows[rowEscribir].Cells[4].Value = Program.precio1;
dataGridView1.Rows[rowEscribir].Cells[8].Value = Program.grupo;
dataGridView1.Rows[rowEscribir].Cells[9].Value = Program.marca;
dataGridView1.Rows[rowEscribir].Cells[10].Value = Program.id;
dataGridView1.Rows[rowEscribir].Cells[11].Value = Program.tienda1;
dataGridView1.Rows[rowEscribir].Cells[12].Value = Program.precio1;
dataGridView1.Rows[rowEscribir].Cells[6].Value = exento;
dataGridView1.CurrentCell = dataGridView1.Rows[rowEscribir].Cells[3];
//limpiar();
}
else
{
label11.Text = "Ya No Puede Agregar Mas Items A La Factura";
}
dataGridView2.ClearSelection();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cargarPress(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == (char)Keys.Enter && textBox9.Text == "")
{
e.Handled = true;
toolTip1.Show("Escriba algo", textBox9, 3000);
}
else
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
if (dataGridView2.Rows[dataGridView2.CurrentRow.Index].Selected == true)
{
cargar();
dataGridView2.ClearSelection();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void textBox9_KeyPress(object sender, KeyPressEventArgs e)
{
cargarPress(sender, e);
}
private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
if (dataGridView2.Rows[dataGridView2.CurrentRow.Index].Selected == true)
{
cargar();
dataGridView2.ClearSelection();
}
}
}catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
textBox9.Focus();
checkBox4.Checked = false;
checkBox3.Checked = false;
checkBox2.Checked = false;
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
textBox9.Focus();
checkBox4.Checked = false;
checkBox3.Checked = false;
checkBox1.Checked = false;
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
textBox9.Focus();
checkBox4.Checked = false;
checkBox2.Checked = false;
checkBox1.Checked = false;
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
textBox9.Focus();
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
}
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Escape)
{
c5.ReadOnly = false;
}
}
private void factura_FormClosed(object sender, FormClosedEventArgs e)
{
cargarclientes();
}
private void textBox9_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyValue == (char)Keys.Down)
{
dataGridView2.Focus();
}
}
private void dataGridView2_DoubleClick(object sender, EventArgs e)
{
cargarClick(sender, e);
}
public void totales(object sender, DataGridViewCellEventArgs e)
{
try
{
subtotal = 0;
ISV = 0;
subtotal2 = 0;
descuentototal = 0;
totaltotal = 0;
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox5.Clear();
cantidad = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["c4"].Value.ToString());
precio = double.Parse(dataGridView1.Rows[e.RowIndex].Cells["c5"].Value.ToString());
dataGridView1.Rows[e.RowIndex].Cells["c6"].Value = cantidad * precio;
textBox9.Clear();
textBox9.Focus();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["c7"].Value) == true)
{
subtotal += Convert.ToDouble(row.Cells["c6"].Value);
descuentototal += Convert.ToDouble(row.Cells["c8"].Value) * Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["c4"].Value);
}
else if (Convert.ToBoolean(row.Cells["c7"].Value) == false)
{
subtotal2 += Convert.ToDouble(row.Cells["c6"].Value);
descuentototal += Convert.ToDouble(row.Cells["c8"].Value) * Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["c4"].Value);
ISV = (Program.ISV * subtotal2);
}
}
totaltotal = subtotal + subtotal2 + ISV;
textBox7.Text = ISV.ToString("N2");
textBox8.Text = totaltotal.ToString("N2");
textBox6.Text = (subtotal + subtotal2).ToString("N2");
textBox5.Text = descuentototal.ToString("N2");
dataGridView1.ClearSelection();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
conexion.Open();
//editar cantidad
if (dataGridView1.Columns[e.ColumnIndex].Name == "c4")
{
totales(sender, e);
}
if (dataGridView1.Columns[e.ColumnIndex].Name == "c5")
{
try
{
double precio11 = double.Parse(dataGridView1.Rows[e.RowIndex].Cells["c5"].Value.ToString());
int idInventario = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["c11"].Value.ToString());
OleDbCommand comando200 = new OleDbCommand("SELECT precio2 FROM inventario where id = " + idInventario + "", conexion);
OleDbDataReader reader = comando200.ExecuteReader();
double precio33 = 0.00;
if (reader.Read())
{
precio33 = reader.GetDouble(0);
}
//if (precio11 < precio33)
//if (false)
//{
// MessageBox.Show("No se puede dar a ese precio, excede el precio minimo", "Precio demasiado bajo", MessageBoxButtons.OK, MessageBoxIcon.Error);
// dataGridView1.Rows[e.RowIndex].Cells["c5"].Value = precio;
//}
if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[1].Value) > 0)
{
totales(sender, e);
}
else
{
totales(sender, e);
c5.ReadOnly = true;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
if (dataGridView1.Columns[e.ColumnIndex].Name == "c2")
{
int descuentoprueb = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
if (descuentoprueb <= descuentobd)
{
descuentototal = 0;
precio1 = 0;
subtotal = 0;
ISV = 0;
subtotal2 = 0;
descuentototal = 0;
totaltotal = 0;
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox5.Clear();
precio1 = Convert.ToDouble(dataGridView1.Rows[e.RowIndex].Cells[12].Value);
double adescuento = (precio1 * Convert.ToDouble(dataGridView1.Rows[e.RowIndex].Cells[1].Value)) / 100;
double total = precio1 - adescuento;
// dataGridView1.Rows[e.RowIndex].Cells[4].Value = total;
//dataGridView1.Rows[e.RowIndex].Cells[5].Value = total * Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[3].Value);
dataGridView1.Rows[e.RowIndex].Cells["c8"].Value = adescuento;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells[6].Value) == true)
{
subtotal += Convert.ToDouble(row.Cells[5].Value);
descuentototal += Convert.ToDouble(row.Cells[7].Value) * Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[3].Value);
}
else if (Convert.ToBoolean(row.Cells[6].Value) == false)
{
subtotal2 += Convert.ToDouble(row.Cells[5].Value);
ISV += (Program.ISV * subtotal2);
descuentototal += Convert.ToDouble(row.Cells[7].Value) * Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[3].Value);
}
}
totaltotal = subtotal + subtotal2 + ISV - descuentototal;
textBox7.Text = ISV.ToString("N2");
textBox8.Text = totaltotal.ToString("N2");
textBox6.Text = ((subtotal + subtotal2) - descuentototal).ToString("N2");
textBox5.Text = descuentototal.ToString("N2");
dataGridView1.ClearSelection();
}
else
{
MessageBox.Show("Descuento Denegado");
dataGridView1.Rows[e.RowIndex].Cells[1].Value = 0;
totales(sender, e);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conexion.Close();
}
}
}
}
| 39.669777
| 246
| 0.464567
|
e23dd059ea36f0bf5219a70c8ee8e6a5aa009d2b
| 1,748
|
lua
|
Lua
|
LUA/game1.lua
|
AoiSaya/FlashAir-Roulette
|
0218a478a4f3eb42deb8b66025d5e8c9bbf1c44b
|
[
"BSD-2-Clause"
] | null | null | null |
LUA/game1.lua
|
AoiSaya/FlashAir-Roulette
|
0218a478a4f3eb42deb8b66025d5e8c9bbf1c44b
|
[
"BSD-2-Clause"
] | null | null | null |
LUA/game1.lua
|
AoiSaya/FlashAir-Roulette
|
0218a478a4f3eb42deb8b66025d5e8c9bbf1c44b
|
[
"BSD-2-Clause"
] | null | null | null |
-----------------------------------------------
-- game1: Simple roulette for FlashAir Roulette
-- under the BSD-2-Clause, Copyright 2018 AoiSaya
-- 2018/08/02 rev.0.05
-----------------------------------------------
require "/LUA/libRoulette"
-- 定数
local SPEED_MAX = 100 --速度の上限。SPEED_STOP+SPEED_DEC*7より大きいこと
local SPEED_INC = 20 --増速時の幅
local SPEED_DEC = 1 --減速時の幅
local SPEED_STOP = 3 --この速度以下なら止める。SPEED_DECより大きいこと
--
local number = 0 -- LEDの番号
local speed = 0 -- ルーレットのスピード
local step = 1 -- ルーレットのステップ
local i = 0
local Abutton, Bbutton
-- GPIOが使えないときは終了
if readyGpio()==false then
return
end
-- A,Bボタンが離されるまで待つ --
repeat
sleep(100)
Abutton,Bbutton = light(number)
until Abutton==0 and Bbutton==0
-- メインの処理 --
while noBreak() do -- FTLE(FlashTools Lua Editor)のBreakで止められる
Abutton,Bbutton = light(number)
-- ルーレットの回し方をボタンで変える
if Bbutton==1 then step = 1 end
if Abutton==1 then step = 3 end -- 3ステップずつ回す
-- ボタンを押してると加速、離してると減速させる
if Abutton==1 or Bbutton==1 then
if speed<SPEED_MAX then
speed = speed + SPEED_INC
end
else
speed = speed - SPEED_DEC
end
if speed<SPEED_STOP then
-- 止まっているときの処理 --
-- 押し時間でズルができないように初期値をばらつかせる
if speed<-7 then speed=0 end
-- for i = 0,7 do light(i) end --全LEDを弱く光らせる
-- i = (i+1)%80; light((i-i%10)/10) --全LEDを順番に光らせる
-- light((number-1)%8); light((number+1)%8) --前後を弱く光らせる
light(number)
sleep(20)
collectgarbage()
else
-- 回っているときの処理 --
number = (number + step + 8) % 8
lightBuz(number,1) --軽く音を鳴らす
sleep(1)
lightBuz(number,2)
lightBuz(number,3)
sleepTime = 1000/speed
-- デバッグ中に間違って不正な値でsleepしないようにする保険
if sleepTime<0 then sleepTime=0 end
-- sleep時間で回る速さを表現する
sleep(sleepTime)
end
end
| 23.621622
| 61
| 0.64016
|
fe7ffdfad7fc1ecf2cbf4d10f1b034531642bd9e
| 15,601
|
swift
|
Swift
|
PeasNovel/Classes/Search/Controller/SearchViewController.swift
|
LieonShelly/PeasNovel
|
ba21ccb9e0446c4239171dcbd01c6882606be257
|
[
"MIT"
] | null | null | null |
PeasNovel/Classes/Search/Controller/SearchViewController.swift
|
LieonShelly/PeasNovel
|
ba21ccb9e0446c4239171dcbd01c6882606be257
|
[
"MIT"
] | null | null | null |
PeasNovel/Classes/Search/Controller/SearchViewController.swift
|
LieonShelly/PeasNovel
|
ba21ccb9e0446c4239171dcbd01c6882606be257
|
[
"MIT"
] | null | null | null |
//
// SearchViewController.swift
// PeasNovel
//
// Created by xinyue on 2019/4/16.
// Copyright © 2019 NotBroken. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import PKHUD
class SearchViewController: BaseViewController {
@IBOutlet weak var fuzzyTableView: UITableView!
@IBOutlet weak var tableViewTop: NSLayoutConstraint!
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var tableView: UITableView!
let searchAction: PublishSubject<String?> = .init()
let fuzzyInput: PublishSubject<String?> = .init()
let beginInput: PublishSubject<Void> = .init()
let hotItemSelected: PublishSubject<SearchHotModel> = .init()
let firstItemAction: PublishSubject<Int> = .init() // 第一个cell上按钮事件
let netSearchAction: PublishSubject<Void> = .init() // 第一个cell上按钮事件
let historyClearAction: PublishSubject<Void> = .init() // 清除历史记录
lazy var dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String?, Any>>(configureCell: {[unowned self] _, tv, ip, model in
if let model = model as? [SearchHotModel] {
let cell = tv.dequeueCell(SearchHotTableViewCell.self, for: ip)
cell.config(model)
cell.itemSelected
.bind(to: self.hotItemSelected)
.disposed(by: cell.bag)
cell.itemSelected
.map{ $0.title }
.bind(to: self.searchAction)
.disposed(by: cell.bag)
return cell
}
if let model = model as? BookInfo, ip.section == 0{
let cell = tv.dequeueCell(SearchFirstResultTableViewCell.self, for: ip)
cell.set(model)
cell.buttonAction
.bind(to: self.firstItemAction)
.disposed(by: cell.bag)
return cell
}
if let model = model as? BookInfo {
let cell = tv.dequeueCell(BookDetailCoverRightCell.self, for: ip)
cell.set(model)
return cell
}
if let model = model as? SearchWebSwitchModel {
let cell = tv.dequeueCell(SogouEnterTableViewCell.self, for: ip)
cell.selectionStyle = .none
cell.btm
.rx
.tap
.bind(to: self.netSearchAction)
.disposed(by: cell.bag)
return cell
}
if let item = model as? LocalTempAdConfig {
let cell = TableViewCellBannerService.chooseCell(item, tableView: tv, indexPath: ip)
return cell
}
if let model = model as? [SearchKeyModel] {
let cell = tv.dequeueCell(SearchHistoryTableViewCell.self, for: ip)
cell.set(model)
cell.tagTapped
.bind(to: self.searchAction)
.disposed(by: cell.bag)
return cell
}
return UITableViewCell()
})
convenience init(_ viewModel: SearchViewModel) {
self.init(nibName: "SearchViewController", bundle: nil)
self.rx
.viewDidLoad
.subscribe(onNext: { [unowned self] in
self.configUI()
self.config(viewModel)
})
.disposed(by: bag)
self.rx
.viewDidLoad
.bind(to: viewModel.viewDidLoad)
.disposed(by: bag)
self.rx
.viewWillAppear
.bind(to: viewModel.viewWillAppear)
.disposed(by: bag)
self.rx
.viewWillDisappear
.bind(to: viewModel.viewWillDisappear)
.disposed(by: bag)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
func config(_ viewModel: SearchViewModel) {
tableViewTop.constant = UIApplication.shared.statusBarFrame.height + ( navigationController?.navigationBar.frame.height ?? 44)
searchAction
.bind(to: viewModel.searchAction)
.disposed(by: bag)
beginInput
.bind(to: viewModel.textFieldActive)
.disposed(by: bag)
historyClearAction
.bind(to: viewModel.historyClearAction)
.disposed(by: bag)
tableView
.rx
.modelSelected(Any.self)
.bind(to: viewModel.itemDidSelected)
.disposed(by: bag)
tableView
.mj_footer
.rx
.start
.bind(to: viewModel.footerRefresh)
.disposed(by: bag)
firstItemAction
.bind(to: viewModel.firstItemAction)
.disposed(by: bag)
netSearchAction
.bind(to: viewModel.sogouSearchAction)
.disposed(by: bag)
hotItemSelected
.bind(to: viewModel.hotItemSelected)
.disposed(by: bag)
viewModel
.searchText
.drive(self.searchField.rx.text)
.disposed(by: bag)
viewModel
.defaultKeyword
.subscribe(onNext: { [unowned self] in
self.searchField.placeholder = $0
})
.disposed(by: bag)
viewModel
.sections
.drive(self.tableView.rx.items(dataSource: self.dataSource))
.disposed(by: bag)
viewModel
.itemOutput
.subscribe(onNext: {
BookReaderHandler.jump($0.book_id, contentId: $0.content_id)
})
.disposed(by: bag)
viewModel
.endMoreDaraRefresh
.drive(tableView.mj_footer.rx.endNoMoreData)
.disposed(by: bag)
viewModel
.catalogViewModel
.subscribe(onNext: { [unowned self] in
let vc = BookCatalogController($0)
self.navigationController?.pushViewController(vc, animated: true)
})
.disposed(by: bag)
viewModel
.webViewModel
.subscribe(onNext: { [weak self] in
guard let weakSelf = self else {
return
}
let vc = WebViewController($0)
weakSelf.navigationController?.pushViewController(vc, animated: true)
})
.disposed(by: bag)
viewModel.sogouViewModel
.subscribe(onNext: { [weak self] in
guard let weakSelf = self else {
return
}
let vc = SogouWebViewController($0)
weakSelf.navigationController?.pushViewController(vc, animated: true)
})
.disposed(by: bag)
viewModel
.activityDriver
.drive(HUD.loading)
.disposed(by: bag)
viewModel
.errorDriver
.drive(HUD.flash)
.disposed(by: bag)
viewModel
.tipHud
.drive(HUD.flash)
.disposed(by: bag)
NotificationCenter.default.rx.notification(UITextField.textDidChangeNotification, object: searchField)
.subscribe(onNext: { [weak self](note) in
if let textField = note.object as? UITextField, let text = textField.text {
self?.fuzzyInput.onNext(text)
}
})
.disposed(by: bag)
let textField = self.searchField
viewModel.fuzzyResults
.asObservable()
.bind(to: fuzzyTableView.rx.items(cellIdentifier: String(describing: FuzzyTableViewCell.self), cellType: FuzzyTableViewCell.self)) { (row, element, cell) in
cell.config(element.book_title ?? "", keyword: textField?.text ?? "")
}
.disposed(by: bag)
fuzzyTableView.rx.modelSelected(BookInfo.self)
.map { $0.book_title }
.unwrap()
.bind(to: searchAction)
.disposed(by: bag)
fuzzyInput.asObservable()
.unwrap()
.bind(to: viewModel.fuzzyInput)
.disposed(by: bag)
viewModel.fuzzyResults
.asObservable()
.map { $0.isEmpty }
.bind(to: fuzzyTableView.rx.isHidden)
.disposed(by: bag)
viewModel.fuzzyResults
.asObservable()
.map { !$0.isEmpty }
.bind(to: tableView.rx.isHidden)
.disposed(by: bag)
loadAd(viewModel)
}
func loadAd(_ viewModel: SearchViewModel) {
viewModel.bannerOutput
.subscribeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] (config) in
self?.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
guard let weakSelf = self else {
return
}
let topBanner = weakSelf.setupBottombannr(config.localConfig)
ViewBannerSerVice.configData(config, bannerView: topBanner)
})
.disposed(by: bag)
viewModel
.bannerConfigoutput
.asObservable()
.unwrap()
.filter { !$0.is_close}
.filter { $0.ad_type == AdvertiseType.GDT.rawValue }
.subscribe(onNext: { [weak self](config) in
guard let weakSelf = self else {
return
}
let gdtViewModel = GDTBannerViewModel(config, viewController: weakSelf)
gdtViewModel.nativeAdOutput
.asObservable()
.map { LocalTempAdConfig(config, adType: .GDT($0))}
.bind(to: viewModel.bannerOutput)
.disposed(by: viewModel.bag)
viewModel.bannerViewModel = gdtViewModel
})
.disposed(by: bag)
viewModel
.bannerConfigoutput
.asObservable()
.unwrap()
.filter { !$0.is_close}
.filter { $0.ad_type == AdvertiseType.todayHeadeline.rawValue }
.subscribe(onNext: { [weak self](config) in
guard let weakSelf = self else {
return
}
let buViewModel = BUNativeBannerViewModel(config, viewController: weakSelf)
buViewModel.nativeAdOutput
.asObservable()
.map { LocalTempAdConfig(config, adType: .todayHeadeline($0))}
.bind(to: viewModel.bannerOutput)
.disposed(by: viewModel.bag)
viewModel.bannerViewModel = buViewModel
})
.disposed(by: bag)
}
func configUI() {
searchField.delegate = self
tableView.estimatedRowHeight = 100
tableView.delegate = self
fuzzyTableView.delegate = self
tableView.registerNibWithCell(SearchHotTableViewCell.self)
tableView.registerNibWithCell(SearchFirstResultTableViewCell.self)
tableView.registerNibWithCell(SearchEmptyWithNetPageTableViewCell.self)
tableView.registerNibWithCell(BookDetailCoverRightCell.self)
tableView.registerNibWithCell(SearchHistoryTableViewCell.self)
tableView.registerNibWithHeaderFooterView(SearchHeaderView.self)
tableView.registerNibWithCell(IMBannerTableViewCell.self)
fuzzyTableView.registerNibWithCell(FuzzyTableViewCell.self)
tableView.registerNibWithCell(SogouEnterTableViewCell.self)
tableView.mj_footer = RefreshFooter()
}
fileprivate func setupBottombannr(_ config: LocalAdvertise) -> UIView? {
guard let topBanner = ViewBannerSerVice.chooseBanner(config, bannerFrame: CGRect(x: 0, y: UIScreen.main.bounds.height - 75 - UIDevice.current.safeAreaInsets.bottom, width: UIScreen.main.bounds.width , height: 75 + UIDevice.current.safeAreaInsets.bottom)) else {
return nil
}
for subView in tableView.tableHeaderView?.subviews ?? [] {
subView.removeFromSuperview()
}
let header = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 75))
header.addSubview(topBanner)
tableView.tableHeaderView = header
topBanner.snp.makeConstraints {
$0.edges.equalTo(0)
}
return topBanner
}
@IBAction func cancelAction(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
deinit {
print("SearchViewController deinit!!!")
}
}
extension SearchViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchAction
.on(.next(textField.text))
fuzzyInput.onNext("")
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
beginInput.on(.next(()))
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if tableView == self.tableView {
if let _ = dataSource.sectionModels[section].model {
return 36
}else{
return 0.001
}
}
return 0.001
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if tableView == self.tableView {
return 5
}
return 0.001
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if tableView == self.tableView {
let header = tableView.dequeueHeaderFooterView(SearchHeaderView.self)
if let title = dataSource.sectionModels[section].model {
header.titleLabel.isHidden = title == "网页搜索"
header.titleLabel.text = title
header.clearButton.isHidden = (title != "历史搜索")
header.clearButton
.rx
.tap
.bind(to: historyClearAction)
.disposed(by: bag)
return header
}else{
return nil
}
}
return nil
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if tableView == self.tableView {
let footer = UIView()
footer.backgroundColor = UIColor(0xF4F6F9)
return footer
}
return nil
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == self.tableView {
if indexPath.section >= dataSource.sectionModels.count {
return 0
}
let item = dataSource.sectionModels[indexPath.section].items[indexPath.row]
if let _ = item as? SearchWebSwitchModel {
return 44
}
return UITableView.automaticDimension
}
return 44
}
}
| 34.137856
| 272
| 0.554964
|
e7582ddb977fc9be213e12fe5b343d16317c6b1e
| 1,743
|
php
|
PHP
|
resources/views/files/edit.blade.php
|
guizoxxv/openpad-laravel
|
e067a7a01196063a4848ea40586b5e05d7c05de7
|
[
"MIT"
] | null | null | null |
resources/views/files/edit.blade.php
|
guizoxxv/openpad-laravel
|
e067a7a01196063a4848ea40586b5e05d7c05de7
|
[
"MIT"
] | null | null | null |
resources/views/files/edit.blade.php
|
guizoxxv/openpad-laravel
|
e067a7a01196063a4848ea40586b5e05d7c05de7
|
[
"MIT"
] | null | null | null |
@extends('layouts/master')
@section('page_style')
<style>
main {
padding: 0;
}
/*footer {
padding-top: 30px;
}*/
</style>
@endsection
@section('inner_header')
<div class="inner-header">
<h2>Name: {{ $file->name }}</h2>
<div class="break"></div>
<ul class="tools-wrapper">
<li>
<a href="{{ route('raw', [$file->name]) }}"><i class="fa fa-eye" aria-hidden="true"><span>Raw</span></i></a>
</li>
<li>
<a href="{{ route('load', [$file->name]) }}"><i class="fa fa-file" aria-hidden="true"><span>File</span></i></a>
</li>
<li>
<a class="copy-btn" href="#" data-clipboard-target=".copy-text-target"><i class="fa fa-clipboard" aria-hidden="true"><span>Copy</span></i></a>
</li>
<li>
<a href="#" data-remodal-target="modal-change-password"><i class="fa fa-lock" aria-hidden="true"><span>Password</span></i></a>
</li>
<li>
<a class="delete-btn" href="#" data-remodal-target="modal-delete"><i class="fa fa-trash" aria-hidden="true"><span>Delete</span></i></a>
</li>
</ul>
</div>
@endsection
@section('main_content')
<form class="edit-form flex-center" method="post" action="">
{{ csrf_field() }}
<i class="more-less-btn fa fa-plus-square fa-3x" aria-hidden="true" title="Show more"></i>
<textarea class="text-input copy-text-target" name="text">{{ $file->text }}</textarea>
<input class="update-name-input" type="hidden" name="name" value="{{ $file->name }}">
<div class="status-wrapper edit-status-wrapper" style="display:none"></div>
</form>
@endsection
@section('modals')
@include('modals/change_password')
@include('modals/delete')
@endsection
| 23.24
| 150
| 0.577166
|
258ee69e3da71f89cef5d8f6c4cd552876627090
| 5,706
|
html
|
HTML
|
en/index.html
|
CardozaAbril/cardozaAbril.github.io
|
e4897d067db04a9c144da8af9cb4248c970361fa
|
[
"MIT"
] | null | null | null |
en/index.html
|
CardozaAbril/cardozaAbril.github.io
|
e4897d067db04a9c144da8af9cb4248c970361fa
|
[
"MIT"
] | null | null | null |
en/index.html
|
CardozaAbril/cardozaAbril.github.io
|
e4897d067db04a9c144da8af9cb4248c970361fa
|
[
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns#" lang="en">
<head>
<meta charset="UTF-8">
<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/">
<title>Charlotte</title>
<meta name="DC.title" content="Charlotte">
<meta name="DC.description" content="">
<meta name="description" content="">
<!-- OPENGRAPH -->
<meta property="og:title" content="Charlotte">
<meta name="fb:app_id" content="1668638246711351">
<meta content="website" property="og:type">
<meta property="og:description" content="">
<meta content="http://localhost:4000/en/" property="og:url">
<meta content="http://localhost:4000/pt/#scrollto-section-2/" property="article:author">
<meta content="http://localhost:4000/assets/img/icon-1000.png" property="og:image">
<meta name="DC.language" scheme="ISO639-1" content="pt-br">
<link rel="stylesheet" href="/assets/css/normalize.css">
<link rel="stylesheet" href="/assets/css/section-scroll.css">
<link rel="stylesheet" href="/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="/assets/css/labrador.css">
<script src="/assets/js/jquery-2.2.3.min.js" ></script>
<script src="/assets/js/jquery.stellar.min.js" ></script>
<script src="/assets/js/jquery.section-scroll.js" ></script>
<script src="/assets/js/labrador.js" ></script>
<meta name="msapplication-TileImage" content="/assets/img/icon-144.png">
<link rel="apple-touch-icon" href="/assets/img/icon-152.png">
<link rel="icon" type="image/png" href="/assets/img/icon.png" />
<link rel="canonical" href="http://localhost:4000/en/">
<meta http-equiv="content-language" content="pt-br">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<header class="profile-photo scrollable-section" data-stellar-background-ratio="0.5" data-section-title="Me">
<div class="photo"></div>
<div class="my-name">
<h1>Labrador</h1>
<h3>Loyal friend</h3>
</div>
<ul class="language">
<li class=""><a href="http://localhost:4000/pt" title="mudar para Português">pt</a></li>
<li class="ativo"><a href="http://localhost:4000/en" title="change to English">en</a></li>
</ul>
<div class="responsive-menu">
<a href="#" class="fa fa-bars btn-responsive-menu"></a>
<div class="menu">
<img src="http://localhost:4000/assets/img/logo.png" class="logo" />
<ul>
<li><span>Linguagens </span>
<ul class="language">
<li class=""><a href="http://localhost:4000/pt" title="mudar para Português">pt</a></li>
<li class="ativo"><a href="http://localhost:4000/en" title="change to English">en</a></li>
</ul>
</li>
<li><a href="#scrollto-section-1">Me</a></li>
<li><a href="#scrollto-section-2">About</a></li>
<li><a href="#scrollto-section-3">Quote</a></li>
<li><a href="#scrollto-section-4"></a></li>
</ul>
</div>
</div>
<div class="gradiente">
<div class="scroll-down">
<span>Scroll down</span>
</div>
</div>
</header>
<section class="profile-about scrollable-section" data-stellar-background-ratio="0.5" data-section-title="About">
<div class="text-about">
<h4>About</h4>
<p>My full name is Charlotte Donini, but my friends call me simply 'Lotte' :-). I am a <a href="https://pt.wikipedia.org/wiki/Labrador_retriever" title="Labrador in wiki" target="_blank"> female labrador retriever </a>. I live with my lovely family.</p>
<p>I am very playful with my large size I drop everything that crosses in my way.</p>
<p>I love eating and sleeping during the day, lie in the sun belly up is my preferred position.</p>
<p>Run and walk with my master are my favorite sports.</p>
</div>
<div class="social-links">
<h4>Social</h4>
<ul class="social">
<li><a class="fa fa-facebook-official" target="_blank" href="https://www.facebook.com/LabradorRetrieverDogs" title="@LabradorRetrieverDogs" taget="_blank"></a></li>
<li><a class="fa fa-youtube-play" target="_blank" href="https://www.youtube.com/results?search_query=labrador" title="@labrador" taget="_blank"></a></li>
<li><a class="fa fa-instagram" target="_blank" href="https://www.instagram.com/explore/tags/#labrador" title="@#labrador" taget="_blank"></a></li>
</ul>
</div>
</section>
<section class="profile-quote scrollable-section" data-stellar-background-ratio="0.5" data-section-title="Quote">
<div class="overlay-quote outer-vertical ">
<div class="text-quote inner-vertical ">
<h4>Favorite quote</h4>
<p>" No matter that few are your possessions and your money. Having a dog makes you rich. "</p>
<div class="author-quote">Louis Sabin</div>
</div>
</div>
</section>
<footer>
<div class="copyright-text">
<p>Copyright © 2016 Rodrigo Donini. Made with ♥ and <a href='https://jekyllrb.com/' target='_blank'>Jekyll</a> fork on <a href='https://github.com/donini/personal-page' target='_blank'>Github</a>.</p>
</div>
</footer>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-76309509-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| 29.564767
| 255
| 0.628987
|
a5c8e958c555b6a04b88fb188067e1b591356879
| 2,897
|
swift
|
Swift
|
BucketList/Classes/Bucket.swift
|
benbahrenburg/BucketList
|
3c486a92b8150dd4f447b130e6f8b7c2fef4553f
|
[
"MIT"
] | 2
|
2017-03-05T13:47:09.000Z
|
2022-02-26T03:46:59.000Z
|
BucketList/Classes/Bucket.swift
|
benbahrenburg/BucketList
|
3c486a92b8150dd4f447b130e6f8b7c2fef4553f
|
[
"MIT"
] | null | null | null |
BucketList/Classes/Bucket.swift
|
benbahrenburg/BucketList
|
3c486a92b8150dd4f447b130e6f8b7c2fef4553f
|
[
"MIT"
] | null | null | null |
//
// BucketList - Just another cache provider with security built in
// Bucket.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2016 bencoding.com. All rights reserved.
//
/**
Protocol used by all Bucket Cache Providers that do not require secrets
*/
public protocol Bucket {
/**
Adds an AnyObject to secure cache provider
- Parameter secret: The password used to encrypt the object
- Parameter forKey: The cache key for the cached AnyObject
- Parameter object: The object to be cached
- Returns: True if the object was successfully added to cache
*/
@discardableResult func add(_ forKey: String, object: AnyObject) -> Bool
/**
Adds a UIImage to secure cache provider
- Parameter forKey: The cache key for the cached image
- Parameter image: The image to be cached
- Returns: True if the image was successfully added to cache
*/
@discardableResult func add(_ forKey: String, image: UIImage) throws -> Bool
/**
Adds Data to secure cache provider
- Parameter forKey: The cache key for the cached data
- Parameter data: The data to be cached
- Returns: True if the data was successfully added to cache
*/
@discardableResult func add(_ forKey: String, data: Data) throws -> Bool
/**
Returns AnyObject? (optional) for a provided key. Nil is returned if no cache value is found.
- Parameter forKey: The cache key for the cached AnyObject
- Returns: AnyObject? (optional) for the provided cache key
*/
func getObject(_ forKey: String) -> AnyObject?
/**
Returns Data? (optional) for a provided key. Nil is returned if no cache value is found.
- Parameter forKey: The cache key for the cached Data
- Returns: Data? (optional) for the provided cache key
*/
func getData(_ forKey: String) -> Data?
/**
Returns UIImage? (optional) for a provided key. Nil is returned if no cache value is found.
- Parameter forKey: The cache key for the cached UIImage
- Returns: UIImage? (optional) for the provided cache key
*/
func getImage(_ forKey: String) -> UIImage?
/**
Removes item from cached.
- Parameter forKey: The cache key for the cached UIImage
- Returns: True if the cached value is successfully removed
*/
@discardableResult func remove(_ forKey: String) throws -> Bool
/**
Removes all values from cache
- Parameter forKey: The cache key for the cached UIImage
- Returns: True if the all cached values is successfully removed
*/
@discardableResult func empty() -> Bool
/**
Returns True if a Cache key exists
- Parameter forKey: The key to check if a cached value exists
- Returns: True if a cached value exists
*/
func exists(_ forKey: String) -> Bool
}
| 34.903614
| 98
| 0.66448
|
4d54f50f6274485d0497eebafb1f99b02ffe88dd
| 3,938
|
cs
|
C#
|
Assets/A-STEROID/Scripts/NoCollider/NoColKaboom.cs
|
alelievr/TwoColorsGameJam
|
069d32c9cf2c13452434c2349a2da0f6408b462b
|
[
"MIT"
] | null | null | null |
Assets/A-STEROID/Scripts/NoCollider/NoColKaboom.cs
|
alelievr/TwoColorsGameJam
|
069d32c9cf2c13452434c2349a2da0f6408b462b
|
[
"MIT"
] | null | null | null |
Assets/A-STEROID/Scripts/NoCollider/NoColKaboom.cs
|
alelievr/TwoColorsGameJam
|
069d32c9cf2c13452434c2349a2da0f6408b462b
|
[
"MIT"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class NoColKaboom : MonoBehaviour
{
public float poid = 1;
[Range(0, 1)] public float resitimpact = 0;
public float life = 1000;
[HideInInspector] public Rigidbody2D rbody;
public float flickerCount = 4;
public float flickerInterval = 0.1f;
public GameObject invoqueondead;
new Renderer renderer;
public int debritCount = 2;
public GameObject debrit;
[Space]
public float recupTime;
public bool recup;
bool dead = false;
void Start ()
{
rbody = GetComponent<Rigidbody2D>();
renderer = GetComponentInChildren< Renderer >();
if (renderer == null)
renderer = GetComponent< Renderer >();
}
IEnumerator Destroyation()
{
yield return new WaitForSeconds(0.2f);
Destroy(gameObject);
}
void Die()
{
if (dead)
return ;
dead = true;
GameObject.Instantiate(invoqueondead, transform.position, Quaternion.identity);
for (int i = 0; i < debritCount; i++)
NoColDebrisPool.instance.NewDebris(transform.position);
if (tag == "boss")
GameManager.instance.DefeatBoss();
StartCoroutine(Destroyation());
}
float invudegat = 0.2f;
IEnumerator Flicker()
{
for (int i = 0; i < flickerCount; i++)
{
renderer.enabled = false;
yield return new WaitForSeconds(flickerInterval);
renderer.enabled = true;
yield return new WaitForSeconds(flickerInterval);
}
}
IEnumerator Recup()
{
recup = true;
yield return new WaitForSeconds(recupTime);
recup = false;
}
IEnumerator HitSound()
{
// AudioController.instance.PlayDamageAtPosition(transform.position);
yield return new WaitForSeconds(0.2f);
// AudioController.instance.PlayDamageAtPosition(transform.position);
yield return new WaitForSeconds(0.2f);
// AudioController.instance.PlayDamageAtPosition(transform.position);
}
void ToDoOnCol(GameObject collided)
{
// NoColKaboom impactant = collided.GetComponent<NoColKaboom>();
if ((!recup)/* && (impactant != null)*/)
{
// Vector2 realvelocity = impactant.rbody.velocity - rbody.velocity;
if (collided.tag == "Player")//lol
{
Debug.Log("PLAYER COLLIDED KABOOM");
StartCoroutine(Flicker());
StartCoroutine(Recup());
StartCoroutine(HitSound());
Die();
}
if (collided.tag == "boss")
rbody.velocity += (Vector2)(collided.transform.position - transform.position).normalized * 2000;
}
}
// void OnCollisionEnter2D(Collision2D other)
// {
// Kaboom impactant = other.gameObject.GetComponent<Kaboom>();
// if ((!recup) && (impactant != null))
// {
// Vector2 realvelocity = impactant.rbody.velocity - rbody.velocity;
// if ((resitimpact < 0.5f || other.gameObject.tag == "Player") && invudegat < 0) //lol
// {
// StartCoroutine(Flicker());
// StartCoroutine(Recup());
// StartCoroutine(HitSound());
// life -= Mathf.Clamp(realvelocity.magnitude, 0, 30);
// invudegat = 0.2f;
// }
// if (life < 0 && !dead)
// Die();
// if (other.gameObject.tag == "boss")
// rbody.velocity += (Vector2)(other.transform.position - transform.position).normalized * 2000;
// }
// }
private void FixedUpdate()
{
if (tag == "Proj" || tag == "Xenon")
{
if ((transform.position - GameManager.instance.playerPos).sqrMagnitude < GameManager.instance.playerSizeSqr + 10f)
{
GameObject tmp;
// Debug.Log("KABOOM dist to asteroid = " + (transform.position - NoColDebrisManager.instance.transform.position).magnitude);
Debug.DrawLine(transform.position, NoColDebrisManager.instance.transform.position, Color.red, Time.fixedDeltaTime);
if ((tmp = NoColDebrisManager.instance.DebritCollisionCheck(transform.position)) != null)
ToDoOnCol(tmp);
// else
// Debug.Log("DEBRIT NULL");
}
}
}
private void Update()
{
if (invudegat >= 0)
invudegat -= Time.deltaTime;
}
}
| 25.082803
| 128
| 0.676993
|
4651d3fbee09ef59323722f288875c1a1fd87d11
| 8,867
|
php
|
PHP
|
src/Controller/EigenRestfulController.php
|
alichry/laminas-authorization
|
243e8bc8c054f0e44fa792359c7b8d4d7c747e60
|
[
"MIT"
] | 1
|
2020-06-07T22:24:23.000Z
|
2020-06-07T22:24:23.000Z
|
src/Controller/EigenRestfulController.php
|
alichry/laminas-authorization
|
243e8bc8c054f0e44fa792359c7b8d4d7c747e60
|
[
"MIT"
] | 1
|
2020-08-25T21:17:36.000Z
|
2020-08-25T21:17:36.000Z
|
src/Controller/EigenRestfulController.php
|
alichry/laminas-authorization
|
243e8bc8c054f0e44fa792359c7b8d4d7c747e60
|
[
"MIT"
] | 1
|
2020-06-07T22:24:28.000Z
|
2020-06-07T22:24:28.000Z
|
<?php
/**
* Copyright (c) 2019, 2020 Ali Cherry
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace AliChry\Laminas\Authorization\Controller;
use AliChry\Laminas\AccessControl\AccessControlException;
use AliChry\Laminas\Authorization\AuthorizationException;
use AliChry\Laminas\Authorization\AuthorizationService;
use Laminas\Mvc\Exception\RuntimeException;
use Laminas\Mvc\Controller\AbstractRestfulController;
use Laminas\Mvc\MvcEvent;
use Laminas\Stdlib\ResponseInterface as Response;
use Laminas\Mvc\Exception\DomainException;
class EigenRestfulController extends AbstractRestfulController
{
/**
* @var AuthorizationService
*/
protected $authorizationService;
public function __construct(AuthorizationService $authService)
{
$this->authorizationService = $authService;
}
/**
* @param $action
* @return Response|null
* @throws AccessControlException
* @throws AuthorizationException
*/
private function __check($action)
{
return $this->authorizationService->getMvcResult(
$this->authorizationService->isAuthorized(
get_class($this),
$action
)
);
}
/**
* Handle the request
*
* @todo try-catch in "patch" for patchList should be removed in the future
* @param MvcEvent $e
* @return mixed
* @throws DomainException if no route matches in event or invalid HTTP method
* @throws AuthorizationException
* @throws AccessControlException
*/
public function onDispatch(MvcEvent $e)
{
$routeMatch = $e->getRouteMatch();
if (! $routeMatch) {
/**
* @todo Determine requirements for when route match is missing.
* Potentially allow pulling directly from request metadata?
*/
throw new DomainException('Missing route matches; unsure how to retrieve action');
}
$request = $e->getRequest();
// Was an "action" requested?
$action = $routeMatch->getParam('action', false);
if ($action) {
// Handle arbitrary methods, ending in Action
$method = static::getMethodFromAction($action);
if (! method_exists($this, $method)) {
$method = 'notFoundAction';
}
// * AuthorizationService now checks all controllers that have
// * the action param set, so the below is redundant. We'll keep it
// * for a bit.
$return = $this->__check($method);
if (! $return) {
$return = $this->$method();
}
$e->setResult($return);
return $return;
}
// RESTful methods
$method = strtolower($request->getMethod());
switch ($method) {
// Custom HTTP methods (or custom overrides for standard methods)
case (isset($this->customHttpMethodsMap[$method])):
$callable = $this->customHttpMethodsMap[$method];
$action = $method;
if ($return = $this->__check($action)) {
break;
}
$return = call_user_func($callable, $e);
break;
// DELETE
case 'delete':
$id = $this->getIdentifier($routeMatch, $request);
if ($id !== false) {
$action = 'delete';
if ($return = $this->__check($action)) {
break;
}
$return = $this->delete($id);
break;
}
$data = $this->processBodyContent($request);
$action = 'deleteList';
if ($return = $this->__check($action)) {
break;
}
$return = $this->deleteList($data);
break;
// GET
case 'get':
$id = $this->getIdentifier($routeMatch, $request);
if ($id !== false) {
$action = 'get';
if ($return = $this->__check($action)) {
break;
}
$return = $this->get($id);
break;
}
$action = 'getList';
if ($return = $this->__check($action)) {
break;
}
$return = $this->getList();
break;
// HEAD
case 'head':
$id = $this->getIdentifier($routeMatch, $request);
if ($id === false) {
$id = null;
}
$action = 'head';
if ($return = $this->__check($action)) {
break;
}
$headResult = $this->head($id);
$response = ($headResult instanceof Response) ? clone $headResult : $e->getResponse();
$response->setContent('');
$return = $response;
break;
// OPTIONS
case 'options':
$action = 'options';
if ($return = $this->__check($action)) {
break;
}
$this->options();
$return = $e->getResponse();
break;
// PATCH
case 'patch':
$id = $this->getIdentifier($routeMatch, $request);
$data = $this->processBodyContent($request);
if ($id !== false) {
$action = 'patch';
if ($return = $this->__check($action)) {
break;
}
$return = $this->patch($id, $data);
break;
}
// TODO: This try-catch should be removed in the future, but it
// will create a BC break for pre-2.2.0 apps that expect a 405
// instead of going to patchList
try {
$action = 'patchList';
if ($return = $this->__check($action)) {
break;
}
$return = $this->patchList($data);
} catch (RuntimeException $ex) {
$response = $e->getResponse();
$response->setStatusCode(405);
return $response;
}
break;
// POST
case 'post':
$action = 'create';
if ($return = $this->__check($action)) {
break;
}
$return = $this->processPostData($request);
break;
// PUT
case 'put':
$id = $this->getIdentifier($routeMatch, $request);
$data = $this->processBodyContent($request);
if ($id !== false) {
$action = 'update';
if ($return = $this->__check($action)) {
break;
}
$return = $this->update($id, $data);
break;
}
$action = 'replaceList';
if ($return = $this->__check($action)) {
break;
}
$return = $this->replaceList($data);
break;
// All others...
default:
$response = $e->getResponse();
$response->setStatusCode(405);
return $response;
}
$routeMatch->setParam('action', $action);
$e->setResult($return);
return $return;
}
}
| 35.754032
| 102
| 0.493177
|
eab51a1f1ec3d62d503f1bf536a25068ecbea497
| 765
|
rb
|
Ruby
|
app/models/ecm/videos/category.rb
|
robotex82/ecm_videos
|
3dba9a26915e2da7802b3390f9a9992e6ce28f49
|
[
"MIT"
] | null | null | null |
app/models/ecm/videos/category.rb
|
robotex82/ecm_videos
|
3dba9a26915e2da7802b3390f9a9992e6ce28f49
|
[
"MIT"
] | null | null | null |
app/models/ecm/videos/category.rb
|
robotex82/ecm_videos
|
3dba9a26915e2da7802b3390f9a9992e6ce28f49
|
[
"MIT"
] | null | null | null |
module Ecm::Videos
class Category < ActiveRecord::Base
# markup support
include Models::MarkupConcern
markup :description
# acts as published
include ActsAsPublished::ActiveRecord
acts_as_published
has_many :videos, -> { order(position: :asc) }
validates :locale, :name, :markup_language, presence: true
after_initialize :set_defaults, if: :new_record?
def preview_image
videos.first.try(:preview_image)
end
def published_preview_image_url(style)
return unless video = videos.published.first
video.clip.url(style)
end
def videos_count
videos.count
end
private
def set_defaults
self.markup_language = Configuration.default_markup_language
end
end
end
| 20.675676
| 66
| 0.699346
|
4bc1e6759c8d98c029117d62ac6f2350ac813ee5
| 1,413
|
h
|
C
|
head/contrib/gcc/cfglayout.h
|
dplbsd/soc2013
|
c134f5e2a5725af122c94005c5b1af3720706ce3
|
[
"BSD-2-Clause"
] | 105
|
2015-03-02T16:58:34.000Z
|
2022-03-28T07:17:49.000Z
|
head/contrib/gcc/cfglayout.h
|
dplbsd/soc2013
|
c134f5e2a5725af122c94005c5b1af3720706ce3
|
[
"BSD-2-Clause"
] | 145
|
2015-03-18T10:08:17.000Z
|
2022-03-31T01:27:08.000Z
|
head/contrib/gcc/cfglayout.h
|
dplbsd/soc2013
|
c134f5e2a5725af122c94005c5b1af3720706ce3
|
[
"BSD-2-Clause"
] | 26
|
2015-10-10T09:37:44.000Z
|
2022-02-23T02:02:05.000Z
|
/* Basic block reordering routines for the GNU compiler.
Copyright (C) 2000, 2003, 2004 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#ifndef GCC_CFGLAYOUT_H
#define GCC_CFGLAYOUT_H
#include "basic-block.h"
extern rtx cfg_layout_function_footer;
extern void cfg_layout_initialize (unsigned int);
extern void cfg_layout_finalize (void);
extern unsigned int insn_locators_initialize (void);
extern void reemit_insn_block_notes (void);
extern bool can_copy_bbs_p (basic_block *, unsigned);
extern void copy_bbs (basic_block *, unsigned, basic_block *,
edge *, unsigned, edge *, struct loop *,
basic_block);
extern rtx duplicate_insn_chain (rtx, rtx);
#endif /* GCC_CFGLAYOUT_H */
| 36.230769
| 70
| 0.755131
|
20af3cfb4b122e7f72252b47065dc066c210f2d5
| 873
|
py
|
Python
|
src/fluent-python/metaprogramming/frozenjson.py
|
sudeep0901/python
|
7a50af12e72d21ca4cad7f2afa4c6f929552043f
|
[
"MIT"
] | null | null | null |
src/fluent-python/metaprogramming/frozenjson.py
|
sudeep0901/python
|
7a50af12e72d21ca4cad7f2afa4c6f929552043f
|
[
"MIT"
] | 3
|
2019-12-26T05:13:55.000Z
|
2020-03-07T06:59:56.000Z
|
src/fluent-python/metaprogramming/frozenjson.py
|
sudeep0901/python
|
7a50af12e72d21ca4cad7f2afa4c6f929552043f
|
[
"MIT"
] | null | null | null |
from collections import abc
import keyword
# create attribute to object
class FrozenJSON:
"""A read-only façade for navigating a JSON-like object
using attribute notation
"""
def __init__(self, mapping):
# self.__data = dict(mapping)
self.__data = {}
for key, value in mapping.items():
if keyword.iskeyword(key):
key += '_'
self.__data[key] = value
def __getattr__(self, name):
if hasattr(self.__data, name):
return getattr(self.__data, name)
else:
return FrozenJSON.build(self.__data[name])
@classmethod
def build(cls, obj):
if isinstance(obj, abc.Mapping):
return cls(obj)
elif isinstance(obj, abc.MutableSequence):
return [cls.build(item) for item in obj]
else:
return obj
| 26.454545
| 59
| 0.586483
|
2e05093dce886787e97685f39132e57aeaeef9f3
| 1,838
|
lua
|
Lua
|
.config/nvim/lua/core/plug.lua
|
rwxmad/dotfiles
|
f915c40889b72b69744f496bf6ccf58fb2e1105a
|
[
"MIT"
] | null | null | null |
.config/nvim/lua/core/plug.lua
|
rwxmad/dotfiles
|
f915c40889b72b69744f496bf6ccf58fb2e1105a
|
[
"MIT"
] | null | null | null |
.config/nvim/lua/core/plug.lua
|
rwxmad/dotfiles
|
f915c40889b72b69744f496bf6ccf58fb2e1105a
|
[
"MIT"
] | null | null | null |
return require('packer').startup(
function(use)
use 'wbthomason/packer.nvim'
use 'kyazdani42/nvim-web-devicons'
use {'kyazdani42/nvim-tree.lua',
requires = 'nvim-web-devicons',
config = function() require('nvim-tree').setup {} end
}
use 'ggandor/lightspeed.nvim'
use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }
use 'nvim-treesitter/nvim-treesitter-refactor'
use { 'hoob3rt/lualine.nvim', commit = '82f68c42df9d11e52edb52c86113d0eba5be798d'}
use {'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons'}
use 'neovim/nvim-lspconfig'
--use 'glepnir/lspsaga.nvim'
use { 'tami5/lspsaga.nvim' }
use 'windwp/nvim-autopairs'
use 'ray-x/lsp_signature.nvim'
use 'hrsh7th/cmp-nvim-lsp'
use 'hrsh7th/cmp-buffer'
use 'hrsh7th/nvim-cmp'
use 'hrsh7th/cmp-path'
use 'hrsh7th/cmp-vsnip'
use 'hrsh7th/vim-vsnip'
use 'onsails/lspkind-nvim'
use 'tpope/vim-fugitive'
use 'lewis6991/gitsigns.nvim'
use {
'numToStr/Comment.nvim',
config = function()
require('Comment').setup()
end,
}
use 'nvim-lua/plenary.nvim'
use 'nvim-telescope/telescope.nvim'
use 'tpope/vim-surround'
use { 'fatih/vim-go', run = ':GoUpdateBinaries' }
use 'rust-lang/rust.vim'
use 'simrat39/rust-tools.nvim'
use { 'Saecki/crates.nvim', requires = { 'nvim-lua/plenary.nvim' } }
use 'windwp/nvim-ts-autotag'
use 'norcalli/nvim-colorizer.lua'
use 'jose-elias-alvarez/nvim-lsp-ts-utils'
use { 'iamcco/markdown-preview.nvim', run = 'cd app && yarn install' }
use 'ellisonleao/glow.nvim'
use 'gruvbox-community/gruvbox'
use 'folke/tokyonight.nvim'
use 'tiagovla/tokyodark.nvim'
use 'sainnhe/sonokai'
use 'andweeb/presence.nvim'
end)
| 24.837838
| 86
| 0.649075
|
151e6a1ba974667e7bf5d306440e1eb833481edb
| 116
|
swift
|
Swift
|
Sources/kubrick/MediaDevices/Clock.swift
|
krad/kubrick
|
41b1abcb79d58c9e70379bb314187c20ebabcf0f
|
[
"MIT"
] | 4
|
2019-06-06T14:07:40.000Z
|
2021-03-01T06:19:04.000Z
|
Sources/kubrick/MediaDevices/Clock.swift
|
krad/kubrick
|
41b1abcb79d58c9e70379bb314187c20ebabcf0f
|
[
"MIT"
] | null | null | null |
Sources/kubrick/MediaDevices/Clock.swift
|
krad/kubrick
|
41b1abcb79d58c9e70379bb314187c20ebabcf0f
|
[
"MIT"
] | null | null | null |
public protocol Clock { }
#if os(iOS) || os(macOS)
import AVFoundation
extension CMClock: Clock { }
#endif
| 16.571429
| 32
| 0.663793
|
0dd1d1c9d36a42b5dbcdf485375225def45e8b20
| 364
|
cs
|
C#
|
Masarin.IoT.Sensor/Messages/SensorStatusMessage.cs
|
iot-for-tillgenglighet/ingress-mqtt
|
756d1ee8f1ab80a56a46dd1a33451e4649decfc5
|
[
"Apache-2.0"
] | null | null | null |
Masarin.IoT.Sensor/Messages/SensorStatusMessage.cs
|
iot-for-tillgenglighet/ingress-mqtt
|
756d1ee8f1ab80a56a46dd1a33451e4649decfc5
|
[
"Apache-2.0"
] | null | null | null |
Masarin.IoT.Sensor/Messages/SensorStatusMessage.cs
|
iot-for-tillgenglighet/ingress-mqtt
|
756d1ee8f1ab80a56a46dd1a33451e4649decfc5
|
[
"Apache-2.0"
] | 1
|
2020-10-01T19:34:52.000Z
|
2020-10-01T19:34:52.000Z
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Masarin.IoT.Sensor.Messages
{
class SensorStatusMessage : IoTHubMessage
{
public double Volt { get; }
public SensorStatusMessage(IoTHubMessageOrigin origin, string timestamp, double volts) : base(origin, timestamp, "sensor.status")
{
Volt = volts;
}
}
}
| 21.411765
| 132
| 0.714286
|
856c57700c7101ae0ce5e7bb5ea93a7dc084f9ae
| 253
|
kts
|
Kotlin
|
kwicket-kotlinx-html/build.gradle.kts
|
ageery/kwicket
|
58b90cfa0474b452a622c21d7972034e6235db4f
|
[
"Apache-2.0"
] | 12
|
2017-09-18T08:36:51.000Z
|
2021-02-22T18:50:16.000Z
|
kwicket-kotlinx-html/build.gradle.kts
|
ageery/kwicket
|
58b90cfa0474b452a622c21d7972034e6235db4f
|
[
"Apache-2.0"
] | 2
|
2017-09-18T09:24:19.000Z
|
2020-03-30T19:16:34.000Z
|
kwicket-kotlinx-html/build.gradle.kts
|
ageery/kwicket
|
58b90cfa0474b452a622c21d7972034e6235db4f
|
[
"Apache-2.0"
] | null | null | null |
dependencies {
val kotlinxHtmlVersion = org.kwicket.gradle.Versions.kotlinxHtmlVersion
compile(project(":kwicket-core"))
compile(project(":kwicket-wicket-core"))
compileOnly("org.jetbrains.kotlinx:kotlinx-html-jvm:$kotlinxHtmlVersion")
}
| 42.166667
| 77
| 0.762846
|
e781bfd2e6105fa9c90300608914bdf0c60fa980
| 4,268
|
php
|
PHP
|
resources/views/admin/products/index.blade.php
|
anderfernandes/astral
|
18a55df759845045b0c410de9c697f2c45b4cd69
|
[
"MIT"
] | 1
|
2021-06-24T20:44:30.000Z
|
2021-06-24T20:44:30.000Z
|
resources/views/admin/products/index.blade.php
|
anderfernandes/astral
|
18a55df759845045b0c410de9c697f2c45b4cd69
|
[
"MIT"
] | 90
|
2019-06-12T14:51:51.000Z
|
2021-12-11T05:28:03.000Z
|
resources/views/admin/products/index.blade.php
|
anderfernandes/astral
|
18a55df759845045b0c410de9c697f2c45b4cd69
|
[
"MIT"
] | 1
|
2021-01-30T05:45:43.000Z
|
2021-01-30T05:45:43.000Z
|
@extends('layout.admin')
@section('title', 'Products')
@section('subtitle', 'Manage products')
@section('icon', 'box')
@section('content')
<form action="{{ route('admin.products.index') }}" class="ui form" method="GET">
<div class="four fields">
<div class="field">
<select name="product_name" class="ui search dropdown">
<option selected value="">All Products</option>
@foreach (App\Product::all()->sortBy('name') as $p)
<option value="{{ $p->id }}">{{ $p->name }}</option>
@endforeach
</select>
</div>
<div class="field">
<select name="product_type" class="ui search dropdown">
<option value="">All Product Types</option>
@foreach ($productTypes->sortBy('name') as $t)
<option value="{{ $t->id }}">{{ $t->name }}</option>
@endforeach
</select>
</div>
<div class="field">
<div class="ui labeled input">
<div class="ui basic label">$</div>
<input name="product_price" type="text" value="{{ isSet($request->product_price) ? $request->product_price : null }}" placeholder="Product Price">
</div>
</div>
<div class="field">
<button class="ui secondary button" type="submit"><i class="search icon"></i> Search</button>
</div>
</div>
</form>
@if (str_contains(Auth::user()->role->permissions['products'], "C"))
<div onclick="$('#add-product').modal('toggle')" class="ui secondary button">
<i class="ui icons">
<i class="box icon"></i>
<i class="inverted corner add icon"></i>
</i>
Add Product
</div>
<br><br>
@endif
<div class="ui two column doubling stackable grid">
@foreach ($products as $product)
<div class="column">
<div class="ui items">
<div class="item">
<div class="image">
<img src="{{ $product->cover }}">
@if (str_contains(Auth::user()->role->permissions['products'], "U"))
<a href="{{ route('admin.products.edit', $product) }}" class="ui yellow right corner label"><i class="edit icon"></i></a>
@endif
</div>
<div class="content">
<a class="header">{{ $product->name }}</a>
<div class="extra">
<div class="ui green tag label" style="margin-right:0">$ {{ number_format($product->price, 2, '.', ',')}}</div>
<div class="ui black label" style="margin-right:0">{{ $product->type->name }}</div>
@if ($product->inventory)
<div class="ui {{ $product->stock < 10 ? 'red' : 'black' }} label" {!! $product->stock < 10 ? "data-tooltip='Only $product->stock in stock!' data-inverted=''" : ""!!} style="margin-right:0">
<i class="box icon"></i>
<div class="detail">{{ $product->stock }}</div>
</div>
@endif
@if ($product->creator_id != 1)
<div class="ui black label" style="margin-right:0">
<i class="user circle icon"></i>
<div class="detail">{{ $product->creator->fullname }}</div>
</div>
@endif
<div class="ui basic {{ $product->active ? "green" : "red" }} label">
{{ $product->active ? "active" : "inactive" }}
</div>
@if ($product->public)
<i class="globe icon" style="color: black !important"></i>
@endif
<p><i class="pencil icon"></i>{{ $product->created_at->format('l, F j, Y \a\t g:i A') }}</p>
<p><i class="edit icon"></i>{{ Date::parse($product->updated_at)->format('l, F j, Y \a\t g:i A') }}</p>
</div>
<div class="meta">
<p><i class="info circle icon"></i> {{ $product->description }}</p>
</div>
</div>
</div>
</div>
</div>
<?php $product = null ?>
@endforeach
</div>
@include('admin.products._create')
<div class="ui centered grid">
{{ $products->appends(app('request')->input())->links('vendor.pagination.semantic-ui') }}
</div>
<script>
@if ($request->product_name)
$('[name="product_name"]').dropdown('set selected', {{ $request->product_name }})
@endif
@if ($request->product_type)
$('[name="product_type"]').dropdown('set selected', {{ $request->product_type }})
@endif
</script>
@endsection
| 36.793103
| 204
| 0.544283
|
46b98d5f30e54c180de60504f01ab2e2c03f5b69
| 3,996
|
py
|
Python
|
picard/file.py
|
thejohnfreeman/picard
|
09b39d6655e1df071ea9f3f63eaf35ddbd2f0e0f
|
[
"MIT"
] | 3
|
2018-12-28T03:14:49.000Z
|
2019-05-24T21:05:13.000Z
|
picard/file.py
|
thejohnfreeman/picard
|
09b39d6655e1df071ea9f3f63eaf35ddbd2f0e0f
|
[
"MIT"
] | null | null | null |
picard/file.py
|
thejohnfreeman/picard
|
09b39d6655e1df071ea9f3f63eaf35ddbd2f0e0f
|
[
"MIT"
] | null | null | null |
"""Make-style file (and directory) targets."""
import os
from pathlib import Path
import typing as t
from picard.context import Context
from picard.typing import Target
FileLike = t.Union[str, os.PathLike]
FileTargetLike = t.Union[Target, FileLike]
# Need a way to type *args and **kwargs without ignoring the known parameters.
Recipe = t.Callable[
[Target, Context, t.Any],
t.Awaitable[t.Union[None, Path]],
]
def is_file_like(value):
# For now, ``isinstance`` does not play well with ``typing.Union``.
# https://stackoverflow.com/a/45959000/618906
return isinstance(value, (str, os.PathLike))
class FileRecipePostConditionError(Exception):
"""Raised when a file recipe fails to update its target."""
class FileTarget(Target):
"""A file that must be newer than its prerequisite files."""
def __init__(
self, path: Path, recipe: Recipe, *prereqs: FileTargetLike,
) -> None:
self.path = path
self.prereqs = [file_target(p) for p in prereqs]
self._recipe = recipe
@property
def name(self) -> str: # type: ignore
return str(self.path)
async def recipe(self, context: Context) -> Path:
"""Conditionally rebuild this file.
The conditions are (1) if this file does not exist or (2) if its
prerequisites have changed since it was last touched.
"""
# TODO: Memoize value.
# There is no way around evaluating all of the prerequisites. Either
# (1) some have changed but we must feed them all to the recipe or (2)
# we must check all of them to make sure none have changed.
from picard.api import sync # pylint: disable=cyclic-import
prereqs = await sync(self.prereqs)
if not await self._is_up_to_date(context, prereqs):
context.log.info(f'start: {self.name}')
value = await self._recipe(self, context, *prereqs)
if value is not None and value != self.path:
context.log.warning(
f'discarding value returned by {self._recipe}: {value}')
if not await self._is_up_to_date(context, prereqs):
raise FileRecipePostConditionError(self.name)
context.log.info(f'finish: {self.name}')
return self.path
async def _is_up_to_date(
self, context: Context, prereqs: t.Iterable[t.Any]
) -> bool:
try:
mtime = os.stat(self.name).st_mtime
except FileNotFoundError:
return False
for prereq in prereqs:
if not is_file_like(prereq):
# Not a filename.
context.log.warn(
f'skipping non-filename dependency: {prereq}')
continue
if os.stat(prereq).st_mtime > mtime:
# Prerequisite has been modified after target.
return False
return True
def file_target(value: FileTargetLike) -> Target:
"""Canonicalize a value to a :class:`Target`.
If the value is already a :class:`Target`, it is returned as-is.
If it is a :class:`str`, it is returned as a :class:`FileTarget`.
Parameters
----------
value :
A value convertible to :class:`Target`.
Returns
-------
Target
A target.
Raises
------
Exception
If :param:`value` is not convertible to a target.
"""
if isinstance(value, Target):
return value
if is_file_like(value):
# Treat ``value`` as a filename.
return file(value)()
raise Exception(f'not a target: {value}')
async def _noop(*args, **kwargs) -> None: # pylint: disable=unused-argument
"""A function that does nothing."""
def file(target: FileLike, *prereqs: FileTargetLike):
"""A file that is newer than its prerequisite files."""
# pylint: disable=unused-argument
def decorator(recipe: Recipe = _noop):
return FileTarget(Path(target), recipe, *prereqs)
return decorator
| 33.3
| 78
| 0.622623
|
b41bc6efcfba9901766c6fac3569a14859f51dce
| 81
|
ps1
|
PowerShell
|
apps/apps-web/netbasal.com/make-your-angular-forms-error-messages-magically-appear/intro1/appStart.ps1
|
reyou/Ggg.Angular
|
a402c352401fcc126be9bc480906283f02c7ac01
|
[
"Apache-2.0"
] | null | null | null |
apps/apps-web/netbasal.com/make-your-angular-forms-error-messages-magically-appear/intro1/appStart.ps1
|
reyou/Ggg.Angular
|
a402c352401fcc126be9bc480906283f02c7ac01
|
[
"Apache-2.0"
] | 32
|
2021-03-09T12:56:09.000Z
|
2022-03-02T11:24:07.000Z
|
apps/apps-web/netbasal.com/make-your-angular-forms-error-messages-magically-appear/intro1/appStart.ps1
|
reyou/Ggg.Angular
|
a402c352401fcc126be9bc480906283f02c7ac01
|
[
"Apache-2.0"
] | null | null | null |
Set-Location .\angular-forms-error
ng serve --port 3000 --open
Set-Location .\..
| 20.25
| 34
| 0.716049
|
85324201b8253adb4bb5dd8557ab10e2837cdd74
| 958
|
cs
|
C#
|
CsharpLibrary/Extensions/XmlExtension.cs
|
hellomrsun/CsharpLibrary
|
5e81dff41aade2f6f80799ff4ca3b82776637cee
|
[
"Apache-2.0"
] | null | null | null |
CsharpLibrary/Extensions/XmlExtension.cs
|
hellomrsun/CsharpLibrary
|
5e81dff41aade2f6f80799ff4ca3b82776637cee
|
[
"Apache-2.0"
] | null | null | null |
CsharpLibrary/Extensions/XmlExtension.cs
|
hellomrsun/CsharpLibrary
|
5e81dff41aade2f6f80799ff4ca3b82776637cee
|
[
"Apache-2.0"
] | null | null | null |
using System;
using System.IO;
using System.Xml.Serialization;
namespace CsharpLibrary.Extensions
{
public static class XmlExtension
{
public static string SerializeToString<T>(this T obj, XmlSerializerNamespaces namespaces)
{
if (obj == null)
{
throw new ArgumentNullException($"null can not be serialized to xml!");
}
using (var writer = new StringWriter())
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj, namespaces);
return writer.ToString();
}
}
public static T DeserializeFromObject<T>(string str)
{
using (var reader = new StringReader(str))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}
}
}
}
| 25.891892
| 97
| 0.549061
|
38a5b7f7c96452db611d59b4c47e83287d32c053
| 670
|
php
|
PHP
|
src/Entities/Instagram.php
|
takaaki-mizuno/video-service-url-analyser
|
093c8977628e2a3a2705feecfea0c9855958d8a9
|
[
"MIT"
] | 2
|
2015-10-28T00:05:35.000Z
|
2017-04-26T02:16:41.000Z
|
src/Entities/Instagram.php
|
takaaki-mizuno/video-service-url-analyser
|
093c8977628e2a3a2705feecfea0c9855958d8a9
|
[
"MIT"
] | null | null | null |
src/Entities/Instagram.php
|
takaaki-mizuno/video-service-url-analyser
|
093c8977628e2a3a2705feecfea0c9855958d8a9
|
[
"MIT"
] | 3
|
2015-12-18T08:46:17.000Z
|
2020-03-27T10:40:20.000Z
|
<?php
namespace TakaakiMizuno\VideoServiceUrlAnalyzer\Entities;
class Instagram extends Base
{
public function getEmbeddedSrcUrl()
{
return 'http://www.instagram.com/p/'.$this->getId().'/';
}
public function getEmbeddedHtml($width = 560, $height = 315)
{
return $this->getInfo('html');
}
public function getUrl()
{
return 'https://www.instagram.com/p/'.$this->getId().'/';
}
public function getServiceName()
{
return 'Instagram';
}
protected function getOEmbedUrl()
{
return 'http://api.instagram.com/oembed?format=json&url='.htmlspecialchars($this->getUrl());
}
}
| 21.612903
| 100
| 0.614925
|
6d0925c922007c8631a5c77d82304b3745119d53
| 91
|
ts
|
TypeScript
|
FrontEnd/Angular/src/environments/environment.prod.ts
|
jsalmeida1101/Angular-Teste
|
048829a51701795fce8e90b26eaae11875fcbbc4
|
[
"Unlicense"
] | null | null | null |
FrontEnd/Angular/src/environments/environment.prod.ts
|
jsalmeida1101/Angular-Teste
|
048829a51701795fce8e90b26eaae11875fcbbc4
|
[
"Unlicense"
] | 8
|
2019-12-30T02:54:36.000Z
|
2022-03-02T05:51:04.000Z
|
FrontEnd/Angular/src/environments/environment.prod.ts
|
jsalmeida1101/Angular-Teste
|
048829a51701795fce8e90b26eaae11875fcbbc4
|
[
"Unlicense"
] | null | null | null |
export const environment = {
production: true,
api_url: 'http://localhost:49493/api/'
};
| 18.2
| 39
| 0.703297
|
4ebb67bdaaffe735e2f1abc142641f3d030342ea
| 1,016
|
lua
|
Lua
|
lua/settings.lua
|
arnavyc/nvim-config
|
1a0d6cd48cf0abc95fa0dc78ceb30552f0b4ba1b
|
[
"0BSD"
] | null | null | null |
lua/settings.lua
|
arnavyc/nvim-config
|
1a0d6cd48cf0abc95fa0dc78ceb30552f0b4ba1b
|
[
"0BSD"
] | null | null | null |
lua/settings.lua
|
arnavyc/nvim-config
|
1a0d6cd48cf0abc95fa0dc78ceb30552f0b4ba1b
|
[
"0BSD"
] | null | null | null |
local indent_size = 2
vim.cmd 'syntax enable'
vim.cmd 'filetype plugin indent on'
vim.opt.expandtab = true
vim.opt.shiftwidth = indent_size
vim.opt.smartindent = true
vim.opt.tabstop = indent_size
vim.opt.hidden = true
vim.opt.ignorecase = true
vim.opt.scrolloff = 4
vim.opt.shiftround = true
vim.opt.smartcase = true
vim.opt.splitbelow = true
vim.opt.splitright = true
vim.opt.wildmode = 'list:longest'
vim.opt.number = true
-- vim.opt.clipboard = 'unnamed,unnamedplus'
vim.o.completeopt = 'menuone,noinsert,noselect'
-- Highlight on yank
vim.cmd 'au TextYankPost * lua vim.highlight.on_yank {on_visual = false}'
-- sheerun/vim-polyglot
vim.g.polyglot_disable = {
'c.plugin', 'cpp.plugin', 'javascript.plugin', 'typescript.plugin', 'sensible'
}
-- editorconfig/editorconfig-vim
-- Exclude patterns to ensure plugin works well with vim-fugitive
vim.g.EditorConfig_exclude_patterns = {'fugitive://.*'}
-- Disable Editorconfig for git commits
vim.cmd [[au FileType gitcommit let b:EditorConfig_disable = 1]]
| 26.736842
| 80
| 0.752953
|
e6161f834472d80507d6d2889526a136dbbe9d18
| 7,193
|
swift
|
Swift
|
Example/Tests/FeatureTagManagerTests.swift
|
threeplay/TPFeatureTag
|
8e668e49d8bf6df7661040aca55f696c6f1303cc
|
[
"MIT"
] | null | null | null |
Example/Tests/FeatureTagManagerTests.swift
|
threeplay/TPFeatureTag
|
8e668e49d8bf6df7661040aca55f696c6f1303cc
|
[
"MIT"
] | null | null | null |
Example/Tests/FeatureTagManagerTests.swift
|
threeplay/TPFeatureTag
|
8e668e49d8bf6df7661040aca55f696c6f1303cc
|
[
"MIT"
] | null | null | null |
//
// Created by Eliran Ben-Ezra on 10/28/18.
//
import XCTest
import Nimble
@testable import TPFeatureTag
class FeatureTagManagerTests: XCTestCase {
class TestFeatures {
let f1 = makeFeature()
let f2 = makeFeature(key: "123")
let f3 = makeFeature(enabled: true)
let ignoreBool = true
let ignoreString = "123"
let ignoreInt = 123
}
class OtherTestFeatures {
let f1 = makeFeature()
}
class Getter: FeatureTagGetter {
var value = [FeatureTag: Bool]()
func isOn(feature: FeatureTag) -> Bool? {
return value[feature]
}
}
class MockResolver: Getter, FeatureTagSetter {
enum Action: Equatable {
case set(FeatureTag, state: Bool)
case clear(FeatureTag)
}
var actions = [Action]()
func set(feature: FeatureTag, isOn: Bool) {
value[feature] = isOn
actions.append(.set(feature, state: isOn))
}
func clear(feature: FeatureTag) {
value.removeValue(forKey: feature)
actions.append(.clear(feature))
}
}
let testFeatures = TestFeatures()
let otherTestFeatures = OtherTestFeatures()
var mockGetter = Getter()
var mockResolver = MockResolver()
var manager: FeatureTags.Manager!
override func setUp() {
super.setUp()
manager = FeatureTags.Manager()
}
func test_that_feature_returns_default_if_it_was_never_registered() {
expect(makeFeature().isOn).to(beFalse())
expect(makeFeature(enabled: true).isOn).to(beTrue())
}
func test_that_feature_returns_default_source_if_it_was_never_registered() {
expect(makeFeature().source).to(equal(FeatureTags.Manager.defaultSource))
}
func test_that_instance_always_returns_the_same_instance() {
expect(FeatureTags.Manager.instance) === FeatureTags.Manager.instance
}
func test_that_non_feature_tag_instance_vars_are_ignored() {
manager.register(testFeatures)
expect(self.manager.allFeatures.map { $0.name }).toNot(contain(["ignoreBool", "ignoreString", "ignoreInt"]))
}
func test_that_registered_features_have_the_correct_name_space() {
let expectedNameSpace = "TestFeatures"
manager.register(testFeatures)
manager.register(otherTestFeatures)
expect(self.testFeatures.f1.namespace).to(equal(expectedNameSpace))
expect(self.testFeatures.f2.namespace).to(equal(expectedNameSpace))
expect(self.testFeatures.f3.namespace).to(equal(expectedNameSpace))
expect(self.otherTestFeatures.f1.namespace).to(equal("OtherTestFeatures"))
}
func test_that_registered_features_have_the_correct_name() {
manager.register(testFeatures)
expect(self.testFeatures.f1.name).to(equal("f1"))
expect(self.testFeatures.f2.name).to(equal("f2"))
expect(self.testFeatures.f3.name).to(equal("f3"))
}
func test_that_it_can_register_features() {
manager.register(testFeatures)
let ourFeatures = manager.allFeatures.filter { $0.namespace == "TestFeatures" }
expect(ourFeatures).to(contain([testFeatures.f1, testFeatures.f2, testFeatures.f3]))
}
func test_that_resolvers_can_be_installed() {
manager.install(name: "local", priority: 1, resolver: mockGetter)
manager.register(testFeatures)
mockGetter.value[testFeatures.f1] = true
expect(self.testFeatures.f1.isOn).to(beTrue())
mockGetter.value = [:]
expect(self.testFeatures.f1.isOn).to(beFalse())
}
func test_that_features_return_the_default_value() {
manager.register(testFeatures)
expect(self.testFeatures.f1.isOn).to(beFalse())
expect(self.testFeatures.f3.isOn).to(beTrue())
}
func test_that_features_return_the_values_source() {
manager.install(name: "local", priority: 1, resolver: mockGetter)
manager.register(testFeatures)
expect(self.testFeatures.f1.source).to(equal("default"))
mockGetter.value[testFeatures.f1] = true
expect(self.testFeatures.f1.source).to(equal("local"))
}
func test_that_feature_tags_can_move_to_a_new_manager() {
manager.register(testFeatures)
manager.install(name: "local", priority: 1, resolver: mockGetter)
mockGetter.value[testFeatures.f1] = true
let otherManager = FeatureTags.Manager()
otherManager.register(testFeatures)
expect(self.testFeatures.f1.isOn).to(beFalse())
}
func test_that_feature_tags_can_be_registered_multiple_times_to_the_same_manager() {
manager.register(testFeatures)
manager.register(testFeatures)
expect(self.manager.allFeatures.count).to(equal(3))
}
func test_that_resolvers_are_evaluated_in_decending_priority_order() {
let priority1 = Getter()
let priority2 = Getter()
let priority3 = Getter()
manager.install(name: "p1", priority: 1, resolver: priority1)
manager.install(name: "p3", priority: 3, resolver: priority3)
manager.install(name: "p2", priority: 2, resolver: priority2)
priority1.value[testFeatures.f1] = true
expect(self.manager.resolve(self.testFeatures.f1).source).to(equal("p1"))
priority2.value[testFeatures.f1] = false
priority3.value[testFeatures.f1] = false
expect(self.manager.resolve(self.testFeatures.f1).source).to(equal("p3"))
priority3.value = [:]
expect(self.manager.resolve(self.testFeatures.f1).source).to(equal("p2"))
}
func test_that_individual_resolvers_can_be_requested_to_override_a_feature_value() {
let resolver = MockResolver()
manager.install(name: "mock", priority: 1, resolver: resolver)
manager.set(testFeatures.f1, to: true, in: "mock")
expect(resolver.actions).to(contain([MockResolver.Action.set(testFeatures.f1, state: true)]))
manager.set(testFeatures.f2, to: true, in: "other")
expect(resolver.actions).toNot(contain([MockResolver.Action.set(testFeatures.f2, state: true)]))
}
func test_that_individual_resolvers_can_be_request_to_reset_a_feature_value() {
let resolver = MockResolver()
manager.install(name: "mock", priority: 1, resolver: resolver)
manager.clear(testFeatures.f1, in: "mock")
expect(resolver.actions).to(contain([MockResolver.Action.clear(testFeatures.f1)]))
manager.clear(testFeatures.f2, in: "other")
expect(resolver.actions).toNot(contain([MockResolver.Action.clear(testFeatures.f2)]))
}
func test_that_all_resolvers_can_be_requested_to_override_a_feature_value() {
let resolver1 = MockResolver()
let resolver2 = MockResolver()
manager.install(name: "mock", priority: 1, resolver: resolver1)
manager.install(name: "other", priority: 2, resolver: resolver2)
manager.set(testFeatures.f1, to: true)
expect(resolver1.actions).to(contain([MockResolver.Action.set(testFeatures.f1, state: true)]))
expect(resolver1.actions).to(contain([MockResolver.Action.set(testFeatures.f1, state: true)]))
}
func test_that_all_resolvers_can_be_requested_to_reset_a_feature_value() {
let resolver1 = MockResolver()
let resolver2 = MockResolver()
manager.install(name: "mock", priority: 1, resolver: resolver1)
manager.install(name: "other", priority: 2, resolver: resolver2)
manager.clear(testFeatures.f1)
expect(resolver1.actions).to(contain([MockResolver.Action.clear(testFeatures.f1)]))
expect(resolver2.actions).to(contain([MockResolver.Action.clear(testFeatures.f1)]))
}
}
| 36.328283
| 112
| 0.731406
|
ac00ce275589bd04708833ef01f0cfdd194ad55e
| 966
|
dart
|
Dart
|
lib/utils/global.dart
|
DC2T/flutter-daophim
|
e4208a419878cf8a8eea6f794540af73e083cc1c
|
[
"MIT"
] | null | null | null |
lib/utils/global.dart
|
DC2T/flutter-daophim
|
e4208a419878cf8a8eea6f794540af73e083cc1c
|
[
"MIT"
] | null | null | null |
lib/utils/global.dart
|
DC2T/flutter-daophim
|
e4208a419878cf8a8eea6f794540af73e083cc1c
|
[
"MIT"
] | null | null | null |
import 'package:admin/models/Category.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
/*
Not allow modifier(add, edit, delete,...) in this file utils
*/
final List<Map<String, dynamic>> tables = <Map<String, dynamic>>[
{'name': 'Movie', 'icon': Icon(Icons.movie_creation_outlined)},
{'name': 'Worker', 'icon': Icon(Icons.cloud_outlined)},
{'name': 'Advertising', 'icon': Icon(Icons.campaign)},
];
String formatDate(DateTime d){
return DateFormat('MM/dd/yyyy').format(d);
}
String formatTime(DateTime d){
return DateFormat('HH:mm').format(d);
}
String formatDateTime(DateTime d){
return DateFormat('MM/dd/yyyy HH:mm').format(d);
}
String filePicked = '';
pickFile() async {
FilePickerResult result =
await FilePicker.platform
.pickFiles();
if (result != null) {
filePicked = result.files.single.path;
} else {
// User canceled the picker
}
}
| 24.15
| 65
| 0.687371
|
663644eaf39e2cbc01bb1691806f609ee446bedf
| 468
|
py
|
Python
|
Module2/marketing.py
|
KBtooeasy/python-for-data-science
|
a1539070d5a5c45dbd4c80ed3a0d09c81854f37e
|
[
"MIT"
] | 1
|
2018-05-29T07:57:34.000Z
|
2018-05-29T07:57:34.000Z
|
Module2/marketing.py
|
KBtooeasy/python-for-data-science
|
a1539070d5a5c45dbd4c80ed3a0d09c81854f37e
|
[
"MIT"
] | null | null | null |
Module2/marketing.py
|
KBtooeasy/python-for-data-science
|
a1539070d5a5c45dbd4c80ed3a0d09c81854f37e
|
[
"MIT"
] | null | null | null |
import pandas as pd
df = pd.read_csv("Datasets/direct_marketing.csv")
print(df.describe())
#print(df['recency'])
print(df[['recency']])
df.loc[:, 'recency']
# Produces a series object:
df.recency
df['recency']
df.loc[:, 'recency']
df.iloc[:, 0]
df.ix[:, 0]
#
# Produces a dataframe object:
df[['recency']]
df.loc[:, ['recency']]
df.iloc[:, [0]]
print(df.iloc[0:5,:3])
print(df[ (df.recency > 10) & (df.newbie == 0)])
print(df.loc[0:4, ['recency', 'channel']])
| 16.137931
| 49
| 0.623932
|
0ac90845fc54ca78518afeb6eb223ad2426aa853
| 2,199
|
cs
|
C#
|
src/Surging.Apm/Surging.Apm.Skywalking/Transport/Grpc/Common/AsyncLock.cs
|
foreverhot1019/surging
|
65467b10a06e37491cdbf6a2ef36cb586c210e08
|
[
"MIT"
] | 518
|
2017-06-16T14:52:54.000Z
|
2022-03-27T20:02:34.000Z
|
src/Surging.Apm/Surging.Apm.Skywalking/Transport/Grpc/Common/AsyncLock.cs
|
foreverhot1019/surging
|
65467b10a06e37491cdbf6a2ef36cb586c210e08
|
[
"MIT"
] | 23
|
2020-04-23T06:08:41.000Z
|
2021-10-14T07:33:59.000Z
|
src/Surging.Apm/Surging.Apm.Skywalking/Transport/Grpc/Common/AsyncLock.cs
|
foreverhot1019/surging
|
65467b10a06e37491cdbf6a2ef36cb586c210e08
|
[
"MIT"
] | 159
|
2017-06-16T14:53:14.000Z
|
2022-03-15T17:34:03.000Z
|
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Surging.Apm.Skywalking.Transport.Grpc.Common
{
internal class AsyncLock
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private readonly Release _release;
private readonly Task<Release> _releaseTask;
public AsyncLock()
{
_release = new Release(this);
_releaseTask = Task.FromResult(_release);
}
public Task<Release> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var wait = _semaphore.WaitAsync(cancellationToken);
return wait.IsCompleted
? _releaseTask
: wait.ContinueWith(
(_, state) => ((AsyncLock) state)._release,
this, CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public Release Lock()
{
_semaphore.Wait();
return _release;
}
public struct Release : IDisposable
{
private readonly AsyncLock _toRelease;
internal Release(AsyncLock toRelease)
{
_toRelease = toRelease;
}
public void Dispose()
=> _toRelease._semaphore.Release();
}
}
}
| 31.869565
| 104
| 0.639382
|
957a7951992ecc95e77eae4cda7c3e664b88b1de
| 3,900
|
kt
|
Kotlin
|
example/src/main/java/com/eaglesakura/example/AnnotationExampleActivity.kt
|
eaglesakura/workflow-dispatcher
|
fb1f84c2e7cf5fe8a70ece1564fa342e514c28e4
|
[
"MIT"
] | 2
|
2020-08-31T02:00:32.000Z
|
2021-04-05T11:12:31.000Z
|
example/src/main/java/com/eaglesakura/example/AnnotationExampleActivity.kt
|
eaglesakura/workflow-dispatcher
|
fb1f84c2e7cf5fe8a70ece1564fa342e514c28e4
|
[
"MIT"
] | 7
|
2020-03-27T07:22:16.000Z
|
2021-02-18T07:51:07.000Z
|
example/src/main/java/com/eaglesakura/example/AnnotationExampleActivity.kt
|
eaglesakura/workflow-dispatcher
|
fb1f84c2e7cf5fe8a70ece1564fa342e514c28e4
|
[
"MIT"
] | null | null | null |
package com.eaglesakura.example
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.appcompat.app.AppCompatActivity
import com.eaglesakura.workflowdispatcher.OnActivityResultFlow
import com.eaglesakura.workflowdispatcher.OnDialogResultFlow
import com.eaglesakura.workflowdispatcher.OnRuntimePermissionResultFlow
import com.eaglesakura.workflowdispatcher.dialog.AlertDialogFactory
import com.eaglesakura.workflowdispatcher.dialog.DialogResult
import com.eaglesakura.workflowdispatcher.permission.RuntimePermissionResult
import java.util.Date
class AnnotationExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
val startDate = Date()
showExampleDialogWithState(AlertDialogFactory.Builder().also { builder ->
builder.message = "Start Runtime-Permission!!\nstartDate='$startDate'"
builder.positiveButton = "Start"
builder.negativeButton = "Abort"
}.build(), startDate, "https://google.com")
} else {
Toast.makeText(this, "ReBuild Activity", Toast.LENGTH_SHORT).show()
}
}
/**
* Done dialog result.
*/
@OnDialogResultFlow("showExampleDialog")
internal fun onShowExampleDialogResult(result: DialogResult) {
when (result.selected) {
DialogResult.Selection.Positive -> {
runtimePermissionFlow()
}
}
}
@OnDialogResultFlow("showExampleDialogWithState")
internal fun onShowExampleDialogWithStateResult(
result: DialogResult,
startDate: Date,
url: String
) {
when (result.selected) {
DialogResult.Selection.Positive -> {
runtimePermissionWithStateFlow(url = url, startDate = startDate)
}
}
}
/**
* Done runtime permission result.
*/
@OnRuntimePermissionResultFlow(
"runtimePermissionFlow",
[android.Manifest.permission.WRITE_EXTERNAL_STORAGE]
)
internal fun onRuntimePermissionResult(result: RuntimePermissionResult) {
if (!result.allGranted) {
Toast.makeText(this, "permission not granted: ${result.permissions}", Toast.LENGTH_LONG)
.show()
finish()
return
}
activityResultFlow(Intent(Intent.ACTION_VIEW, Uri.parse("https://yahoo.com")))
}
/**
* Done runtime permission result.
*/
@OnRuntimePermissionResultFlow(
"runtimePermissionWithStateFlow",
[android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE]
)
internal fun onRuntimePermissionWithStateResult(
result: RuntimePermissionResult,
startDate: Date,
url: String
) {
if (!result.allGranted) {
Toast.makeText(this, "permission not granted: ${result.permissions}", Toast.LENGTH_LONG)
.show()
finish()
return
}
activityResultFlowWithState(
Intent(Intent.ACTION_VIEW, Uri.parse(url)),
startDate = startDate
)
}
/**
* Done activity result.
*/
@OnActivityResultFlow("activityResultFlow")
internal fun onActivityResultFlowResult(result: ActivityResult) {
Toast.makeText(this, "Done All Flow!!", Toast.LENGTH_LONG).show()
}
@OnActivityResultFlow("activityResultFlowWithState")
internal fun onActivityResultWithStateFlowResult(
result: ActivityResult, startDate: Date
) {
Toast.makeText(this, "startDate='$startDate'", Toast.LENGTH_LONG).show()
}
}
| 33.050847
| 111
| 0.666154
|
fb8cce2e52000dfcd1f396f3aaaea22a1a1b7ad7
| 59,636
|
c
|
C
|
release/src-rt-6.x.4708/router/nano/src/global.c
|
afeng11/tomato-arm
|
1ca18a88480b34fd495e683d849f46c2d47bb572
|
[
"FSFAP"
] | 4
|
2017-05-17T11:27:04.000Z
|
2020-05-24T07:23:26.000Z
|
release/src-rt-6.x.4708/router/nano/src/global.c
|
afeng11/tomato-arm
|
1ca18a88480b34fd495e683d849f46c2d47bb572
|
[
"FSFAP"
] | 1
|
2018-08-21T03:43:09.000Z
|
2018-08-21T03:43:09.000Z
|
release/src-rt-6.x.4708/router/nano/src/global.c
|
afeng11/tomato-arm
|
1ca18a88480b34fd495e683d849f46c2d47bb572
|
[
"FSFAP"
] | 5
|
2017-10-11T08:09:11.000Z
|
2020-10-14T04:10:13.000Z
|
/**************************************************************************
* global.c *
* *
* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, *
* 2008, 2009, 2010, 2011, 2013, 2014 Free Software Foundation, Inc. *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
* 02110-1301, USA. *
* *
**************************************************************************/
#include "proto.h"
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include "assert.h"
/* Global variables. */
#ifndef NANO_TINY
volatile sig_atomic_t sigwinch_counter = 0;
/* Is incremented by the handler whenever a SIGWINCH occurs. */
#endif
bool meta_key;
/* Whether the current keystroke is a Meta key. */
bool func_key;
/* Whether the current keystroke is an extended keypad value. */
bool focusing = TRUE;
/* Whether an update of the edit window should center the cursor. */
message_type lastmessage = HUSH;
/* Messages of type HUSH should not overwrite type MILD nor ALERT. */
#ifndef NANO_TINY
int controlleft = CONTROL_LEFT;
int controlright = CONTROL_RIGHT;
#endif
#ifndef DISABLE_WRAPJUSTIFY
ssize_t fill = 0;
/* The column where we will wrap lines. */
ssize_t wrap_at = -CHARS_FROM_EOL;
/* The position where we will wrap lines. fill is equal to this
* if it's greater than zero, and equal to (COLS + this) if it
* isn't. */
#endif
char *last_search = NULL;
/* The last string we searched for. */
char *present_path = NULL;
/* The current browser directory when trying to do tab completion. */
unsigned flags[4] = {0, 0, 0, 0};
/* Our flag containing the states of all global options. */
WINDOW *topwin;
/* The top portion of the window, where we display the version
* number of nano, the name of the current file, and whether the
* current file has been modified. */
WINDOW *edit;
/* The middle portion of the window, i.e. the edit window, where
* we display the current file we're editing. */
WINDOW *bottomwin;
/* The bottom portion of the window, where we display statusbar
* messages, the statusbar prompt, and a list of shortcuts. */
int editwinrows = 0;
/* How many rows does the edit window take up? */
int maxrows = 0;
/* How many usable lines there are (due to soft wrapping). */
filestruct *cutbuffer = NULL;
/* The buffer where we store cut text. */
filestruct *cutbottom = NULL;
#ifndef DISABLE_JUSTIFY
filestruct *jusbuffer = NULL;
/* The buffer where we store unjustified text. */
#endif
partition *filepart = NULL;
/* The partition where we store a portion of the current
* file. */
openfilestruct *openfile = NULL;
/* The list of all open file buffers. */
#ifndef NANO_TINY
char *matchbrackets = NULL;
/* The opening and closing brackets that can be found by bracket
* searches. */
char *whitespace = NULL;
/* The characters used when visibly showing tabs and spaces. */
int whitespace_len[2];
/* The length in bytes of these characters. */
#endif
#ifndef DISABLE_JUSTIFY
char *punct = NULL;
/* The closing punctuation that can end sentences. */
char *brackets = NULL;
/* The closing brackets that can follow closing punctuation and
* can end sentences. */
char *quotestr = NULL;
/* The quoting string. The default value is set in main(). */
#ifdef HAVE_REGEX_H
regex_t quotereg;
/* The compiled regular expression from the quoting string. */
int quoterc;
/* Whether it was compiled successfully. */
char *quoteerr = NULL;
/* The error message, if it didn't. */
#else
size_t quotelen;
/* The length of the quoting string in bytes. */
#endif
#endif
bool nodelay_mode = FALSE;
/* Are we checking for a cancel wile doing something? */
char *answer = NULL;
/* The answer string used by the statusbar prompt. */
ssize_t tabsize = -1;
/* The width of a tab in spaces. The default value is set in
* main(). */
#ifndef NANO_TINY
char *backup_dir = NULL;
/* The directory where we store backup files. */
const char *locking_prefix = ".";
/* Prefix of how to store the vim-style lock file. */
const char *locking_suffix = ".swp";
/* Suffix of the vim-style lock file. */
#endif
#ifndef DISABLE_OPERATINGDIR
char *operating_dir = NULL;
/* The relative path to the operating directory, which we can't
* move outside of. */
char *full_operating_dir = NULL;
/* The full path to it. */
#endif
#ifndef DISABLE_SPELLER
char *alt_speller = NULL;
/* The command to use for the alternate spell checker. */
#endif
#ifndef DISABLE_COLOR
syntaxtype *syntaxes = NULL;
/* The global list of color syntaxes. */
char *syntaxstr = NULL;
/* The color syntax name specified on the command line. */
#endif
bool refresh_needed = FALSE;
/* Did a command mangle enough of the buffer that we should
* repaint the screen? */
int currmenu = MMOST;
/* The currently active menu, initialized to a dummy value. */
sc *sclist = NULL;
/* Pointer to the start of the shortcuts list. */
subnfunc *allfuncs = NULL;
/* Pointer to the start of the functions list. */
subnfunc *tailfunc;
/* Pointer to the last function in the list. */
subnfunc *exitfunc;
/* Pointer to the special Exit/Close item. */
subnfunc *uncutfunc;
/* Pointer to the special Uncut/Unjustify item. */
#ifndef DISABLE_HISTORIES
filestruct *search_history = NULL;
/* The search string history list. */
filestruct *searchage = NULL;
/* The top of the search string history list. */
filestruct *searchbot = NULL;
/* The bottom of the search string history list. */
filestruct *replace_history = NULL;
/* The replace string history list. */
filestruct *replaceage = NULL;
/* The top of the replace string history list. */
filestruct *replacebot = NULL;
/* The bottom of the replace string history list. */
poshiststruct *position_history = NULL;
/* The cursor position history list. */
#endif
/* Regular expressions. */
#ifdef HAVE_REGEX_H
regex_t search_regexp;
/* The compiled regular expression to use in searches. */
regmatch_t regmatches[10];
/* The match positions for parenthetical subexpressions, 10
* maximum, used in regular expression searches. */
#endif
int hilite_attribute = A_REVERSE;
/* The curses attribute we use for reverse video. */
#ifndef DISABLE_COLOR
char* specified_color_combo[] = {};
/* The color combinations as specified in the rcfile. */
#endif
color_pair interface_color_pair[] = {};
/* The processed color pairs for the interface elements. */
char *homedir = NULL;
/* The user's home directory, from $HOME or /etc/passwd. */
/* Return the number of entries in the shortcut list for a given menu. */
size_t length_of_list(int menu)
{
subnfunc *f;
size_t i = 0;
for (f = allfuncs; f != NULL; f = f->next)
if ((f->menus & menu) != 0) {
i++;
}
return i;
}
/* To make the functions and shortcuts lists clearer. */
#define VIEW TRUE /* Is allowed in view mode. */
#define NOVIEW FALSE
#define BLANKAFTER TRUE /* A blank line after this one. */
#define TOGETHER FALSE
/* Just throw this here. */
void case_sens_void(void)
{
}
void regexp_void(void)
{
}
void backwards_void(void)
{
}
void gototext_void(void)
{
}
#ifndef DISABLE_BROWSER
void to_files_void(void)
{
}
void goto_dir_void(void)
{
}
#endif
void dos_format_void(void)
{
}
void mac_format_void(void)
{
}
void append_void(void)
{
}
void prepend_void(void)
{
}
void backup_file_void(void)
{
}
void discard_buffer(void)
{
}
void new_buffer_void(void)
{
}
void flip_replace_void(void)
{
}
void flip_execute_void(void)
{
}
/* Add a function to the function list. */
void add_to_funcs(void (*func)(void), int menus, const char *desc, const char *help,
bool blank_after, bool viewok)
{
subnfunc *f = (subnfunc *)nmalloc(sizeof(subnfunc));
if (allfuncs == NULL)
allfuncs = f;
else
tailfunc->next = f;
tailfunc = f;
f->next = NULL;
f->scfunc = func;
f->menus = menus;
f->desc = desc;
f->viewok = viewok;
#ifndef DISABLE_HELP
f->help = help;
f->blank_after = blank_after;
#endif
#ifdef DEBUG
fprintf(stderr, "Added func %ld (%s) for menus %x\n", (long)func, f->desc, menus);
#endif
}
/* Add a key combo to the shortcut list. */
void add_to_sclist(int menus, const char *scstring, void (*func)(void), int toggle)
{
static sc *tailsc;
static int counter = 0;
sc *s = (sc *)nmalloc(sizeof(sc));
/* Start the list, or tack on the next item. */
if (sclist == NULL)
sclist = s;
else
tailsc->next = s;
tailsc = s;
s->next = NULL;
/* Fill in the data. */
s->menus = menus;
s->scfunc = func;
s->toggle = toggle;
if (toggle)
s->ordinal = ++counter;
s->keystr = (char *) scstring;
s->type = strtokeytype(scstring);
assign_keyinfo(s);
#ifdef DEBUG
fprintf(stderr, "Setting sequence to %d for shortcut \"%s\" in menus %x\n", s->seq, scstring, s->menus);
#endif
}
/* Assign one function's shortcuts to another function. */
void replace_scs_for(void (*oldfunc)(void), void (*newfunc)(void))
{
sc *s;
for (s = sclist; s != NULL; s = s->next)
if (s->scfunc == oldfunc)
s->scfunc = newfunc;
}
/* Return the first shortcut in the list of shortcuts that
* matches the given func in the given menu. */
const sc *first_sc_for(int menu, void (*func)(void))
{
const sc *s;
for (s = sclist; s != NULL; s = s->next)
if ((s->menus & menu) && s->scfunc == func)
return s;
#ifdef DEBUG
fprintf(stderr, "Whoops, returning null given func %ld in menu %x\n", (long)func, menu);
#endif
/* Otherwise... */
return NULL;
}
/* Return the given menu's first shortcut sequence, or the default value
* (2nd arg). Assumes currmenu for the menu to check. */
int sc_seq_or(void (*func)(void), int defaultval)
{
const sc *s = first_sc_for(currmenu, func);
if (s) {
meta_key = (s->type == META);
return s->seq;
}
/* else */
return defaultval;
}
/* Return a pointer to the function that is bound to the given key. */
functionptrtype func_from_key(int *kbinput)
{
const sc *s = get_shortcut(kbinput);
if (s)
return s->scfunc;
else
return NULL;
}
/* Return the type of command key based on the given string. */
key_type strtokeytype(const char *str)
{
if (str[0] == '^')
return CONTROL;
else if (str[0] == 'M')
return META;
else if (str[0] == 'F')
return FKEY;
else
return RAWINPUT;
}
/* Assign the info to the shortcut struct.
* Assumes keystr is already assigned, naturally. */
void assign_keyinfo(sc *s)
{
if (s->type == CONTROL) {
assert(strlen(s->keystr) > 1);
s->seq = s->keystr[1] - 64;
} else if (s->type == META) {
assert(strlen(s->keystr) > 2);
s->seq = tolower((int) s->keystr[2]);
} else if (s->type == FKEY) {
assert(strlen(s->keystr) > 1);
s->seq = KEY_F0 + atoi(&s->keystr[1]);
} else /* RAWINPUT */
s->seq = (int) s->keystr[0];
/* Override some keys which don't bind as easily as we'd like. */
if (s->type == CONTROL && (!strcasecmp(&s->keystr[1], "space")))
s->seq = 0;
else if (s->type == META && (!strcasecmp(&s->keystr[2], "space")))
s->seq = (int) ' ';
else if (s->type == RAWINPUT) {
if (!strcasecmp(s->keystr, "Up"))
s->seq = KEY_UP;
else if (!strcasecmp(s->keystr, "Down"))
s->seq = KEY_DOWN;
else if (!strcasecmp(s->keystr, "Left"))
s->seq = KEY_LEFT;
else if (!strcasecmp(s->keystr, "Right"))
s->seq = KEY_RIGHT;
else if (!strcasecmp(s->keystr, "Ins"))
s->seq = KEY_IC;
else if (!strcasecmp(s->keystr, "Del"))
s->seq = KEY_DC;
else if (!strcasecmp(s->keystr, "Bsp"))
s->seq = KEY_BACKSPACE;
/* The Tab and Enter keys don't actually produce special codes
* but the exact integer values of ^I and ^M. Rebinding the
* latter therefore also rebinds Tab and Enter. */
else if (!strcasecmp(s->keystr, "Tab"))
s->seq = NANO_CONTROL_I;
else if (!strcasecmp(s->keystr, "Enter"))
s->seq = KEY_ENTER;
else if (!strcasecmp(s->keystr, "PgUp"))
s->seq = KEY_PPAGE;
else if (!strcasecmp(s->keystr, "PgDn"))
s->seq = KEY_NPAGE;
else if (!strcasecmp(s->keystr, "Home"))
s->seq = KEY_HOME;
else if (!strcasecmp(s->keystr, "End"))
s->seq = KEY_END;
}
}
#ifdef DEBUG
void print_sclist(void)
{
sc *s;
const subnfunc *f;
for (s = sclist; s != NULL; s = s->next) {
f = sctofunc(s);
if (f)
fprintf(stderr, "Shortcut \"%s\", function: %s, menus %x\n", s->keystr, f->desc, f->menus);
else
fprintf(stderr, "Hmm, didn't find a func for \"%s\"\n", s->keystr);
}
}
#endif
/* These four tags are used elsewhere too, so they are global. */
/* TRANSLATORS: Try to keep the next fifteen strings at most 10 characters. */
const char *exit_tag = N_("Exit");
const char *close_tag = N_("Close");
const char *uncut_tag = N_("Uncut Text");
#ifndef DISABLE_JUSTIFY
const char *unjust_tag = N_("Unjustify");
#endif
/* Initialize the list of functions and the list of shortcuts. */
void shortcut_init(void)
{
const char *read_file_tag = N_("Read File");
const char *whereis_tag = N_("Where Is");
const char *replace_tag = N_("Replace");
const char *gotoline_tag = N_("Go To Line");
const char *prev_line_tag = N_("Prev Line");
const char *next_line_tag = N_("Next Line");
const char *prev_page_tag = N_("Prev Page");
const char *next_page_tag = N_("Next Page");
#ifndef DISABLE_JUSTIFY
const char *justify_tag = N_("Justify");
const char *fulljustify_tag = N_("FullJstify");
#endif
const char *refresh_tag = N_("Refresh");
#ifndef NANO_TINY
/* TRANSLATORS: Try to keep this string at most 12 characters. */
const char *whereis_next_tag = N_("WhereIs Next");
#endif
#ifndef DISABLE_HELP
#ifndef DISABLE_JUSTIFY
/* TRANSLATORS: The next long series of strings are shortcut descriptions;
* they are best kept shorter than 56 characters, but may be longer. */
const char *nano_justify_msg = N_("Justify the current paragraph");
#endif
const char *nano_cancel_msg = N_("Cancel the current function");
const char *nano_help_msg = N_("Display this help text");
const char *nano_exit_msg =
#ifndef DISABLE_MULTIBUFFER
N_("Close the current file buffer / Exit from nano")
#else
N_("Exit from nano")
#endif
;
const char *nano_writeout_msg =
N_("Write the current file to disk");
const char *nano_insert_msg =
N_("Insert another file into the current one");
const char *nano_whereis_msg =
N_("Search for a string or a regular expression");
#ifndef DISABLE_BROWSER
const char *nano_browser_whereis_msg = N_("Search for a string");
const char *nano_browser_refresh_msg = N_("Refresh the file list");
const char *nano_browser_lefthand_msg = N_("Go to lefthand column");
const char *nano_browser_righthand_msg = N_("Go to righthand column");
#endif
const char *nano_prevpage_msg = N_("Go one screenful up");
const char *nano_nextpage_msg = N_("Go one screenful down");
const char *nano_cut_msg =
N_("Cut the current line and store it in the cutbuffer");
const char *nano_uncut_msg =
N_("Uncut from the cutbuffer into the current line");
const char *nano_cursorpos_msg = N_("Display the position of the cursor");
#ifndef DISABLE_SPELLER
const char *nano_spell_msg = N_("Invoke the spell checker, if available");
#endif
const char *nano_replace_msg = N_("Replace a string or a regular expression");
const char *nano_gotoline_msg = N_("Go to line and column number");
#ifndef NANO_TINY
const char *nano_mark_msg = N_("Mark text starting from the cursor position");
const char *nano_whereis_next_msg = N_("Repeat the last search");
const char *nano_copy_msg =
N_("Copy the current line and store it in the cutbuffer");
const char *nano_indent_msg = N_("Indent the current line");
const char *nano_unindent_msg = N_("Unindent the current line");
#ifdef ENABLE_COMMENT
const char *nano_comment_msg = N_("Comment/uncomment the current line or marked lines");
#endif
const char *nano_undo_msg = N_("Undo the last operation");
const char *nano_redo_msg = N_("Redo the last undone operation");
#endif
const char *nano_back_msg = N_("Go back one character");
const char *nano_forward_msg = N_("Go forward one character");
#ifndef NANO_TINY
const char *nano_prevword_msg = N_("Go back one word");
const char *nano_nextword_msg = N_("Go forward one word");
#endif
const char *nano_prevline_msg = N_("Go to previous line");
const char *nano_nextline_msg = N_("Go to next line");
const char *nano_home_msg = N_("Go to beginning of current line");
const char *nano_end_msg = N_("Go to end of current line");
#ifndef DISABLE_JUSTIFY
const char *nano_parabegin_msg =
N_("Go to beginning of paragraph; then of previous paragraph");
const char *nano_paraend_msg =
N_("Go just beyond end of paragraph; then of next paragraph");
#endif
const char *nano_firstline_msg = N_("Go to the first line of the file");
const char *nano_lastline_msg = N_("Go to the last line of the file");
#ifndef NANO_TINY
const char *nano_bracket_msg = N_("Go to the matching bracket");
const char *nano_scrollup_msg =
N_("Scroll up one line without scrolling the cursor");
const char *nano_scrolldown_msg =
N_("Scroll down one line without scrolling the cursor");
#endif
#ifndef DISABLE_MULTIBUFFER
const char *nano_prevfile_msg = N_("Switch to the previous file buffer");
const char *nano_nextfile_msg = N_("Switch to the next file buffer");
#endif
const char *nano_verbatim_msg = N_("Insert the next keystroke verbatim");
const char *nano_tab_msg = N_("Insert a tab at the cursor position");
const char *nano_enter_msg = N_("Insert a newline at the cursor position");
const char *nano_delete_msg = N_("Delete the character under the cursor");
const char *nano_backspace_msg =
N_("Delete the character to the left of the cursor");
#ifndef NANO_TINY
const char *nano_cut_word_left_msg =
N_("Cut backward from cursor to word start");
const char *nano_cut_word_right_msg =
N_("Cut forward from cursor to next word start");
const char *nano_cut_till_eof_msg =
N_("Cut from the cursor position to the end of the file");
#endif
#ifndef DISABLE_JUSTIFY
const char *nano_fulljustify_msg = N_("Justify the entire file");
#endif
#ifndef NANO_TINY
const char *nano_wordcount_msg =
N_("Count the number of words, lines, and characters");
#endif
const char *nano_refresh_msg =
N_("Refresh (redraw) the current screen");
const char *nano_suspend_msg =
N_("Suspend the editor (if suspension is enabled)");
#ifndef NANO_TINY
const char *nano_savefile_msg = N_("Save file without prompting");
const char *nano_findprev_msg = N_("Search next occurrence backward");
const char *nano_findnext_msg = N_("Search next occurrence forward");
const char *nano_case_msg =
N_("Toggle the case sensitivity of the search");
const char *nano_reverse_msg =
N_("Reverse the direction of the search");
#endif
#ifdef HAVE_REGEX_H
const char *nano_regexp_msg =
N_("Toggle the use of regular expressions");
#endif
#ifndef DISABLE_HISTORIES
const char *nano_prev_history_msg =
N_("Recall the previous search/replace string");
const char *nano_next_history_msg =
N_("Recall the next search/replace string");
#endif
#ifndef DISABLE_BROWSER
const char *nano_tofiles_msg = N_("Go to file browser");
#endif
#ifndef NANO_TINY
const char *nano_dos_msg = N_("Toggle the use of DOS format");
const char *nano_mac_msg = N_("Toggle the use of Mac format");
const char *nano_append_msg = N_("Toggle appending");
const char *nano_prepend_msg = N_("Toggle prepending");
const char *nano_backup_msg = N_("Toggle backing up of the original file");
const char *nano_execute_msg = N_("Execute external command");
#endif
const char *nano_discard_buffer_msg = N_("Close buffer without saving it");
#ifndef DISABLE_MULTIBUFFER
const char *nano_multibuffer_msg = N_("Toggle the use of a new buffer");
#endif
#ifndef DISABLE_BROWSER
const char *nano_exitbrowser_msg = N_("Exit from the file browser");
const char *nano_firstfile_msg = N_("Go to the first file in the list");
const char *nano_lastfile_msg = N_("Go to the last file in the list");
const char *nano_backfile_msg = N_("Go to the previous file in the list");
const char *nano_forwardfile_msg = N_("Go to the next file in the list");
const char *nano_gotodir_msg = N_("Go to directory");
#endif
#ifndef DISABLE_COLOR
const char *nano_lint_msg = N_("Invoke the linter, if available");
const char *nano_prevlint_msg = N_("Go to previous linter msg");
const char *nano_nextlint_msg = N_("Go to next linter msg");
#ifndef DISABLE_SPELLER
const char *nano_formatter_msg = N_("Invoke formatter, if available");
#endif
#endif
#endif /* !DISABLE_HELP */
#ifndef DISABLE_HELP
#define IFSCHELP(help) help
#else
#define IFSCHELP(help) ""
#endif
/* Start populating the different menus with functions. */
add_to_funcs(do_help_void, MMOST,
/* TRANSLATORS: Try to keep the following strings at most 10 characters. */
N_("Get Help"), IFSCHELP(nano_help_msg), TOGETHER, VIEW);
add_to_funcs(do_cancel, ((MMOST & ~MMAIN & ~MBROWSER) | MYESNO),
N_("Cancel"), IFSCHELP(nano_cancel_msg), BLANKAFTER, VIEW);
add_to_funcs(do_exit, MMAIN,
exit_tag, IFSCHELP(nano_exit_msg), TOGETHER, VIEW);
/* Remember the entry for Exit, to be able to replace it with Close. */
exitfunc = tailfunc;
#ifndef DISABLE_BROWSER
add_to_funcs(do_exit, MBROWSER,
exit_tag, IFSCHELP(nano_exitbrowser_msg), TOGETHER, VIEW);
#endif
add_to_funcs(do_writeout_void, MMAIN,
N_("Write Out"), IFSCHELP(nano_writeout_msg), TOGETHER, NOVIEW);
#ifndef DISABLE_JUSTIFY
if (!ISSET(RESTRICTED)) {
#else
/* If we can't replace Insert with Justify, show Insert anyway, to
* keep the help items nicely paired also in restricted mode. */
if (TRUE) {
#endif
add_to_funcs(do_insertfile_void, MMAIN,
read_file_tag, IFSCHELP(nano_insert_msg), BLANKAFTER,
/* We allow inserting files in view mode if multibuffer mode
* is switched on, so that we can view multiple files. */
#ifndef DISABLE_MULTIBUFFER
VIEW);
#else
NOVIEW);
#endif
} else {
#ifndef DISABLE_JUSTIFY
add_to_funcs(do_justify_void, MMAIN,
justify_tag, IFSCHELP(nano_justify_msg), BLANKAFTER, NOVIEW);
#endif
}
add_to_funcs(do_search, MMAIN,
whereis_tag, IFSCHELP(nano_whereis_msg), TOGETHER, VIEW);
add_to_funcs(do_replace, MMAIN,
replace_tag, IFSCHELP(nano_replace_msg), TOGETHER, NOVIEW);
#ifndef DISABLE_BROWSER
add_to_funcs(do_search, MBROWSER,
whereis_tag, IFSCHELP(nano_browser_whereis_msg), TOGETHER, VIEW);
add_to_funcs(goto_dir_void, MBROWSER,
N_("Go To Dir"), IFSCHELP(nano_gotodir_msg), BLANKAFTER, VIEW);
#endif
#ifndef DISABLE_HELP
/* The description ("x") and blank_after (0) are irrelevant,
* because the help viewer does not have a help text. */
add_to_funcs(do_exit, MHELP, exit_tag, "x", 0, VIEW);
add_to_funcs(total_refresh, MHELP, refresh_tag, "x", 0, VIEW);
add_to_funcs(do_up_void, MHELP, prev_line_tag, "x", 0, VIEW);
add_to_funcs(do_down_void, MHELP, next_line_tag, "x" , 0, VIEW);
#endif
add_to_funcs(do_cut_text_void, MMAIN,
N_("Cut Text"), IFSCHELP(nano_cut_msg), TOGETHER, NOVIEW);
add_to_funcs(do_uncut_text, MMAIN,
uncut_tag, IFSCHELP(nano_uncut_msg), BLANKAFTER, NOVIEW);
/* Remember the entry for Uncut, to be able to replace it with Unjustify. */
uncutfunc = tailfunc;
if (!ISSET(RESTRICTED)) {
#ifndef DISABLE_JUSTIFY
add_to_funcs(do_justify_void, MMAIN,
justify_tag, IFSCHELP(nano_justify_msg), TOGETHER, NOVIEW);
#endif
#ifndef DISABLE_SPELLER
add_to_funcs(do_spell, MMAIN,
N_("To Spell"), IFSCHELP(nano_spell_msg), TOGETHER, NOVIEW);
#endif
#ifndef DISABLE_COLOR
add_to_funcs(do_linter, MMAIN,
N_("To Linter"), IFSCHELP(nano_lint_msg), TOGETHER, NOVIEW);
#ifndef DISABLE_SPELLER
add_to_funcs(do_formatter, MMAIN,
N_("Formatter"), IFSCHELP(nano_formatter_msg), BLANKAFTER, NOVIEW);
#endif
#endif
}
#ifndef NANO_TINY
add_to_funcs(case_sens_void, MWHEREIS|MREPLACE,
N_("Case Sens"), IFSCHELP(nano_case_msg), TOGETHER, VIEW);
#endif
#ifdef HAVE_REGEX_H
add_to_funcs(regexp_void, MWHEREIS|MREPLACE,
N_("Regexp"), IFSCHELP(nano_regexp_msg), TOGETHER, VIEW);
#endif
#ifndef NANO_TINY
add_to_funcs(backwards_void, MWHEREIS|MREPLACE,
N_("Backwards"), IFSCHELP(nano_reverse_msg), TOGETHER, VIEW);
#endif
add_to_funcs(flip_replace_void, MWHEREIS,
replace_tag, IFSCHELP(nano_replace_msg), BLANKAFTER, VIEW);
add_to_funcs(flip_replace_void, MREPLACE,
N_("No Replace"), IFSCHELP(nano_whereis_msg), BLANKAFTER, VIEW);
#ifndef DISABLE_JUSTIFY
add_to_funcs(do_full_justify, MWHEREIS,
fulljustify_tag, IFSCHELP(nano_fulljustify_msg), TOGETHER, NOVIEW);
#endif
add_to_funcs(do_cursorpos_void, MMAIN,
N_("Cur Pos"), IFSCHELP(nano_cursorpos_msg), TOGETHER, VIEW);
#if defined(DISABLE_COLOR) || !defined(DISABLE_JUSTIFY)
/* Conditionally placing this one here or further on, to keep the
* help items nicely paired in most conditions. */
add_to_funcs(do_gotolinecolumn_void, MMAIN|MWHEREIS,
gotoline_tag, IFSCHELP(nano_gotoline_msg), BLANKAFTER, VIEW);
#endif
add_to_funcs(do_page_up, MMAIN|MHELP,
prev_page_tag, IFSCHELP(nano_prevpage_msg), TOGETHER, VIEW);
add_to_funcs(do_page_down, MMAIN|MHELP,
next_page_tag, IFSCHELP(nano_nextpage_msg), TOGETHER, VIEW);
add_to_funcs(do_first_line, MMAIN|MHELP|MWHEREIS|MREPLACE|MREPLACEWITH|MGOTOLINE,
N_("First Line"), IFSCHELP(nano_firstline_msg), TOGETHER, VIEW);
add_to_funcs(do_last_line, MMAIN|MHELP|MWHEREIS|MREPLACE|MREPLACEWITH|MGOTOLINE,
N_("Last Line"), IFSCHELP(nano_lastline_msg), BLANKAFTER, VIEW);
#ifndef NANO_TINY
add_to_funcs(do_research, MMAIN,
whereis_next_tag, IFSCHELP(nano_whereis_next_msg), TOGETHER, VIEW);
add_to_funcs(do_find_bracket, MMAIN,
N_("To Bracket"), IFSCHELP(nano_bracket_msg), TOGETHER, VIEW);
add_to_funcs(do_mark, MMAIN,
N_("Mark Text"), IFSCHELP(nano_mark_msg), TOGETHER, VIEW);
add_to_funcs(do_copy_text, MMAIN,
N_("Copy Text"), IFSCHELP(nano_copy_msg), BLANKAFTER, NOVIEW);
add_to_funcs(do_indent_void, MMAIN,
N_("Indent Text"), IFSCHELP(nano_indent_msg), TOGETHER, NOVIEW);
add_to_funcs(do_unindent, MMAIN,
N_("Unindent Text"), IFSCHELP(nano_unindent_msg), BLANKAFTER, NOVIEW);
add_to_funcs(do_undo, MMAIN,
N_("Undo"), IFSCHELP(nano_undo_msg), TOGETHER, NOVIEW);
add_to_funcs(do_redo, MMAIN,
N_("Redo"), IFSCHELP(nano_redo_msg), BLANKAFTER, NOVIEW);
#endif /* !NANO_TINY */
add_to_funcs(do_left, MMAIN,
N_("Back"), IFSCHELP(nano_back_msg), TOGETHER, VIEW);
add_to_funcs(do_right, MMAIN,
N_("Forward"), IFSCHELP(nano_forward_msg), TOGETHER, VIEW);
#ifndef DISABLE_BROWSER
add_to_funcs(do_left, MBROWSER,
N_("Back"), IFSCHELP(nano_backfile_msg), TOGETHER, VIEW);
add_to_funcs(do_right, MBROWSER,
N_("Forward"), IFSCHELP(nano_forwardfile_msg), TOGETHER, VIEW);
#endif
#ifndef NANO_TINY
add_to_funcs(do_prev_word_void, MMAIN,
N_("Prev Word"), IFSCHELP(nano_prevword_msg), TOGETHER, VIEW);
add_to_funcs(do_next_word_void, MMAIN,
N_("Next Word"), IFSCHELP(nano_nextword_msg), TOGETHER, VIEW);
#endif
add_to_funcs(do_home, MMAIN,
N_("Home"), IFSCHELP(nano_home_msg), TOGETHER, VIEW);
add_to_funcs(do_end, MMAIN,
N_("End"), IFSCHELP(nano_end_msg), TOGETHER, VIEW);
add_to_funcs(do_up_void, MMAIN|MBROWSER,
prev_line_tag, IFSCHELP(nano_prevline_msg), TOGETHER, VIEW);
add_to_funcs(do_down_void, MMAIN|MBROWSER,
next_line_tag, IFSCHELP(nano_nextline_msg), BLANKAFTER, VIEW);
#ifndef DISABLE_JUSTIFY
add_to_funcs(do_para_begin_void, MMAIN|MWHEREIS,
N_("Beg of Par"), IFSCHELP(nano_parabegin_msg), TOGETHER, VIEW);
add_to_funcs(do_para_end_void, MMAIN|MWHEREIS,
N_("End of Par"), IFSCHELP(nano_paraend_msg), TOGETHER, VIEW);
#endif
#ifndef NANO_TINY
add_to_funcs(do_scroll_up, MMAIN,
N_("Scroll Up"), IFSCHELP(nano_scrollup_msg), TOGETHER, VIEW);
add_to_funcs(do_scroll_down, MMAIN,
N_("Scroll Down"), IFSCHELP(nano_scrolldown_msg), BLANKAFTER, VIEW);
#endif
#ifndef DISABLE_MULTIBUFFER
add_to_funcs(switch_to_prev_buffer_void, MMAIN,
N_("Prev File"), IFSCHELP(nano_prevfile_msg), TOGETHER, VIEW);
add_to_funcs(switch_to_next_buffer_void, MMAIN,
N_("Next File"), IFSCHELP(nano_nextfile_msg), BLANKAFTER, VIEW);
#endif
#if !defined(DISABLE_COLOR) && defined(DISABLE_JUSTIFY)
add_to_funcs(do_gotolinecolumn_void, MMAIN,
gotoline_tag, IFSCHELP(nano_gotoline_msg), BLANKAFTER, VIEW);
#endif
add_to_funcs(do_verbatim_input, MMAIN,
N_("Verbatim"), IFSCHELP(nano_verbatim_msg), TOGETHER, NOVIEW);
add_to_funcs(do_tab, MMAIN,
N_("Tab"), IFSCHELP(nano_tab_msg), TOGETHER, NOVIEW);
add_to_funcs(do_enter, MMAIN,
N_("Enter"), IFSCHELP(nano_enter_msg), BLANKAFTER, NOVIEW);
add_to_funcs(do_delete, MMAIN,
N_("Delete"), IFSCHELP(nano_delete_msg), TOGETHER, NOVIEW);
add_to_funcs(do_backspace, MMAIN,
N_("Backspace"), IFSCHELP(nano_backspace_msg),
#ifndef NANO_TINY
TOGETHER,
#else
BLANKAFTER,
#endif
NOVIEW);
#ifndef NANO_TINY
add_to_funcs(do_cut_prev_word, MMAIN,
/* TRANSLATORS: The next two strings refer to cutting words. */
N_("Cut Left"), IFSCHELP(nano_cut_word_left_msg), TOGETHER, NOVIEW);
add_to_funcs(do_cut_next_word, MMAIN,
N_("Cut Right"), IFSCHELP(nano_cut_word_right_msg), TOGETHER, NOVIEW);
add_to_funcs(do_cut_till_eof, MMAIN,
N_("CutTillEnd"), IFSCHELP(nano_cut_till_eof_msg), BLANKAFTER, NOVIEW);
#endif
#ifndef DISABLE_JUSTIFY
add_to_funcs(do_full_justify, MMAIN,
fulljustify_tag, IFSCHELP(nano_fulljustify_msg), TOGETHER, NOVIEW);
#endif
#ifndef NANO_TINY
add_to_funcs(do_wordlinechar_count, MMAIN,
N_("Word Count"), IFSCHELP(nano_wordcount_msg), TOGETHER, VIEW);
#endif
add_to_funcs(total_refresh, MMAIN,
refresh_tag, IFSCHELP(nano_refresh_msg), TOGETHER, VIEW);
add_to_funcs(do_suspend_void, MMAIN,
N_("Suspend"), IFSCHELP(nano_suspend_msg), BLANKAFTER, VIEW);
#ifdef ENABLE_COMMENT
add_to_funcs(do_comment, MMAIN,
N_("Comment Lines"), IFSCHELP(nano_comment_msg), BLANKAFTER, NOVIEW);
#endif
#ifndef NANO_TINY
add_to_funcs(do_savefile, MMAIN,
N_("Save"), IFSCHELP(nano_savefile_msg), BLANKAFTER, NOVIEW);
add_to_funcs(do_findprevious, MMAIN,
N_("Previous"), IFSCHELP(nano_findprev_msg), TOGETHER, VIEW);
add_to_funcs(do_findnext, MMAIN,
N_("Next"), IFSCHELP(nano_findnext_msg), BLANKAFTER, VIEW);
#endif
#ifndef DISABLE_HISTORIES
add_to_funcs(get_history_older_void,
(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE),
N_("PrevHstory"), IFSCHELP(nano_prev_history_msg), TOGETHER, VIEW);
add_to_funcs(get_history_newer_void,
(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE),
N_("NextHstory"), IFSCHELP(nano_next_history_msg), BLANKAFTER, VIEW);
#endif
#if !defined(DISABLE_COLOR) && defined(DISABLE_JUSTIFY)
add_to_funcs(do_gotolinecolumn_void, MWHEREIS,
gotoline_tag, IFSCHELP(nano_gotoline_msg), BLANKAFTER, VIEW);
#endif
add_to_funcs(gototext_void, MGOTOLINE,
N_("Go To Text"), IFSCHELP(nano_whereis_msg), BLANKAFTER, VIEW);
#ifndef NANO_TINY
add_to_funcs(dos_format_void, MWRITEFILE,
N_("DOS Format"), IFSCHELP(nano_dos_msg), TOGETHER, NOVIEW);
add_to_funcs(mac_format_void, MWRITEFILE,
N_("Mac Format"), IFSCHELP(nano_mac_msg), TOGETHER, NOVIEW);
/* If we're using restricted mode, the Append, Prepend, and Backup toggles
* are disabled. The first and second are not useful as they only allow
* reduplicating the current file, and the third is not allowed as it
* would write to a file not specified on the command line. */
if (!ISSET(RESTRICTED)) {
add_to_funcs(append_void, MWRITEFILE,
N_("Append"), IFSCHELP(nano_append_msg), TOGETHER, NOVIEW);
add_to_funcs(prepend_void, MWRITEFILE,
N_("Prepend"), IFSCHELP(nano_prepend_msg), TOGETHER, NOVIEW);
add_to_funcs(backup_file_void, MWRITEFILE,
N_("Backup File"), IFSCHELP(nano_backup_msg), BLANKAFTER, NOVIEW);
}
/* If we're using restricted mode, file insertion is disabled, and
* thus command execution and the multibuffer toggle have no place. */
if (!ISSET(RESTRICTED)) {
add_to_funcs(flip_execute_void, MINSERTFILE,
N_("Execute Command"), IFSCHELP(nano_execute_msg), TOGETHER, NOVIEW);
add_to_funcs(flip_execute_void, MEXTCMD,
read_file_tag, IFSCHELP(nano_insert_msg), TOGETHER, NOVIEW);
#ifndef DISABLE_MULTIBUFFER
add_to_funcs(new_buffer_void, MINSERTFILE|MEXTCMD,
N_("New Buffer"), IFSCHELP(nano_multibuffer_msg), TOGETHER, NOVIEW);
#endif
}
#endif /* !NANO_TINY */
#ifndef DISABLE_BROWSER
if (!ISSET(RESTRICTED))
add_to_funcs(to_files_void, MWRITEFILE|MINSERTFILE,
N_("To Files"), IFSCHELP(nano_tofiles_msg), TOGETHER, VIEW);
add_to_funcs(do_page_up, MBROWSER,
prev_page_tag, IFSCHELP(nano_prevpage_msg), TOGETHER, VIEW);
add_to_funcs(do_page_down, MBROWSER,
next_page_tag, IFSCHELP(nano_nextpage_msg), TOGETHER, VIEW);
add_to_funcs(do_first_file, (MBROWSER|MWHEREISFILE),
N_("First File"), IFSCHELP(nano_firstfile_msg), TOGETHER, VIEW);
add_to_funcs(do_last_file, (MBROWSER|MWHEREISFILE),
N_("Last File"), IFSCHELP(nano_lastfile_msg), BLANKAFTER, VIEW);
#endif
add_to_funcs(discard_buffer, MWRITEFILE,
N_("Discard buffer"), IFSCHELP(nano_discard_buffer_msg), BLANKAFTER, NOVIEW);
#if !defined(NANO_TINY) && !defined(DISABLE_BROWSER)
add_to_funcs(do_research, MBROWSER,
whereis_next_tag, IFSCHELP(nano_whereis_next_msg), TOGETHER, VIEW);
#endif
#ifndef DISABLE_BROWSER
add_to_funcs(total_refresh, MBROWSER,
refresh_tag, IFSCHELP(nano_browser_refresh_msg), BLANKAFTER, VIEW);
#ifndef NANO_TINY
add_to_funcs(do_prev_word_void, MBROWSER,
N_("Left Column"), IFSCHELP(nano_browser_lefthand_msg), TOGETHER, VIEW);
add_to_funcs(do_next_word_void, MBROWSER,
N_("Right Column"), IFSCHELP(nano_browser_righthand_msg), BLANKAFTER, VIEW);
#endif
#endif
#ifndef DISABLE_COLOR
add_to_funcs(do_page_up, MLINTER,
/* TRANSLATORS: Try to keep the next two strings at most 20 characters. */
N_("Prev Lint Msg"), IFSCHELP(nano_prevlint_msg), TOGETHER, VIEW);
add_to_funcs(do_page_down, MLINTER,
N_("Next Lint Msg"), IFSCHELP(nano_nextlint_msg), TOGETHER, VIEW);
#endif
/* Start associating key combos with functions in specific menus. */
add_to_sclist(MMOST, "^G", do_help_void, 0);
add_to_sclist(MMOST, "F1", do_help_void, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "^X", do_exit, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "F2", do_exit, 0);
add_to_sclist(MMAIN, "^O", do_writeout_void, 0);
add_to_sclist(MMAIN, "F3", do_writeout_void, 0);
add_to_sclist(MMAIN, "^R", do_insertfile_void, 0);
add_to_sclist(MMAIN, "F5", do_insertfile_void, 0);
add_to_sclist(MMAIN, "Ins", do_insertfile_void, 0);
add_to_sclist(MMAIN|MBROWSER, "^W", do_search, 0);
add_to_sclist(MMAIN|MBROWSER, "F6", do_search, 0);
add_to_sclist(MMAIN, "^\\", do_replace, 0);
add_to_sclist(MMAIN, "M-R", do_replace, 0);
add_to_sclist(MMAIN, "F14", do_replace, 0);
add_to_sclist(MMOST, "^K", do_cut_text_void, 0);
add_to_sclist(MMOST, "F9", do_cut_text_void, 0);
add_to_sclist(MMAIN, "^U", do_uncut_text, 0);
add_to_sclist(MMAIN, "F10", do_uncut_text, 0);
#ifndef DISABLE_JUSTIFY
add_to_sclist(MMAIN, "^J", do_justify_void, 0);
add_to_sclist(MMAIN, "F4", do_justify_void, 0);
#endif
#ifndef DISABLE_SPELLER
add_to_sclist(MMAIN, "^T", do_spell, 0);
add_to_sclist(MMAIN, "F12", do_spell, 0);
#else
#ifndef DISABLE_COLOR
add_to_sclist(MMAIN, "^T", do_linter, 0);
add_to_sclist(MMAIN, "F12", do_linter, 0);
#endif
#endif
add_to_sclist(MMAIN, "^C", do_cursorpos_void, 0);
add_to_sclist(MMAIN, "F11", do_cursorpos_void, 0);
add_to_sclist(MMAIN, "^_", do_gotolinecolumn_void, 0);
add_to_sclist(MMAIN, "M-G", do_gotolinecolumn_void, 0);
add_to_sclist(MMAIN, "F13", do_gotolinecolumn_void, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "^Y", do_page_up, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "F7", do_page_up, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "PgUp", do_page_up, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "^V", do_page_down, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "F8", do_page_down, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER|MLINTER, "PgDn", do_page_down, 0);
add_to_sclist(MMAIN|MHELP, "M-\\", do_first_line, 0);
add_to_sclist(MMAIN|MHELP, "M-|", do_first_line, 0);
add_to_sclist(MMAIN|MHELP, "M-/", do_last_line, 0);
add_to_sclist(MMAIN|MHELP, "M-?", do_last_line, 0);
#ifndef NANO_TINY
add_to_sclist(MMAIN|MBROWSER, "M-W", do_research, 0);
add_to_sclist(MMAIN|MBROWSER, "F16", do_research, 0);
add_to_sclist(MMAIN, "M-]", do_find_bracket, 0);
add_to_sclist(MMAIN, "^^", do_mark, 0);
add_to_sclist(MMAIN, "M-A", do_mark, 0);
add_to_sclist(MMAIN, "F15", do_mark, 0);
add_to_sclist(MMAIN, "M-^", do_copy_text, 0);
add_to_sclist(MMAIN, "M-6", do_copy_text, 0);
add_to_sclist(MMAIN, "M-}", do_indent_void, 0);
add_to_sclist(MMAIN, "M-{", do_unindent, 0);
add_to_sclist(MMAIN, "M-U", do_undo, 0);
add_to_sclist(MMAIN, "M-E", do_redo, 0);
#endif
#ifdef ENABLE_COMMENT
add_to_sclist(MMAIN, "M-3", do_comment, 0);
#endif
add_to_sclist(MMOST, "^B", do_left, 0);
add_to_sclist(MMOST, "Left", do_left, 0);
add_to_sclist(MMOST, "^F", do_right, 0);
add_to_sclist(MMOST, "Right", do_right, 0);
#ifndef NANO_TINY
add_to_sclist(MMOST, "M-Space", do_prev_word_void, 0);
add_to_sclist(MMOST, "^Space", do_next_word_void, 0);
#endif
add_to_sclist((MMOST & ~MBROWSER), "^A", do_home, 0);
add_to_sclist((MMOST & ~MBROWSER), "Home", do_home, 0);
add_to_sclist((MMOST & ~MBROWSER), "^E", do_end, 0);
add_to_sclist((MMOST & ~MBROWSER), "End", do_end, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "^P", do_up_void, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "Up", do_up_void, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "^N", do_down_void, 0);
add_to_sclist(MMAIN|MHELP|MBROWSER, "Down", do_down_void, 0);
#ifndef DISABLE_JUSTIFY
add_to_sclist(MMAIN, "M-(", do_para_begin_void, 0);
add_to_sclist(MMAIN, "M-9", do_para_begin_void, 0);
add_to_sclist(MMAIN, "M-)", do_para_end_void, 0);
add_to_sclist(MMAIN, "M-0", do_para_end_void, 0);
#endif
#ifndef NANO_TINY
add_to_sclist(MMAIN, "M--", do_scroll_up, 0);
add_to_sclist(MMAIN, "M-_", do_scroll_up, 0);
add_to_sclist(MMAIN, "M-+", do_scroll_down, 0);
add_to_sclist(MMAIN, "M-=", do_scroll_down, 0);
#endif
#ifndef DISABLE_MULTIBUFFER
add_to_sclist(MMAIN, "M-<", switch_to_prev_buffer_void, 0);
add_to_sclist(MMAIN, "M-,", switch_to_prev_buffer_void, 0);
add_to_sclist(MMAIN, "M->", switch_to_next_buffer_void, 0);
add_to_sclist(MMAIN, "M-.", switch_to_next_buffer_void, 0);
#endif
add_to_sclist(MMOST, "M-V", do_verbatim_input, 0);
#ifndef NANO_TINY
add_to_sclist(MMAIN, "M-T", do_cut_till_eof, 0);
add_to_sclist(MMAIN, "M-D", do_wordlinechar_count, 0);
#endif
#ifndef DISABLE_JUSTIFY
add_to_sclist(MMAIN|MWHEREIS, "M-J", do_full_justify, 0);
#endif
add_to_sclist(MMAIN|MHELP, "^L", total_refresh, 0);
add_to_sclist(MMAIN, "^Z", do_suspend_void, 0);
#ifndef NANO_TINY
/* Group of "Appearance" toggles. */
add_to_sclist(MMAIN, "M-X", do_toggle_void, NO_HELP);
add_to_sclist(MMAIN, "M-C", do_toggle_void, CONST_UPDATE);
add_to_sclist(MMAIN, "M-O", do_toggle_void, MORE_SPACE);
add_to_sclist(MMAIN, "M-S", do_toggle_void, SMOOTH_SCROLL);
add_to_sclist(MMAIN, "M-$", do_toggle_void, SOFTWRAP);
add_to_sclist(MMAIN, "M-P", do_toggle_void, WHITESPACE_DISPLAY);
#ifndef DISABLE_COLOR
add_to_sclist(MMAIN, "M-Y", do_toggle_void, NO_COLOR_SYNTAX);
#endif
/* Group of "Editing-behavior" toggles. */
add_to_sclist(MMAIN, "M-H", do_toggle_void, SMART_HOME);
add_to_sclist(MMAIN, "M-I", do_toggle_void, AUTOINDENT);
add_to_sclist(MMAIN, "M-K", do_toggle_void, CUT_TO_END);
#ifndef DISABLE_WRAPPING
add_to_sclist(MMAIN, "M-L", do_toggle_void, NO_WRAP);
#endif
add_to_sclist(MMAIN, "M-Q", do_toggle_void, TABS_TO_SPACES);
/* Group of "Peripheral-feature" toggles. */
add_to_sclist(MMAIN, "M-B", do_toggle_void, BACKUP_FILE);
#ifndef DISABLE_MULTIBUFFER
add_to_sclist(MMAIN, "M-F", do_toggle_void, MULTIBUFFER);
#endif
#ifndef DISABLE_MOUSE
add_to_sclist(MMAIN, "M-M", do_toggle_void, USE_MOUSE);
#endif
add_to_sclist(MMAIN, "M-N", do_toggle_void, NO_CONVERT);
add_to_sclist(MMAIN, "M-Z", do_toggle_void, SUSPEND);
#endif /* !NANO_TINY */
add_to_sclist(MMAIN, "^Q", xon_complaint, 0);
add_to_sclist(MMAIN, "^S", xoff_complaint, 0);
add_to_sclist(((MMOST & ~MMAIN & ~MBROWSER) | MYESNO), "^C", do_cancel, 0);
#ifndef NANO_TINY
add_to_sclist(MWHEREIS|MREPLACE, "M-B", backwards_void, 0);
add_to_sclist(MWHEREIS|MREPLACE, "M-C", case_sens_void, 0);
#endif
add_to_sclist(MWHEREIS|MREPLACE, "M-R", regexp_void, 0);
add_to_sclist(MWHEREIS|MREPLACE, "^R", flip_replace_void, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MGOTOLINE, "^Y", do_first_line, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MGOTOLINE, "^V", do_last_line, 0);
#ifndef DISABLE_JUSTIFY
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH, "^W", do_para_begin_void, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH, "^O", do_para_end_void, 0);
#endif
add_to_sclist(MWHEREIS, "^T", do_gotolinecolumn_void, 0);
add_to_sclist(MGOTOLINE, "^T", gototext_void, 0);
#ifndef DISABLE_HISTORIES
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE, "^P", get_history_older_void, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE, "Up", get_history_older_void, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE, "^N", get_history_newer_void, 0);
add_to_sclist(MWHEREIS|MREPLACE|MREPLACEWITH|MWHEREISFILE, "Down", get_history_newer_void, 0);
#endif
#ifndef DISABLE_BROWSER
add_to_sclist(MWHEREISFILE, "^Y", do_first_file, 0);
add_to_sclist(MWHEREISFILE, "^V", do_last_file, 0);
add_to_sclist(MBROWSER|MWHEREISFILE, "M-\\", do_first_file, 0);
add_to_sclist(MBROWSER|MWHEREISFILE, "M-|", do_first_file, 0);
add_to_sclist(MBROWSER|MWHEREISFILE, "M-/", do_last_file, 0);
add_to_sclist(MBROWSER|MWHEREISFILE, "M-?", do_last_file, 0);
add_to_sclist(MBROWSER, "Home", do_first_file, 0);
add_to_sclist(MBROWSER, "End", do_last_file, 0);
add_to_sclist(MBROWSER, "^_", goto_dir_void, 0);
add_to_sclist(MBROWSER, "M-G", goto_dir_void, 0);
add_to_sclist(MBROWSER, "F13", goto_dir_void, 0);
add_to_sclist(MBROWSER, "^L", total_refresh, 0);
#endif
if (ISSET(TEMP_FILE))
add_to_sclist(MWRITEFILE, "^Q", discard_buffer, 0);
add_to_sclist(MWRITEFILE, "M-D", dos_format_void, 0);
add_to_sclist(MWRITEFILE, "M-M", mac_format_void, 0);
if (!ISSET(RESTRICTED)) {
/* Don't allow Appending, Prepending, nor Backups in restricted mode. */
add_to_sclist(MWRITEFILE, "M-A", append_void, 0);
add_to_sclist(MWRITEFILE, "M-P", prepend_void, 0);
add_to_sclist(MWRITEFILE, "M-B", backup_file_void, 0);
#ifndef DISABLE_BROWSER
add_to_sclist(MWRITEFILE|MINSERTFILE, "^T", to_files_void, 0);
#endif
add_to_sclist(MINSERTFILE|MEXTCMD, "^X", flip_execute_void, 0);
add_to_sclist(MINSERTFILE|MEXTCMD, "M-F", new_buffer_void, 0);
}
add_to_sclist(MHELP|MBROWSER, "^C", do_exit, 0);
/* Allow exiting from the file browser and the help viewer with
* the same key as they were entered. */
#ifndef DISABLE_BROWSER
add_to_sclist(MBROWSER, "^T", do_exit, 0);
#endif
#ifndef DISABLE_HELP
add_to_sclist(MHELP, "^G", do_exit, 0);
add_to_sclist(MHELP, "Home", do_first_line, 0);
add_to_sclist(MHELP, "End", do_last_line, 0);
#endif
add_to_sclist(MMOST, "^I", do_tab, 0);
add_to_sclist(MMOST, "Tab", do_tab, 0);
add_to_sclist(MMOST, "^M", do_enter, 0);
add_to_sclist(MMOST, "Enter", do_enter, 0);
add_to_sclist(MMOST, "^D", do_delete, 0);
add_to_sclist(MMOST, "Del", do_delete, 0);
add_to_sclist(MMOST, "^H", do_backspace, 0);
add_to_sclist(MMOST, "Bsp", do_backspace, 0);
#ifdef DEBUG
print_sclist();
#endif
}
#ifndef DISABLE_COLOR
void set_lint_or_format_shortcuts(void)
{
#ifndef DISABLE_SPELLER
if (openfile->syntax->formatter) {
replace_scs_for(do_spell, do_formatter);
replace_scs_for(do_linter, do_formatter);
} else {
replace_scs_for(do_spell, do_linter);
replace_scs_for(do_formatter, do_linter);
}
#endif
}
void set_spell_shortcuts(void)
{
#ifndef DISABLE_SPELLER
replace_scs_for(do_formatter, do_spell);
replace_scs_for(do_linter, do_spell);
#endif
}
#endif /* !DISABLE_COLOR */
const subnfunc *sctofunc(const sc *s)
{
subnfunc *f = allfuncs;
while (f != NULL && f->scfunc != s->scfunc)
f = f->next;
return f;
}
#ifndef NANO_TINY
/* Now let's come up with a single (hopefully) function to get a string
* for each flag. */
const char *flagtostr(int flag)
{
switch (flag) {
case NO_HELP:
/* TRANSLATORS: The next seventeen strings are toggle descriptions;
* they are best kept shorter than 40 characters, but may be longer. */
return N_("Help mode");
case CONST_UPDATE:
return N_("Constant cursor position display");
case MORE_SPACE:
return N_("Use of one more line for editing");
case SMOOTH_SCROLL:
return N_("Smooth scrolling");
case SOFTWRAP:
return N_("Soft wrapping of overlong lines");
case WHITESPACE_DISPLAY:
return N_("Whitespace display");
case NO_COLOR_SYNTAX:
return N_("Color syntax highlighting");
case SMART_HOME:
return N_("Smart home key");
case AUTOINDENT:
return N_("Auto indent");
case CUT_TO_END:
return N_("Cut to end");
case NO_WRAP:
return N_("Hard wrapping of overlong lines");
case TABS_TO_SPACES:
return N_("Conversion of typed tabs to spaces");
case BACKUP_FILE:
return N_("Backup files");
case MULTIBUFFER:
return N_("Reading file into separate buffer");
case USE_MOUSE:
return N_("Mouse support");
case NO_CONVERT:
return N_("No conversion from DOS/Mac format");
case SUSPEND:
return N_("Suspension");
default:
return "?????";
}
}
#endif /* !NANO_TINY */
#ifndef DISABLE_NANORC
/* Interpret a function string given in the rc file, and return a
* shortcut struct with the corresponding function filled in. */
sc *strtosc(const char *input)
{
sc *s;
s = (sc *)nmalloc(sizeof(sc));
#ifndef DISABLE_HELP
if (!strcasecmp(input, "help"))
s->scfunc = do_help_void;
else
#endif
if (!strcasecmp(input, "cancel"))
s->scfunc = do_cancel;
else if (!strcasecmp(input, "exit"))
s->scfunc = do_exit;
else if (!strcasecmp(input, "discardbuffer"))
s->scfunc = discard_buffer;
else if (!strcasecmp(input, "writeout"))
s->scfunc = do_writeout_void;
#ifndef NANO_TINY
else if (!strcasecmp(input, "savefile"))
s->scfunc = do_savefile;
#endif
else if (!strcasecmp(input, "insert"))
s->scfunc = do_insertfile_void;
else if (!strcasecmp(input, "whereis"))
s->scfunc = do_search;
#ifndef NANO_TINY
else if (!strcasecmp(input, "searchagain") ||
!strcasecmp(input, "research"))
s->scfunc = do_research;
else if (!strcasecmp(input, "findprevious"))
s->scfunc = do_findprevious;
else if (!strcasecmp(input, "findnext"))
s->scfunc = do_findnext;
#endif
else if (!strcasecmp(input, "replace"))
s->scfunc = do_replace;
else if (!strcasecmp(input, "cut"))
s->scfunc = do_cut_text_void;
else if (!strcasecmp(input, "uncut"))
s->scfunc = do_uncut_text;
#ifndef NANO_TINY
else if (!strcasecmp(input, "cutrestoffile"))
s->scfunc = do_cut_till_eof;
else if (!strcasecmp(input, "copytext"))
s->scfunc = do_copy_text;
else if (!strcasecmp(input, "mark"))
s->scfunc = do_mark;
#endif
#ifndef DISABLE_SPELLER
else if (!strcasecmp(input, "tospell") ||
!strcasecmp(input, "speller"))
s->scfunc = do_spell;
#endif
#ifndef DISABLE_COLOR
else if (!strcasecmp(input, "linter"))
s->scfunc = do_linter;
#endif
else if (!strcasecmp(input, "curpos") ||
!strcasecmp(input, "cursorpos"))
s->scfunc = do_cursorpos_void;
else if (!strcasecmp(input, "gotoline"))
s->scfunc = do_gotolinecolumn_void;
#ifndef DISABLE_JUSTIFY
else if (!strcasecmp(input, "justify"))
s->scfunc = do_justify_void;
else if (!strcasecmp(input, "fulljustify"))
s->scfunc = do_full_justify;
else if (!strcasecmp(input, "beginpara"))
s->scfunc = do_para_begin_void;
else if (!strcasecmp(input, "endpara"))
s->scfunc = do_para_end_void;
#endif
#ifdef ENABLE_COMMENT
else if (!strcasecmp(input, "comment"))
s->scfunc = do_comment;
#endif
#ifndef NANO_TINY
else if (!strcasecmp(input, "indent"))
s->scfunc = do_indent_void;
else if (!strcasecmp(input, "unindent"))
s->scfunc = do_unindent;
else if (!strcasecmp(input, "scrollup"))
s->scfunc = do_scroll_up;
else if (!strcasecmp(input, "scrolldown"))
s->scfunc = do_scroll_down;
else if (!strcasecmp(input, "prevword"))
s->scfunc = do_prev_word_void;
else if (!strcasecmp(input, "nextword"))
s->scfunc = do_next_word_void;
else if (!strcasecmp(input, "cutwordleft"))
s->scfunc = do_cut_prev_word;
else if (!strcasecmp(input, "cutwordright"))
s->scfunc = do_cut_next_word;
else if (!strcasecmp(input, "findbracket"))
s->scfunc = do_find_bracket;
else if (!strcasecmp(input, "wordcount"))
s->scfunc = do_wordlinechar_count;
else if (!strcasecmp(input, "undo"))
s->scfunc = do_undo;
else if (!strcasecmp(input, "redo"))
s->scfunc = do_redo;
#endif
else if (!strcasecmp(input, "left") ||
!strcasecmp(input, "back"))
s->scfunc = do_left;
else if (!strcasecmp(input, "right") ||
!strcasecmp(input, "forward"))
s->scfunc = do_right;
else if (!strcasecmp(input, "up") ||
!strcasecmp(input, "prevline"))
s->scfunc = do_up_void;
else if (!strcasecmp(input, "down") ||
!strcasecmp(input, "nextline"))
s->scfunc = do_down_void;
else if (!strcasecmp(input, "home"))
s->scfunc = do_home;
else if (!strcasecmp(input, "end"))
s->scfunc = do_end;
else if (!strcasecmp(input, "pageup") ||
!strcasecmp(input, "prevpage"))
s->scfunc = do_page_up;
else if (!strcasecmp(input, "pagedown") ||
!strcasecmp(input, "nextpage"))
s->scfunc = do_page_down;
else if (!strcasecmp(input, "firstline"))
s->scfunc = do_first_line;
else if (!strcasecmp(input, "lastline"))
s->scfunc = do_last_line;
#ifndef DISABLE_MULTIBUFFER
else if (!strcasecmp(input, "prevbuf"))
s->scfunc = switch_to_prev_buffer_void;
else if (!strcasecmp(input, "nextbuf"))
s->scfunc = switch_to_next_buffer_void;
#endif
else if (!strcasecmp(input, "verbatim"))
s->scfunc = do_verbatim_input;
else if (!strcasecmp(input, "tab"))
s->scfunc = do_tab;
else if (!strcasecmp(input, "enter"))
s->scfunc = do_enter;
else if (!strcasecmp(input, "delete"))
s->scfunc = do_delete;
else if (!strcasecmp(input, "backspace"))
s->scfunc = do_backspace;
else if (!strcasecmp(input, "refresh"))
s->scfunc = total_refresh;
else if (!strcasecmp(input, "suspend"))
s->scfunc = do_suspend_void;
else if (!strcasecmp(input, "casesens"))
s->scfunc = case_sens_void;
#ifndef NANO_TINY
else if (!strcasecmp(input, "regexp") ||
!strcasecmp(input, "regex"))
s->scfunc = regexp_void;
else if (!strcasecmp(input, "backwards"))
s->scfunc = backwards_void;
#endif
else if (!strcasecmp(input, "flipreplace") ||
!strcasecmp(input, "dontreplace"))
s->scfunc = flip_replace_void;
else if (!strcasecmp(input, "gototext"))
s->scfunc = gototext_void;
#ifndef DISABLE_HISTORIES
else if (!strcasecmp(input, "prevhistory"))
s->scfunc = get_history_older_void;
else if (!strcasecmp(input, "nexthistory"))
s->scfunc = get_history_newer_void;
#endif
else if (!strcasecmp(input, "dosformat"))
s->scfunc = dos_format_void;
else if (!strcasecmp(input, "macformat"))
s->scfunc = mac_format_void;
else if (!strcasecmp(input, "append"))
s->scfunc = append_void;
else if (!strcasecmp(input, "prepend"))
s->scfunc = prepend_void;
else if (!strcasecmp(input, "backup"))
s->scfunc = backup_file_void;
#ifndef ENABLE_TINY
else if (!strcasecmp(input, "flipexecute"))
s->scfunc = flip_execute_void;
#endif
#ifndef DISABLE_MULTIBUFFER
else if (!strcasecmp(input, "flipnewbuffer") ||
!strcasecmp(input, "newbuffer"))
s->scfunc = new_buffer_void;
#endif
#ifndef DISABLE_BROWSER
else if (!strcasecmp(input, "tofiles") ||
!strcasecmp(input, "browser"))
s->scfunc = to_files_void;
else if (!strcasecmp(input, "gotodir"))
s->scfunc = goto_dir_void;
else if (!strcasecmp(input, "firstfile"))
s->scfunc = do_first_file;
else if (!strcasecmp(input, "lastfile"))
s->scfunc = do_last_file;
#endif
#ifndef NANO_TINY
else {
s->scfunc = do_toggle_void;
if (!strcasecmp(input, "nohelp"))
s->toggle = NO_HELP;
else if (!strcasecmp(input, "constupdate"))
s->toggle = CONST_UPDATE;
else if (!strcasecmp(input, "morespace"))
s->toggle = MORE_SPACE;
else if (!strcasecmp(input, "smoothscroll"))
s->toggle = SMOOTH_SCROLL;
else if (!strcasecmp(input, "softwrap"))
s->toggle = SOFTWRAP;
else if (!strcasecmp(input, "whitespacedisplay"))
s->toggle = WHITESPACE_DISPLAY;
#ifndef DISABLE_COLOR
else if (!strcasecmp(input, "nosyntax"))
s->toggle = NO_COLOR_SYNTAX;
#endif
else if (!strcasecmp(input, "smarthome"))
s->toggle = SMART_HOME;
else if (!strcasecmp(input, "autoindent"))
s->toggle = AUTOINDENT;
else if (!strcasecmp(input, "cuttoend"))
s->toggle = CUT_TO_END;
#ifndef DISABLE_WRAPPING
else if (!strcasecmp(input, "nowrap"))
s->toggle = NO_WRAP;
#endif
else if (!strcasecmp(input, "tabstospaces"))
s->toggle = TABS_TO_SPACES;
else if (!strcasecmp(input, "backupfile"))
s->toggle = BACKUP_FILE;
#ifndef DISABLE_MULTIBUFFER
else if (!strcasecmp(input, "multibuffer"))
s->toggle = MULTIBUFFER;
#endif
#ifndef DISABLE_MOUSE
else if (!strcasecmp(input, "mouse"))
s->toggle = USE_MOUSE;
#endif
else if (!strcasecmp(input, "noconvert"))
s->toggle = NO_CONVERT;
else if (!strcasecmp(input, "suspendenable"))
s->toggle = SUSPEND;
#endif /* !NANO_TINY */
else {
free(s);
return NULL;
}
#ifndef NANO_TINY
}
#endif
return s;
}
/* Interpret a menu name and return the corresponding menu flag. */
int strtomenu(const char *input)
{
if (!strcasecmp(input, "all"))
return (MMOST|MHELP|MYESNO);
else if (!strcasecmp(input, "main"))
return MMAIN;
else if (!strcasecmp(input, "search"))
return MWHEREIS;
else if (!strcasecmp(input, "replace"))
return MREPLACE;
else if (!strcasecmp(input, "replace2") ||
!strcasecmp(input, "replacewith"))
return MREPLACEWITH;
else if (!strcasecmp(input, "gotoline"))
return MGOTOLINE;
else if (!strcasecmp(input, "writeout"))
return MWRITEFILE;
else if (!strcasecmp(input, "insert"))
return MINSERTFILE;
else if (!strcasecmp(input, "externalcmd") ||
!strcasecmp(input, "extcmd"))
return MEXTCMD;
#ifndef DISABLE_HELP
else if (!strcasecmp(input, "help"))
return MHELP;
#endif
#ifndef DISABLE_SPELLER
else if (!strcasecmp(input, "spell"))
return MSPELL;
#endif
else if (!strcasecmp(input, "linter"))
return MLINTER;
#ifndef DISABLE_BROWSER
else if (!strcasecmp(input, "browser"))
return MBROWSER;
else if (!strcasecmp(input, "whereisfile"))
return MWHEREISFILE;
else if (!strcasecmp(input, "gotodir"))
return MGOTODIR;
#endif
return -1;
}
#endif /* !DISABLE_NANORC */
#ifdef DEBUG
/* This function is used to gracefully return all the memory we've used.
* It should be called just before calling exit(). Practically, the
* only effect is to cause a segmentation fault if the various data
* structures got bolloxed earlier. Thus, we don't bother having this
* function unless debugging is turned on. */
void thanks_for_all_the_fish(void)
{
delwin(topwin);
delwin(edit);
delwin(bottomwin);
#ifndef DISABLE_JUSTIFY
free(quotestr);
#ifdef HAVE_REGEX_H
regfree("ereg);
free(quoteerr);
#endif
#endif
#ifndef NANO_TINY
free(backup_dir);
#endif
#ifndef DISABLE_OPERATINGDIR
free(operating_dir);
free(full_operating_dir);
#endif
free(answer);
free(last_search);
free(present_path);
#ifndef DISABLE_SPELLER
free(alt_speller);
#endif
free_filestruct(cutbuffer);
#ifndef DISABLE_JUSTIFY
free_filestruct(jusbuffer);
#endif
/* Free the memory associated with each open file buffer. */
while (openfile != openfile->next) {
openfile = openfile->next;
delete_opennode(openfile->prev);
}
delete_opennode(openfile);
#ifndef DISABLE_COLOR
free(syntaxstr);
while (syntaxes != NULL) {
syntaxtype *sint = syntaxes;
syntaxes = syntaxes->next;
free(sint->name);
free(sint->linter);
free(sint->formatter);
while (sint->extensions != NULL) {
regexlisttype *item = sint->extensions;
sint->extensions = sint->extensions->next;
free(item->full_regex);
free(item);
}
while (sint->headers != NULL) {
regexlisttype *item = sint->headers;
sint->headers = sint->headers->next;
free(item->full_regex);
free(item);
}
while (sint->magics != NULL) {
regexlisttype *item = sint->magics;
sint->magics = sint->magics->next;
free(item->full_regex);
free(item);
}
while (sint->color != NULL) {
colortype *ink = sint->color;
sint->color = sint->color->next;
free(ink->start_regex);
if (ink->start != NULL) {
regfree(ink->start);
free(ink->start);
}
free(ink->end_regex);
if (ink->end != NULL) {
regfree(ink->end);
free(ink->end);
}
free(ink);
}
free(sint);
}
#endif /* !DISABLE_COLOR */
#ifndef DISABLE_HISTORIES
/* Free the search and replace history lists. */
free_filestruct(searchage);
free_filestruct(replaceage);
#endif
/* Free the list of functions. */
while (allfuncs != NULL) {
subnfunc *f = allfuncs;
allfuncs = allfuncs->next;
free(f);
}
/* Free the list of shortcuts. */
while (sclist != NULL) {
sc *s = sclist;
sclist = sclist->next;
free(s);
}
#ifndef DISABLE_NANORC
free(homedir);
#endif
}
#endif /* DEBUG */
| 33.654628
| 108
| 0.695352
|
faff6d1b2285e5faabe1809e57c47a9c19f826a7
| 1,922
|
rb
|
Ruby
|
ee/spec/requests/api/graphql/mutations/app_sec/fuzzing/api/ci_configuration/create_spec.rb
|
mhuryanov/gitlab
|
3c50a67be2d6b6322a00d360c59629abf7bc5888
|
[
"MIT"
] | null | null | null |
ee/spec/requests/api/graphql/mutations/app_sec/fuzzing/api/ci_configuration/create_spec.rb
|
mhuryanov/gitlab
|
3c50a67be2d6b6322a00d360c59629abf7bc5888
|
[
"MIT"
] | null | null | null |
ee/spec/requests/api/graphql/mutations/app_sec/fuzzing/api/ci_configuration/create_spec.rb
|
mhuryanov/gitlab
|
3c50a67be2d6b6322a00d360c59629abf7bc5888
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'CreateApiFuzzingCiConfiguration' do
include GraphqlHelpers
let_it_be(:project) { create(:project) }
let_it_be(:user) { create(:user) }
let(:mutation) do
%(
mutation {
apiFuzzingCiConfigurationCreate(input: {
apiSpecificationFile: "https://api.gov/api_spec",
authPassword: "$PASSWORD",
authUsername: "$USERNAME",
projectPath: "#{project.full_path}",
scanMode: OPENAPI,
scanProfile: "Quick-10",
target: "https://api.gov"
}) {
configurationYaml
errors
gitlabCiYamlEditPath
}
}
)
end
before_all do
project.add_developer(user)
end
before do
stub_licensed_features(security_dashboard: true)
end
it 'returns a YAML snippet that can be used to configure API fuzzing scans for the project' do
post_graphql(mutation, current_user: user)
expect(response).to have_gitlab_http_status(:ok)
expect(graphql_errors).to be_nil
mutation_response = graphql_mutation_response(:api_fuzzing_ci_configuration_create)
yaml = mutation_response['configurationYaml']
gitlab_ci_yml_edit_path = mutation_response['gitlabCiYamlEditPath']
errors = mutation_response['errors']
aggregate_failures do
expect(errors).to be_empty
expect(gitlab_ci_yml_edit_path).to eq(project_ci_pipeline_editor_path(project))
expect(Psych.load(yaml)).to eq({
'stages' => ['fuzz'],
'include' => [{ 'template' => 'API-Fuzzing.gitlab-ci.yml' }],
'variables' => {
'FUZZAPI_HTTP_PASSWORD' => '$PASSWORD',
'FUZZAPI_HTTP_USERNAME' => '$USERNAME',
'FUZZAPI_OPENAPI' => 'https://api.gov/api_spec',
'FUZZAPI_PROFILE' => 'Quick-10',
'FUZZAPI_TARGET_URL' => 'https://api.gov'
}
})
end
end
end
| 28.686567
| 96
| 0.646202
|
7f6446e3f58faa3557f5094f7f31db84d857cad0
| 4,273
|
rs
|
Rust
|
third_party/rust_crates/vendor/tokio/src/io/driver/scheduled_io.rs
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 210
|
2019-02-05T12:45:09.000Z
|
2022-03-28T07:59:06.000Z
|
tokio/src/io/driver/scheduled_io.rs
|
PirateDragon/tokio
|
282b00cbe888a96669877ce70662fba87e8c0e3c
|
[
"MIT"
] | 56
|
2021-06-03T03:16:25.000Z
|
2022-03-20T01:07:44.000Z
|
tokio/src/io/driver/scheduled_io.rs
|
PirateDragon/tokio
|
282b00cbe888a96669877ce70662fba87e8c0e3c
|
[
"MIT"
] | 73
|
2019-03-06T18:55:23.000Z
|
2022-03-26T12:04:51.000Z
|
use crate::loom::future::AtomicWaker;
use crate::loom::sync::atomic::AtomicUsize;
use crate::util::bit;
use crate::util::slab::{Address, Entry, Generation};
use std::sync::atomic::Ordering::{AcqRel, Acquire, SeqCst};
#[derive(Debug)]
pub(crate) struct ScheduledIo {
readiness: AtomicUsize,
pub(crate) reader: AtomicWaker,
pub(crate) writer: AtomicWaker,
}
const PACK: bit::Pack = bit::Pack::most_significant(Generation::WIDTH);
impl Entry for ScheduledIo {
fn generation(&self) -> Generation {
unpack_generation(self.readiness.load(SeqCst))
}
fn reset(&self, generation: Generation) -> bool {
let mut current = self.readiness.load(Acquire);
loop {
if unpack_generation(current) != generation {
return false;
}
let next = PACK.pack(generation.next().to_usize(), 0);
match self
.readiness
.compare_exchange(current, next, AcqRel, Acquire)
{
Ok(_) => break,
Err(actual) => current = actual,
}
}
drop(self.reader.take_waker());
drop(self.writer.take_waker());
true
}
}
impl Default for ScheduledIo {
fn default() -> ScheduledIo {
ScheduledIo {
readiness: AtomicUsize::new(0),
reader: AtomicWaker::new(),
writer: AtomicWaker::new(),
}
}
}
impl ScheduledIo {
#[cfg(all(test, loom))]
/// Returns the current readiness value of this `ScheduledIo`, if the
/// provided `token` is still a valid access.
///
/// # Returns
///
/// If the given token's generation no longer matches the `ScheduledIo`'s
/// generation, then the corresponding IO resource has been removed and
/// replaced with a new resource. In that case, this method returns `None`.
/// Otherwise, this returns the current readiness.
pub(crate) fn get_readiness(&self, address: Address) -> Option<usize> {
let ready = self.readiness.load(Acquire);
if unpack_generation(ready) != address.generation() {
return None;
}
Some(ready & !PACK.mask())
}
/// Sets the readiness on this `ScheduledIo` by invoking the given closure on
/// the current value, returning the previous readiness value.
///
/// # Arguments
/// - `token`: the token for this `ScheduledIo`.
/// - `f`: a closure returning a new readiness value given the previous
/// readiness.
///
/// # Returns
///
/// If the given token's generation no longer matches the `ScheduledIo`'s
/// generation, then the corresponding IO resource has been removed and
/// replaced with a new resource. In that case, this method returns `Err`.
/// Otherwise, this returns the previous readiness.
pub(crate) fn set_readiness(
&self,
address: Address,
f: impl Fn(usize) -> usize,
) -> Result<usize, ()> {
let generation = address.generation();
let mut current = self.readiness.load(Acquire);
loop {
// Check that the generation for this access is still the current
// one.
if unpack_generation(current) != generation {
return Err(());
}
// Mask out the generation bits so that the modifying function
// doesn't see them.
let current_readiness = current & mio::Ready::all().as_usize();
let new = f(current_readiness);
debug_assert!(
new <= !PACK.max_value(),
"new readiness value would overwrite generation bits!"
);
match self.readiness.compare_exchange(
current,
PACK.pack(generation.to_usize(), new),
AcqRel,
Acquire,
) {
Ok(_) => return Ok(current),
// we lost the race, retry!
Err(actual) => current = actual,
}
}
}
}
impl Drop for ScheduledIo {
fn drop(&mut self) {
self.writer.wake();
self.reader.wake();
}
}
fn unpack_generation(src: usize) -> Generation {
Generation::new(PACK.unpack(src))
}
| 30.091549
| 81
| 0.572198
|
14a0256cf01e81d65e1c68a2c27d776aecf7aca1
| 424
|
ps1
|
PowerShell
|
Examples/Example-Diagrams/Example-FontsAwesome.ps1
|
Splaxi/PSWriteHTML
|
c9a01afb61ebb418879babda8dd7337784c237c2
|
[
"MIT"
] | null | null | null |
Examples/Example-Diagrams/Example-FontsAwesome.ps1
|
Splaxi/PSWriteHTML
|
c9a01afb61ebb418879babda8dd7337784c237c2
|
[
"MIT"
] | null | null | null |
Examples/Example-Diagrams/Example-FontsAwesome.ps1
|
Splaxi/PSWriteHTML
|
c9a01afb61ebb418879babda8dd7337784c237c2
|
[
"MIT"
] | null | null | null |
Import-Module .\PSWriteHTML.psd1 -Force
New-HTML -TitleText 'My diagram' -Online -FilePath $PSScriptRoot\Example-FontsAwesome.html {
New-HTMLDiagram {
New-DiagramNode -Label 'IconBrands example' -IconBrands accessible-icon
New-DiagramNode -Label 'IconRegular example' -IconRegular address-card
New-DiagramNode -Label 'IconSolid example' -IconSolid air-freshener
} -DisableLoader
} -ShowHTML
| 47.111111
| 92
| 0.745283
|
c6a30bc00c8e796fd0e1efea84d5697201536cc2
| 218
|
rb
|
Ruby
|
db/migrate/20170516153801_remove_hike_ratings_tables.rb
|
BenWilliams7/hike_app_rb
|
a360016504f3eeb3c0ee685134dc91d079d4164c
|
[
"Unlicense"
] | null | null | null |
db/migrate/20170516153801_remove_hike_ratings_tables.rb
|
BenWilliams7/hike_app_rb
|
a360016504f3eeb3c0ee685134dc91d079d4164c
|
[
"Unlicense"
] | null | null | null |
db/migrate/20170516153801_remove_hike_ratings_tables.rb
|
BenWilliams7/hike_app_rb
|
a360016504f3eeb3c0ee685134dc91d079d4164c
|
[
"Unlicense"
] | null | null | null |
class RemoveHikeRatingsTables < ActiveRecord::Migration[5.1]
def change
remove_column :hikes, :rating_id
add_column :hikes, :difficulty, :string
drop_table :ratings
drop_table :hike_ratings
end
end
| 24.222222
| 60
| 0.747706
|
caef1471e610ea4db1e412140adff15fe2fd9e1e
| 3,214
|
rb
|
Ruby
|
spec/engine/common/impression_manager_spec.rb
|
snilesh97/ruby-client
|
09abb87720570cc1e4ac79d070308d8c597b2079
|
[
"Apache-2.0"
] | null | null | null |
spec/engine/common/impression_manager_spec.rb
|
snilesh97/ruby-client
|
09abb87720570cc1e4ac79d070308d8c597b2079
|
[
"Apache-2.0"
] | null | null | null |
spec/engine/common/impression_manager_spec.rb
|
snilesh97/ruby-client
|
09abb87720570cc1e4ac79d070308d8c597b2079
|
[
"Apache-2.0"
] | null | null | null |
# frozen_string_literal: true
require 'spec_helper'
require 'my_impression_listener'
describe SplitIoClient::Engine::Common::ImpressionManager do
subject { SplitIoClient::Engine::Common::ImpressionManager }
let(:log) { StringIO.new }
let(:impression_listener) { MyImpressionListener.new }
let(:config) { SplitIoClient::SplitConfig.new(logger: Logger.new(log), impression_listener: impression_listener) }
let(:ip) { config.machine_ip }
let(:machine_name) { config.machine_name }
let(:version) { "#{config.language}-#{config.version}" }
let(:impression_repository) { SplitIoClient::Cache::Repositories::ImpressionsRepository.new(config) }
let(:impression_counter) { SplitIoClient::Engine::Common::ImpressionCounter.new }
let(:expected) do
{
m: { s: version, i: ip, n: machine_name },
i: {
k: 'matching_key_test',
b: 'bucketing_key_test',
f: 'split_name_test',
t: 'off',
r: 'default label',
c: 1_478_113_516_002,
m: 1_478_113_516_222,
pt: nil
},
attributes: {}
}
end
it 'build impression' do
impression_manager = subject.new(config, impression_repository, impression_counter)
treatment = { treatment: 'off', label: 'default label', change_number: 1_478_113_516_002 }
params = { attributes: {}, time: 1_478_113_516_222 }
result = impression_manager.build_impression('matching_key_test', 'bucketing_key_test', 'split_name_test', treatment, params)
expect(result).to match(expected)
end
it 'track' do
impressions = []
impressions << expected
impression_manager = subject.new(config, impression_repository, impression_counter)
impression_manager.track(impressions)
sleep(0.5)
expect(impression_repository.batch.size).to eq(1)
expect(impression_listener.size).to eq(1)
end
it 'track optimized' do
impressions = []
impression_manager = subject.new(config, impression_repository, impression_counter)
treatment_data = { treatment: 'off', label: 'default label', change_number: 1_478_113_516_002 }
params = { attributes: {}, time: expected[:i][:m] }
imp = expected[:i]
impressions << impression_manager.build_impression(imp[:k], imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression(imp[:k], imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression(imp[:k], imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression(imp[:k], imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression('second_key', imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression('second_key', imp[:b], imp[:f], treatment_data, params)
impressions << impression_manager.build_impression('second_key', imp[:b], 'test_split', treatment_data, params)
impressions << impression_manager.build_impression('second_key', imp[:b], 'test_split', treatment_data, params)
impression_manager.track(impressions)
sleep(0.5)
expect(impression_repository.batch.size).to eq(3)
expect(impression_listener.size).to eq(8)
end
end
| 39.195122
| 129
| 0.710952
|
40eb7e8899c06035a1f90c16d7104dbf83dffe88
| 1,264
|
tsx
|
TypeScript
|
kinvo/src/components/BondSummary/index.tsx
|
pedrobarbosa0/kinvo-front-end-test
|
7ce049be851f97fe12ee09b49aafe17ef9ffbe1a
|
[
"MIT"
] | null | null | null |
kinvo/src/components/BondSummary/index.tsx
|
pedrobarbosa0/kinvo-front-end-test
|
7ce049be851f97fe12ee09b49aafe17ef9ffbe1a
|
[
"MIT"
] | null | null | null |
kinvo/src/components/BondSummary/index.tsx
|
pedrobarbosa0/kinvo-front-end-test
|
7ce049be851f97fe12ee09b49aafe17ef9ffbe1a
|
[
"MIT"
] | null | null | null |
import { useState, useEffect } from "react";
import { api } from "../../services/api";
import { SummaryCard } from "../atoms/SummaryCard";
import * as S from "./index.style";
interface Summary {
equity: number;
valueApplied: number;
equityProfit: number;
percentageProfit: number;
indexerValue: number;
percentageOverIndexer: number;
}
export const BondSummary = () => {
const [summary, setSummary] = useState<Summary | undefined>();
useEffect(() => {
const fetchData = async () => {
const { data } = await api.get("/");
setSummary(data?.data?.snapshotByPortfolio);
};
fetchData();
}, []);
return (
<S.SummaryContainer>
<SummaryCard value={summary?.equity} label="SALDO BRUTO" valueType="currency" />
<SummaryCard
value={summary?.valueApplied}
label="VALOR APLICADO"
valueType="currency"
/>
<SummaryCard value={summary?.equityProfit} label="RESULTADO" valueType="currency" />
<SummaryCard
value={summary?.percentageProfit}
label="RENTABILIDADE"
valueType="percent"
/>
<SummaryCard value={summary?.indexerValue} label="CDI" valueType="percent" />
<SummaryCard
value={summary?.percentageOverIndexer}
label="% SOBRE CDI"
valueType="percent"
/>
</S.SummaryContainer>
);
};
| 25.28
| 87
| 0.673259
|
8e7b2ced8cc7c2d9e249297885528c490496f276
| 8,828
|
js
|
JavaScript
|
index.js
|
CrownPeak-Contrib/cp-accessapi-nodejs
|
6fdf23604cff75dc173a5b5b999cafb3db999f21
|
[
"Apache-2.0"
] | 1
|
2017-12-18T22:05:25.000Z
|
2017-12-18T22:05:25.000Z
|
index.js
|
CrownPeak-Contrib/cp-accessapi-nodejs
|
6fdf23604cff75dc173a5b5b999cafb3db999f21
|
[
"Apache-2.0"
] | 2
|
2018-02-25T18:53:00.000Z
|
2018-05-26T21:08:38.000Z
|
index.js
|
CrownPeak-Contrib/cp-accessapi-nodejs
|
6fdf23604cff75dc173a5b5b999cafb3db999f21
|
[
"Apache-2.0"
] | 1
|
2020-01-29T22:01:17.000Z
|
2020-01-29T22:01:17.000Z
|
var requestify = require('requestify');
var fs = require('fs');
var log4js = require('@log4js-node/log4js-api');
var util = require('util');
const path = require('path');
var keytar = require('keytar');
//create logger for this library
var log = log4js.getLogger('crownpeak-accessapi');
var opts = {
"apikey": "",
domain: '',
instance: '',
username: '',
password: ''
};
var cookies = null;
baseURL = function (opts) {
return 'https://' + opts.domain + '/' + opts.instance + '/cpt_webservice/accessapi';
}
//setup http headers
var options = {
body: '',
method: 'POST',
headers: {
'x-api-key': opts.apikey,
'Content-Type': 'application/json; charset=utf8',
//'Accept-Encoding': 'gzip, deflate '
}
};
function checkConfig() {
if (opts.instance === '' || opts.instance == undefined) {
throw new Error("config not set. use setConfig before calling api functions.");
}
}
let locationPaths = {
[Symbol.iterator]() {
let p = path.parse(process.cwd());
let parts = p.dir.split(path.sep);
let count = parts.length+1;//+1 because we first try cwd
let curTraverse = '.'+path.sep;
return {
next() {
let checkPath = path.join(__dirname, curTraverse);
curTraverse += '..' + path.sep;
count--;
return { done: (count<0), value: checkPath };
}
}
}
};
let findConfigFile = function() {
let filename = "accessapi-config.json";
let triedPaths = [];
for(let p of locationPaths) {
let tryfile = path.join(p, filename);
if(log.isDebugEnabled) log.debug('Trying path %s', tryfile);
triedPaths.push(tryfile);
if(fs.existsSync(tryfile)===true) {
if(log.isDebugEnabled) log.debug('Found %s in %s', filename, p);
return tryfile;
}
}
//failure if we reach this point
log.fatal('Failed to find an accessapi-config.json file.');
throw util.format('Failed to find an accessapi-config.json file.\nPaths searched:\n%s',triedPaths.join('\n'));
}
loadConfig = function(loadOpts) {
var loadOpts = loadOpts || {};
if(loadOpts["file"] === undefined) {
loadOpts["file"] = findConfigFile();
}
var accessapiConfig = JSON.parse(fs.readFileSync(loadOpts["file"]));;
readConfig(loadOpts, accessapiConfig);
setConfig(accessapiConfig);
return opts;
}
function readConfig(loadOpts, accessapiConfig) {
if (Array.isArray(accessapiConfig)) {
//find specified instance
if (loadOpts["instance"] === undefined) {
accessapiConfig = accessapiConfig[0];
} else {
var found = accessapiConfig.find(function(item,index) {
if (item["instance"] !== undefined && item["instance"] === loadOpts["instance"]) {
return true;
}
});
if (found !== undefined) {
accessapiConfig = found;
}
throw new Error(util.format("failed to find instance '{0}' declared in '{1}'.", loadOpts["instance"], loadOpts["file"]));
}
}
if(accessapiConfig === undefined) {
log.warn('Failed to find suitable accessapi config.');
} else {
//set accessapiConfig to opts
opts = accessapiConfig;
}
}
getPassword = function(opts) {
return new Promise((resolve,reject) => {
//easy path
if(opts.password !== undefined && opts.password !== '') {
resolve(opts.password);
}
//create service name for keytar to query OS keyring
var service = 'UN=' + opts.username + ';CN=' + opts.instance;
keytar.getPassword('Crownpeak-AccessAPI-NodeJS',service)
.then((returnedPass) => {
resolve(returnedPass)
}, (reason) => {
log.fatal('Failed to retrieve password: %s',reason);
reject(reason);
});
});
}
auth = function (callback) {
return new Promise((resolve,reject)=> {
getPassword(opts)
.then((password)=> {
var body = {
"instance": opts.instance,
"username": opts.username,
"password": password,
"remember_me": false,
"timeZoneOffsetMinutes": -480
};
var restPostPromise = restPost('/auth/authenticate', body, callback);
resolve(restPostPromise);
});
});
}
logout = function (callback) {
return restPost('/auth/logout', null, callback);
}
AssetExists = function (assetIdOrPath, callback) {
var body = {
"assetIdOrPath" : assetIdOrPath
};
return restPost('/asset/Exists', body, callback);
}
AssetUpdate = function (assetId, fields, fieldsToDelete, options) {
var body = {
"assetId" : assetId,
"fields": fields,
"fieldsToDelete": fieldsToDelete
};
options = options || {};
if (options.runPostInput !== undefined)
body["runPostInput"] = options.runPostInput;
if (options.runPostSave !== undefined)
body["runPostSave"] = options.runPostSave;
return restPost('/asset/Update', body, arguments[arguments.length - 1]);
}
AssetUpload = function (newName, folderId, modelId, workflowId, bytes, callback) {
var body = {
"newName": newName,
"destinationFolderId": folderId,
"modelId": modelId,
"workflowId": workflowId,
"bytes": bytes
};
if (folderId == 0 || folderId == undefined) return callback('not allowed to import to root');
return restPost('/asset/Upload', body, callback);
}
AssetCreate = function (newName, folderId, modelId, type, devTemplateLanguage, templateId, workflowId, callback) {
var body = {
"newName": newName,
"destinationFolderId": folderId,
"modelId": modelId,
"type": type,
"devTemplateLanguage": devTemplateLanguage,
"templateId": templateId,
"workflowId": workflowId
}
if (folderId == 0 || folderId == undefined) {
log.fatal('create asset error, folderId=%d', folderId);
return callback('not allowed to import to root');
}
return restPost('/asset/Create', body, callback);
}
AssetFields = function (AssetFieldsRequest) {
return new Promise((resolve,reject)=>{
if(AssetFieldsRequest===undefined || AssetFieldsRequest["assetId"]===undefined) {
reject("No assetId specified.");
}
url = '/asset/fields/' + AssetFieldsRequest["assetId"];
new Promise((resolve2,reject2)=>{
restPost(url, null)
.then((resp)=>resolve(resp));
})
});
}
AssetPaged = function (AssetPagedRequest, callback) {
var body = AssetPagedRequest || {};
return restPost('/asset/Paged', body, callback);
}
AssetRoute = function (AssetRouteRequest, callback) {
var body = AssetRouteRequest || {};
return restPost('/asset/Route', body, callback);
}
AssetBranch = function(id) {
var body = {};
var idParam;
if(typeof(id) === 'number') {
idParam = id;
}
return restPost(`/asset/Branch/${idParam}`, body);
}
function setConfig(config) {
for (var k in config) {
opts[k] = config[k];
}
}
//main http call
function restPost(url, body) {
return new Promise((resolve,reject) => {
url = baseURL(opts) + url;
log.info("calling: %s", url);
if (log.isDebugEnabled) {
log.debug("body:", JSON.stringify(body));
log.debug("opts:", opts);
}
options.body = body;
//check if we need pass the cookies
options.headers = {
'x-api-key': opts.apikey,
'Content-Type': 'application/json; charset=utf8',
'Accept': 'application/json',
//'Accept-Encoding': 'gzip, deflate '
};
if (cookies != null) {
// todo: try to reuse headers from above.
options.headers['Cookie'] = cookies
}
if (log.isDebugEnabled) log.debug('sending request', options);
requestify.request(url, options).then(function (resp) {
processCookies(resp);
try { resp.json = JSON.parse(resp.body); } catch(ex) { }
resolve(resp);
}, (err) => {
//todo: handle http 429, rate limiting busy, retry-after
log.error('received error response:', err);
reject(JSON.parse(err.body));
});
//var cbarg = arguments[arguments.length - 1];
//if (typeof cbarg === 'function') try { return deferred.promise.nodeify(cbarg); } catch(ex) { log.warn('restPost cbarg failure: ', ex); }
});
}
//handles cookies between http calls
function processCookies(resp, callback) {
if (resp.headers['set-cookie'] != null) {
log.debug('processing cookies');
var cooks = resp.headers['set-cookie'];
var newCookies = '';
var cookieCount = 0;
cooks.forEach(function (cookie) {
var parts = cookie.split(';');
if (cookieCount++ > 0) {
newCookies += "; ";
}
newCookies += parts[0];
});
cookies = newCookies;
}
}
module.exports = {
auth: auth,
loadConfig: loadConfig,
setConfig: setConfig,
AssetExists: AssetExists,
AssetCreate: AssetCreate,
AssetPaged: AssetPaged,
AssetRoute: AssetRoute,
AssetFields: AssetFields,
AssetBranch: AssetBranch,
logger: log
}
| 25.079545
| 142
| 0.622904
|
79a4fb36d2fefc0b328a10119e54be8f3497dfeb
| 3,785
|
php
|
PHP
|
tests/Bairwell/Emojicalc/Controllers/AboutTest.php
|
bairwell/emojicalc
|
3c34549e4f858720d50cbf5c6d7345ad448a5254
|
[
"MIT"
] | null | null | null |
tests/Bairwell/Emojicalc/Controllers/AboutTest.php
|
bairwell/emojicalc
|
3c34549e4f858720d50cbf5c6d7345ad448a5254
|
[
"MIT"
] | null | null | null |
tests/Bairwell/Emojicalc/Controllers/AboutTest.php
|
bairwell/emojicalc
|
3c34549e4f858720d50cbf5c6d7345ad448a5254
|
[
"MIT"
] | null | null | null |
<?php
namespace Bairwell\Emojicalc\Controllers;
use Bairwell\Emojicalc\RenderViewInterface;
use Bairwell\Emojicalc\RequestInterface;
use Bairwell\Emojicalc\Response;
use PHPUnit\Framework\TestCase;
/**
* Class AboutTest
* @package Bairwell\Emojicalc\Controllers
* @coversDefaultClass Bairwell\Emojicalc\Controllers\About
* @uses \Bairwell\Emojicalc\Request
* @uses \Bairwell\Emojicalc\Response
* @uses \Bairwell\Emojicalc\RenderView
* @uses \Bairwell\Emojicalc\Controllers\About
*/
class AboutTest extends TestCase
{
/**
* Build a mock render view.
* @coversNothing
* @return RenderViewInterface
*/
protected function getRenderView(): RenderViewInterface
{
$renderView = $this->createMock(RenderViewInterface::class);
$callback = function (string $fileName, array $parameters = []): string {
$viewData['viewData:' . $fileName] = $parameters;
$out = json_encode($viewData);
return $out;
};
$renderView->expects($this->any())->method('renderView')->will($this->returnCallback($callback));
return $renderView;
}
/**
* Tests the author action outputs HTML as expected.
*
* @covers ::authorAction
* @covers ::__construct
*/
public function testAuthorAction()
{
$sut = new About($this->getRenderView());
$request = $this->createMock(RequestInterface::class);
$response = new Response();
// start the test
$sentResponse = $sut->authorAction($request, $response);
// assert we got our response back.
$this->assertSame($response,$sentResponse,'Response object is different: got '.get_class($sentResponse).' back'.' expected '.get_class($response));
// body checks
$body = $sentResponse->getBody();
// check the body will match up
$view = $this->getRenderView();
$output = $view->renderView('author', []);
$this->assertSame($output, $body);
}
/**
* Tests the specification action outputs HTML as expected.
*
* @covers ::specificationAction
* @covers ::__construct
*/
public function testSpecificationAction()
{
$sut = new About($this->getRenderView());
$request = $this->createMock(RequestInterface::class);
$response = new Response();
// start the test
$sentResponse = $sut->specificationAction($request, $response);
// assert we got our response back.
$this->assertSame($response,$sentResponse,'Response object is different: got '.get_class($sentResponse).' back'.' expected '.get_class($response));
// body checks
$body = $sentResponse->getBody();
// check the body will match up
$view = $this->getRenderView();
$output = $view->renderView('specification', []);
$this->assertSame($output, $body);
}
/**
* Tests the licence action outputs HTML as expected.
*
* @covers ::licenceAction
* @covers ::__construct
*/
public function testLicenceAction()
{
$sut = new About($this->getRenderView());
$request = $this->createMock(RequestInterface::class);
$response = new Response();
// start the test
$sentResponse = $sut->licenceAction($request, $response);
// assert we got our response back.
$this->assertSame($response,$sentResponse,'Response object is different: got '.get_class($sentResponse).' back'.' expected '.get_class($response));
// body checks
$body = $sentResponse->getBody();
// check the body will match up
$view = $this->getRenderView();
$output = $view->renderView('licence', []);
$this->assertSame($output, $body);
}
}
| 35.046296
| 155
| 0.624306
|
a33060e909ddeb209d04bcf3af61c190ae975687
| 1,052
|
ts
|
TypeScript
|
litmus-portal/frontend/src/views/Analytics/ApplicationDashboards/Steps/ConfigureDashboardMetadata/Form/styles.ts
|
oHanafi/litmus
|
e53909948c6fc280985ebf296268bc080794862f
|
[
"Apache-2.0"
] | null | null | null |
litmus-portal/frontend/src/views/Analytics/ApplicationDashboards/Steps/ConfigureDashboardMetadata/Form/styles.ts
|
oHanafi/litmus
|
e53909948c6fc280985ebf296268bc080794862f
|
[
"Apache-2.0"
] | null | null | null |
litmus-portal/frontend/src/views/Analytics/ApplicationDashboards/Steps/ConfigureDashboardMetadata/Form/styles.ts
|
oHanafi/litmus
|
e53909948c6fc280985ebf296268bc080794862f
|
[
"Apache-2.0"
] | null | null | null |
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
root: {
background: theme.palette.background.paper,
height: '100%',
width: '100%',
border: 1,
borderRadius: 3,
padding: theme.spacing(0, 4),
},
flexDisplay: {
height: '5rem',
display: 'flex',
gap: '1.5rem',
marginLeft: theme.spacing(1),
},
heading: {
fontSize: '1rem',
fontWeight: 500,
lineHeight: '150%',
marginLeft: theme.spacing(1),
},
// Form Select Properties
formControl: {
height: '3.25rem',
width: '20rem',
},
selectTextLabel: {
color: theme.palette.border.main,
'&.Mui-focused': {
color: theme.palette.primary.main,
},
},
selectText: {
height: '3.25rem',
},
formErrorText: {
color: theme.palette.error.main,
},
namespaceSelect: {
width: '41.5rem',
margin: theme.spacing(3.5, 1),
},
appSelectFlex: {
display: 'flex',
gap: '1.5rem',
margin: theme.spacing(0, 1),
},
}));
export default useStyles;
| 17.245902
| 47
| 0.577947
|
ef37a0b1363eb8709d9df729b396d9ff07e95ecd
| 4,158
|
c
|
C
|
src/vidhrdw/ninjakd2_vidhrdw.c
|
trngaje/mame-2003-plus-kaze
|
61199f8424c7ec84b42dbcb66636fe099923a63a
|
[
"RSA-MD"
] | 145
|
2018-04-10T17:24:39.000Z
|
2022-03-27T17:39:03.000Z
|
src/vidhrdw/ninjakd2_vidhrdw.c
|
trngaje/mame-2003-plus-kaze
|
61199f8424c7ec84b42dbcb66636fe099923a63a
|
[
"RSA-MD"
] | 779
|
2018-04-09T21:30:15.000Z
|
2022-03-31T06:38:07.000Z
|
src/vidhrdw/ninjakd2_vidhrdw.c
|
trngaje/mame-2003-plus-kaze
|
61199f8424c7ec84b42dbcb66636fe099923a63a
|
[
"RSA-MD"
] | 152
|
2018-04-10T10:52:18.000Z
|
2022-03-09T08:24:16.000Z
|
#include "driver.h"
#include "vidhrdw/generic.h"
UINT8 *ninjakd2_bg_videoram, *ninjakd2_fg_videoram;
static UINT8 ninjakd2_bg_enable = 1, sprite_overdraw_enabled = 0;
static UINT16 ninjakd2_scrollx, ninjakd2_scrolly;
static struct tilemap *fg_tilemap, *bg_tilemap;
static struct mame_bitmap *bitmap_sp; /* for sprite overdraw */
static void get_bg_tile_info(int tile_index)
{
int code = ((ninjakd2_bg_videoram[tile_index*2 + 1] & 0xc0) << 2) | ninjakd2_bg_videoram[tile_index*2];
int color = ninjakd2_bg_videoram[tile_index*2 + 1] & 0xf;
SET_TILE_INFO(0, code, color, TILE_FLIPYX((ninjakd2_bg_videoram[tile_index*2 + 1] & 0x30) >> 4))
}
static void get_fg_tile_info(int tile_index)
{
int code = ((ninjakd2_fg_videoram[tile_index*2 + 1] & 0xc0) << 2) | ninjakd2_fg_videoram[tile_index*2];
int color = ninjakd2_fg_videoram[tile_index*2 + 1] & 0xf;
SET_TILE_INFO(2, code, color, TILE_FLIPYX((ninjakd2_fg_videoram[tile_index*2 + 1] & 0x30) >> 4))
}
VIDEO_START( ninjakd2 )
{
bg_tilemap = tilemap_create(get_bg_tile_info, tilemap_scan_rows, TILEMAP_OPAQUE, 16, 16, 32, 32);
fg_tilemap = tilemap_create(get_fg_tile_info, tilemap_scan_rows, TILEMAP_TRANSPARENT, 8, 8, 32, 32);
tilemap_set_transparent_pen(fg_tilemap, 15);
if ((bitmap_sp = auto_bitmap_alloc(Machine->drv->screen_width,Machine->drv->screen_height)) == 0)
return 1;
return 0;
}
WRITE_HANDLER( ninjakd2_bgvideoram_w )
{
ninjakd2_bg_videoram[offset] = data;
tilemap_mark_tile_dirty(bg_tilemap, offset >> 1);
}
WRITE_HANDLER( ninjakd2_fgvideoram_w )
{
ninjakd2_fg_videoram[offset] = data;
tilemap_mark_tile_dirty(fg_tilemap, offset >> 1);
}
WRITE_HANDLER( ninjakd2_scrollx_w )
{
if(offset)
ninjakd2_scrollx = ((ninjakd2_scrollx & 0x0ff) | data*256) & 0x1ff;
else
ninjakd2_scrollx = ((ninjakd2_scrollx & 0x100) | data) & 0x1ff;
}
WRITE_HANDLER( ninjakd2_scrolly_w )
{
if(offset)
ninjakd2_scrolly = ((ninjakd2_scrolly & 0x0ff) | data*256) & 0x1ff;
else
ninjakd2_scrolly = ((ninjakd2_scrolly & 0x100) | data) & 0x1ff;
}
WRITE_HANDLER( ninjakd2_background_enable_w )
{
ninjakd2_bg_enable = data & 1;
}
WRITE_HANDLER( ninjakd2_sprite_overdraw_w )
{
sprite_overdraw_enabled = data & 1;
if(sprite_overdraw_enabled)
fillbitmap(bitmap_sp,15,&Machine->visible_area);
}
void ninjakd2_draw_sprites(struct mame_bitmap *bitmap, const struct rectangle *cliprect)
{
int offs;
/* Draw the sprites */
for (offs = 11 ;offs < spriteram_size; offs+=16)
{
int sx,sy,tile,color,flipx,flipy;
if (spriteram[offs+2] & 2)
{
sx = spriteram[offs+1];
sy = spriteram[offs];
if (spriteram[offs+2] & 1) sx-=256;
tile = spriteram[offs+3]+((spriteram[offs+2] & 0xc0)<<2);
flipx = spriteram[offs+2] & 0x10;
flipy = spriteram[offs+2] & 0x20;
color = spriteram[offs+4] & 0x0f;
if(sprite_overdraw_enabled && (color >= 0x0c && color <= 0x0e) )
{
/* "static" sprites */
drawgfx(bitmap_sp,Machine->gfx[1],
tile,
color,
flipx,flipy,
sx,sy,
cliprect,
TRANSPARENCY_PEN, 15);
}
else
{
drawgfx(bitmap,Machine->gfx[1],
tile,
color,
flipx,flipy,
sx,sy,
cliprect,
TRANSPARENCY_PEN, 15);
/* "normal" sprites with color = 0x0f clear the "static" ones */
if(sprite_overdraw_enabled && color == 0x0f)
{
int x,y,offset = 0;
const struct GfxElement *gfx = Machine->gfx[1];
UINT8 *srcgfx = gfx->gfxdata + tile * gfx->char_modulo;
for(y = 0; y < gfx->height; y++)
{
for(x = 0; x < gfx->width; x++)
{
if(srcgfx[offset] != 15)
{
plot_pixel(bitmap_sp, sx + x, sy + y, 15);
}
offset++;
}
}
}
}
}
}
if(sprite_overdraw_enabled)
copybitmap(bitmap, bitmap_sp, 0, 0, 0, 0, cliprect, TRANSPARENCY_PEN, 15);
}
VIDEO_UPDATE( ninjakd2 )
{
fillbitmap(bitmap, Machine->pens[0],0);
tilemap_set_scrollx(bg_tilemap, 0, ninjakd2_scrollx);
tilemap_set_scrolly(bg_tilemap, 0, ninjakd2_scrolly);
if (ninjakd2_bg_enable)
tilemap_draw(bitmap, cliprect, bg_tilemap, 0, 0);
ninjakd2_draw_sprites(bitmap, cliprect);
tilemap_draw(bitmap, cliprect, fg_tilemap, 0, 0);
}
| 25.353659
| 104
| 0.684704
|
3d321a265eb9eb29a9fb2246b2e0d8c625d91070
| 46
|
ps1
|
PowerShell
|
Chapter05/7.8.5.JaggedArray_AccessingElements.ps1
|
gr8greet/Mastering-Windows-PowerShell-Scripting-Third-Edition
|
e8076c68e4cb89bc3d79515c1ad535286dd639ff
|
[
"MIT"
] | 34
|
2019-02-03T16:13:09.000Z
|
2022-03-07T00:18:09.000Z
|
Chapter05/7.8.5.JaggedArray_AccessingElements.ps1
|
atifrather/Mastering-Windows-PowerShell-Scripting-Third-Edition
|
90838e69947d2a1b8a21fa22697503ce65d90354
|
[
"MIT"
] | null | null | null |
Chapter05/7.8.5.JaggedArray_AccessingElements.ps1
|
atifrather/Mastering-Windows-PowerShell-Scripting-Third-Edition
|
90838e69947d2a1b8a21fa22697503ce65d90354
|
[
"MIT"
] | 26
|
2018-12-19T14:24:46.000Z
|
2021-09-27T07:15:50.000Z
|
$arrayOfArrays[1][5]
# Expects output:
#
# 9
| 7.666667
| 20
| 0.630435
|
25798e15b34e1d7454d4a247fe90c86f61c41a73
| 5,995
|
cshtml
|
C#
|
src/Web/MVC/MsSystem.Web/Areas/Sys/Views/User/Index.cshtml
|
didalqb/MsSystem-BPM-ServiceAndWebApps
|
5432ccea9213f89448d4c5fd6ce3fe0b0fa0de9c
|
[
"MIT"
] | 26
|
2019-05-28T10:42:27.000Z
|
2021-12-19T09:05:16.000Z
|
src/Web/MVC/MsSystem.Web/Areas/Sys/Views/User/Index.cshtml
|
didalqb/MsSystem-BPM-ServiceAndWebApps
|
5432ccea9213f89448d4c5fd6ce3fe0b0fa0de9c
|
[
"MIT"
] | null | null | null |
src/Web/MVC/MsSystem.Web/Areas/Sys/Views/User/Index.cshtml
|
didalqb/MsSystem-BPM-ServiceAndWebApps
|
5432ccea9213f89448d4c5fd6ce3fe0b0fa0de9c
|
[
"MIT"
] | 15
|
2019-05-28T11:40:35.000Z
|
2021-09-25T02:29:46.000Z
|
@model UserIndexViewModel
@{
ViewData["Title"] = "用户管理";
Layout = "~/Views/Shared/_LayoutContent.cshtml";
}
@section css{
<link href="~/ui/css/plugins/ztree/metroStyle/metroStyle.css" asp-append-version="true" rel="stylesheet" />
}
@section scripts{
<script> seajs.use("@Url.Content("/src/sys/user/js/index.js")");</script>
}
<div class="wrapper-content">
<div class="row m10" style="display: none" id="roles">
<div class="navbar-fixed-top mt40 p5">
<button type="button" class="btn btn-primary btn-permission btn-permission-save btn-xs" id="saveroles"><i class="fa fa-save"><span class="ml5">保存</span></i></button>
<input type="hidden" name="huserid" value="0" />
</div>
<div class="mt30 ztree" id="rolesTree"></div>
</div>
<div class="row">
<div class="ibox">
<div class="ibox-title">
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12 text-left pl20">
<form method="get">
<div class="col-lg-4 col-md-4 col-sm-4 ms-group">
<label class="col-lg-4 col-md-4 col-sm-4 ms-label">用户名</label>
<div class="col-lg-8 col-md-8 col-sm-8 ms-input">
<input type="text" class="form-control" name="UserName" asp-for="@Model.Search.UserName">
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 ms-group">
<label class="col-lg-4 col-md-4 col-sm-4 ms-label">用户状态</label>
<div class="col-lg-8 col-md-8 col-sm-8 ms-input">
<span class="select-box inline">
<select class="select" name="IsDel">
<option value="-1" selected="@(Model.Search.IsDel==-1)">--全部--</option>
<option value="0" selected="@(Model.Search.IsDel==0)">可用</option>
<option value="1" selected="@(Model.Search.IsDel==1)">不可用</option>
</select>
</span>
</div>
</div>
</form>
</div>
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 text-right">
@await Component.InvokeAsync("Menu")
</div>
</div>
</div>
<div class="ibox-content">
<div class="full-height-scroll">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th class="w50"><input type="checkbox" id="ms_checkall" class="i-checks" /></th>
<th>用户账号</th>
<th>用户名</th>
<th>工号</th>
<th class="w150">创建时间</th>
@*<th class="w100 text-center">数据授权</th>*@
<th class="w75 text-center">分配角色</th>
<th class="w75 text-center">分配部门</th>
<th class="w75 text-center">账号状态</th>
<th class="w75 text-center">操作</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Users.Items)
{
<tr>
<td>
<input type="checkbox" class="i-checks" value="@item.UserId" />
</td>
<td>@item.Account</td>
<td>@item.UserName</td>
<td>@item.JobNumber</td>
<td>@item.CreateTime.ToDateTime().ToString("yyyy-MM-dd hh:mm:ss")</td>
@*<td class="text-center">
<a name="showdataprivileges" data-userid="@item.UserId"><i class="fa fa-database"></i></a>
</td>*@
<td class="text-center">
<a name="showrole" data-userid="@item.UserId"><i class="fa fa-group"></i></a>
</td>
<td class="text-center">
<a name="showdept" data-userid="@item.UserId"><i class="fa fa-sitemap"></i></a>
</td>
<td class="text-center">
@Html.Raw(item.IsDel == 1 ? "<i title=\"已删除\" class=\"fa fa-trash red\"></i>" : "<i title=\"可用\" class=\"fa fa-check green\"></i>")
</td>
<td class="text-center"><a name="showuserinfo" data-userid="@item.UserId">查看</a></td>
</tr>
}
</tbody>
</table>
</div>
<div class="jquery-pager" data-pageindex="@Model.Search.PageIndex" data-pagesize="@Model.Search.PageSize" data-datacount="@Model.Users.TotalItems"></div>
</div>
</div>
</div>
</div>
</div>
| 58.203883
| 177
| 0.375813
|
ddb85dbe36836bb04506783ec93aa87571568823
| 8,501
|
java
|
Java
|
src/main/java/com/sff/rbacdemo/common/aspect/AutoLogAspect.java
|
superfrankiefan/simple-rbac-template
|
c6c605490d20fc071879a3913b072f18a35d0def
|
[
"MIT"
] | null | null | null |
src/main/java/com/sff/rbacdemo/common/aspect/AutoLogAspect.java
|
superfrankiefan/simple-rbac-template
|
c6c605490d20fc071879a3913b072f18a35d0def
|
[
"MIT"
] | null | null | null |
src/main/java/com/sff/rbacdemo/common/aspect/AutoLogAspect.java
|
superfrankiefan/simple-rbac-template
|
c6c605490d20fc071879a3913b072f18a35d0def
|
[
"MIT"
] | null | null | null |
//package com.sff.rbacdemo.common.aspect;
//
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.serializer.PropertyFilter;
//import com.sff.rbacdemo.common.aspect.annotation.AutoLog;
//import com.sff.rbacdemo.common.enums.CommonConstant;
//import com.sff.rbacdemo.common.enums.ModuleType;
//import com.sff.rbacdemo.common.model.Result;
//import com.sff.rbacdemo.common.utils.IPUtils;
//import com.sff.rbacdemo.common.utils.ObjectConvertUtils;
//import com.sff.rbacdemo.common.utils.SpringContextUtils;
//import com.sff.rbacdemo.system_old.dto.LogDTO;
//import com.sff.rbacdemo.system_old.dto.LoginUserDTO;
//import com.sff.rbacdemo.system_old.service.BaseCommonService;
//import org.apache.shiro.SecurityUtils;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
//import org.springframework.stereotype.Component;
//import org.springframework.validation.BindingResult;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.annotation.Resource;
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServletRequest;
//import java.lang.reflect.Method;
//import java.util.Date;
//
//
///**
// * 系统日志,切面处理类
// */
//@Aspect
//@Component
//public class AutoLogAspect {
//
// @Resource
// private BaseCommonService baseCommonService;
//
// @Pointcut("@annotation(org.ims.base.core.aspect.annotation.AutoLog)")
// public void logPointCut() {
//
// }
//
// @Around("logPointCut()")
// public Object around(ProceedingJoinPoint point) throws Throwable {
// long beginTime = System.currentTimeMillis();
// //执行方法
// Object result = point.proceed();
// //执行时长(毫秒)
// long time = System.currentTimeMillis() - beginTime;
//
// //保存日志
// saveSysLog(point, time, result);
//
// return result;
// }
//
// private void saveSysLog(ProceedingJoinPoint joinPoint, long time, Object obj) {
// MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// Method method = signature.getMethod();
//
// LogDTO dto = new LogDTO();
// AutoLog syslog = method.getAnnotation(AutoLog.class);
// if (syslog != null) {
// //update-begin-author:taoyan date:
// String content = syslog.value();
// if (syslog.module() == ModuleType.ONLINE) {
// content = getOnlineLogContent(obj, content);
// }
// //注解上的描述,操作日志内容
// dto.setLogType(syslog.logType());
// dto.setLogContent(content);
// }
//
// //请求的方法名
// String className = joinPoint.getTarget().getClass().getName();
// String methodName = signature.getName();
// dto.setMethod(className + "." + methodName + "()");
//
//
// //设置操作类型
// if (dto.getLogType() == CommonConstant.LOG_TYPE_2) {
// dto.setOperateType(getOperateType(methodName, syslog.operateType()));
// }
//
// //获取request
// HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
// //请求的参数
// dto.setRequestParam(getReqestParams(request, joinPoint));
// //设置IP地址
// dto.setIp(IPUtils.getIpAddr(request));
// //获取登录用户信息
// LoginUserDTO sysUser = (LoginUserDTO) SecurityUtils.getSubject().getPrincipal();
// if (sysUser != null) {
// dto.setUserid(sysUser.getUsername());
// dto.setUsername(sysUser.getRealname());
//
// }
// //耗时
// dto.setCostTime(time);
// dto.setCreateTime(new Date());
// //保存系统日志
// baseCommonService.addLog(dto);
// }
//
//
// /**
// * 获取操作类型
// */
// private int getOperateType(String methodName, int operateType) {
// if (operateType > 0) {
// return operateType;
// }
// if (methodName.startsWith("list")) {
// return CommonConstant.OPERATE_TYPE_1;
// }
// if (methodName.startsWith("add")) {
// return CommonConstant.OPERATE_TYPE_2;
// }
// if (methodName.startsWith("edit")) {
// return CommonConstant.OPERATE_TYPE_3;
// }
// if (methodName.startsWith("delete")) {
// return CommonConstant.OPERATE_TYPE_4;
// }
// if (methodName.startsWith("import")) {
// return CommonConstant.OPERATE_TYPE_5;
// }
// if (methodName.startsWith("export")) {
// return CommonConstant.OPERATE_TYPE_6;
// }
// return CommonConstant.OPERATE_TYPE_1;
// }
//
// /**
// * @param request: request
// * @param joinPoint: joinPoint
// * @Description: 获取请求参数
// * @Return: java.lang.String
// */
// private String getReqestParams(HttpServletRequest request, JoinPoint joinPoint) {
// String httpMethod = request.getMethod();
// String params = "";
// if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {
// Object[] paramsArray = joinPoint.getArgs();
// // java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
// // https://my.oschina.net/mengzhang6/blog/2395893
// Object[] arguments = new Object[paramsArray.length];
// for (int i = 0; i < paramsArray.length; i++) {
// if (paramsArray[i] instanceof BindingResult || paramsArray[i] instanceof ServletRequest || paramsArray[i] instanceof ServletResponse || paramsArray[i] instanceof MultipartFile) {
// //ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
// //ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
// continue;
// }
// arguments[i] = paramsArray[i];
// }
// //update-begin-author:taoyan date:20200724 for:日志数据太长的直接过滤掉
// PropertyFilter profilter = new PropertyFilter() {
// @Override
// public boolean apply(Object o, String name, Object value) {
// if (value != null && value.toString().length() > 500) {
// return false;
// }
// return true;
// }
// };
// params = JSONObject.toJSONString(arguments, profilter);
// //update-end-author:taoyan date:20200724 for:日志数据太长的直接过滤掉
// } else {
// MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// Method method = signature.getMethod();
// // 请求的方法参数值
// Object[] args = joinPoint.getArgs();
// // 请求的方法参数名称
// LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
// String[] paramNames = u.getParameterNames(method);
// if (args != null && paramNames != null) {
// for (int i = 0; i < args.length; i++) {
// params += " " + paramNames[i] + ": " + args[i];
// }
// }
// }
// return params;
// }
//
// /**
// * online日志内容拼接
// *
// * @param obj
// * @param content
// * @return
// */
// private String getOnlineLogContent(Object obj, String content) {
// if (Result.class.isInstance(obj)) {
// Result res = (Result) obj;
// String msg = res.getMessage();
// String tableName = res.getOnlTable();
// if (ObjectConvertUtils.isNotEmpty(tableName)) {
// content += ",表名:" + tableName;
// }
// if (res.isSuccess()) {
// content += "," + (ObjectConvertUtils.isEmpty(msg) ? "操作成功" : msg);
// } else {
// content += "," + (ObjectConvertUtils.isEmpty(msg) ? "操作失败" : msg);
// }
// }
// return content;
// }
//}
| 39.356481
| 212
| 0.595106
|
393b2fb5fbf455025696300bea018e60095b8820
| 222
|
py
|
Python
|
codigo_das_aulas/exercicios/aula_05_a.py
|
VeirichR/curso-python-selenium
|
9b9107a64adb4e6bcf10c76287e0b4cc7d024321
|
[
"CC0-1.0"
] | 234
|
2020-04-03T02:59:30.000Z
|
2022-03-27T15:29:21.000Z
|
codigo_das_aulas/exercicios/aula_05_a.py
|
VeirichR/curso-python-selenium
|
9b9107a64adb4e6bcf10c76287e0b4cc7d024321
|
[
"CC0-1.0"
] | 8
|
2020-04-20T11:20:43.000Z
|
2021-08-18T16:41:15.000Z
|
codigo_das_aulas/exercicios/aula_05_a.py
|
VeirichR/curso-python-selenium
|
9b9107a64adb4e6bcf10c76287e0b4cc7d024321
|
[
"CC0-1.0"
] | 77
|
2020-04-03T13:25:19.000Z
|
2022-02-24T15:31:26.000Z
|
from selenium.webdriver import Firefox
b = Firefox()
b.get('http://selenium.dunossauro.live/aula_05_a.html')
elemento_id_a = b.find_element_by_id('a')
print(elemento_id_a.text)
print(elemento_id_a.get_attribute('id'))
| 20.181818
| 55
| 0.779279
|
44540ecb5d64e803c58fe684bc616f9fd8c11a93
| 19,489
|
py
|
Python
|
magicclass/widgets/containers.py
|
hanjinliu/magic-class
|
2a9d8af3d385ec3870ebcade9f2dbc03115bed22
|
[
"BSD-3-Clause"
] | 15
|
2021-09-07T10:18:59.000Z
|
2022-03-23T14:55:45.000Z
|
magicclass/widgets/containers.py
|
hanjinliu/magic-class
|
2a9d8af3d385ec3870ebcade9f2dbc03115bed22
|
[
"BSD-3-Clause"
] | 12
|
2021-09-10T08:54:43.000Z
|
2022-03-31T02:43:50.000Z
|
magicclass/widgets/containers.py
|
hanjinliu/magic-class
|
2a9d8af3d385ec3870ebcade9f2dbc03115bed22
|
[
"BSD-3-Clause"
] | 1
|
2022-02-13T15:51:51.000Z
|
2022-02-13T15:51:51.000Z
|
from __future__ import annotations
from typing import Any, TypeVar, Callable
import warnings
from qtpy import QtWidgets as QtW
from qtpy.QtCore import Qt, QEvent, QSize
from magicgui.application import use_app
from magicgui.widgets._bases import Widget
from magicgui.widgets._concrete import merge_super_sigs, ContainerWidget
from magicgui.backends._qtpy.widgets import (
QBaseWidget,
Container as ContainerBase,
MainWindow as MainWindowBase
)
# Container variations that is useful in making GUI designs better.
C = TypeVar("C", bound=ContainerWidget)
def wrap_container(cls: type[C] = None, base: type = None) -> Callable | type[C]:
"""
Provide a wrapper for a new container widget with a new protocol.
"""
def wrapper(cls) -> type[Widget]:
def __init__(self, **kwargs):
app = use_app()
assert app.native
kwargs["widget_type"] = base
super(cls, self).__init__(**kwargs)
cls.__init__ = __init__
cls = merge_super_sigs(cls)
return cls
return wrapper(cls) if cls else wrapper
class _Splitter(ContainerBase):
_qwidget: QtW.QWidget
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
# SetLayout is not supported for QSplitter.
# Layout is just a dummy.
self._splitter = QtW.QSplitter(self._qwidget)
if layout == "horizontal":
self._splitter.setOrientation(Qt.Horizontal)
self._layout = QtW.QHBoxLayout()
else:
self._splitter.setOrientation(Qt.Vertical)
self._layout = QtW.QVBoxLayout()
self._scroll_area = None
self._qwidget.setLayout(QtW.QVBoxLayout())
self._qwidget.layout().addWidget(self._splitter)
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
def _mgui_insert_widget(self, position: int, widget: Widget):
self._splitter.insertWidget(position, widget.native)
def _mgui_remove_widget(self, widget: Widget):
widget.native.setParent(None)
def _mgui_get_margins(self) -> tuple[int, int, int, int]:
return (0, 0, 0, 0)
def _mgui_set_margins(self, margins: tuple[int, int, int, int]) -> None:
pass
class _ToolBox(ContainerBase):
_qwidget: QtW.QToolBox
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QToolBox)
if layout == "horizontal":
msg = "Horizontal ToolBox is not implemented yet."
warnings.warn(msg, UserWarning)
self._layout = self._qwidget.layout()
def _mgui_insert_widget(self, position: int, widget: Widget):
self._qwidget.insertItem(position, widget.native, widget.name)
def _mgui_remove_widget(self, widget: Widget):
for i in range(self._qwidget.count()):
if self._qwidget.widget(i) is widget.native:
self._qwidget.removeItem(i)
widget.native.setParent(None)
break
else:
raise ValueError(f"Widget {widget.name} not found.")
class _Tab(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._scroll_area = None
self._tab_widget = QtW.QTabWidget(self._qwidget)
self._tab_widget.setLayout(self._layout)
self._qwidget.setLayout(QtW.QVBoxLayout())
self._qwidget.layout().addWidget(self._tab_widget)
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
def _mgui_insert_widget(self, position: int, widget: Widget):
self._tab_widget.insertTab(position, widget.native, widget.name)
def _mgui_remove_widget(self, widget: Widget):
for i in range(self._tab_widget.count()):
if self._tab_widget.widget(i) is widget.native:
self._tab_widget.removeTab(i)
widget.native.setParent(None)
break
else:
raise ValueError(f"Widget {widget.name} not found.")
class _Stack(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._stacked_widget = QtW.QStackedWidget(self._qwidget)
self._stacked_widget.setContentsMargins(0, 0, 0, 0)
self._inner_widget = QtW.QWidget(self._qwidget)
self._qwidget.setLayout(self._layout)
self._layout.addWidget(self._stacked_widget)
self._layout.addWidget(self._inner_widget)
def _mgui_insert_widget(self, position: int, widget: Widget):
self._stacked_widget.insertWidget(position, widget.native)
def _mgui_remove_widget(self, widget: Widget):
self._stacked_widget.removeWidget(widget.native)
widget.native.setParent(None)
class _ScrollableContainer(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
self._scroll_area = QtW.QScrollArea(self._qwidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._scroll_area.setWidgetResizable(True)
self._scroll_area.setContentsMargins(0, 0, 0, 0)
self._inner_widget = QtW.QWidget(self._scroll_area)
self._inner_widget.setLayout(self._layout)
self._scroll_area.setWidget(self._inner_widget)
self._qwidget.setLayout(QtW.QVBoxLayout())
self._qwidget.layout().addWidget(self._scroll_area)
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
class _WheelDisabledScrollArea(QtW.QScrollArea):
def eventFilter(self, source, event: QEvent):
if event.type() == QEvent.Wheel:
return True
return super().eventFilter(source, event)
class _DraggableContainer(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
self._scroll_area = _WheelDisabledScrollArea(self._qwidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._scroll_area.setWidgetResizable(True)
self._scroll_area.setContentsMargins(0, 0, 0, 0)
self._inner_widget = QtW.QWidget(self._scroll_area)
self._inner_widget.setLayout(self._layout)
self._scroll_area.setWidget(self._inner_widget)
self._qwidget.setLayout(QtW.QVBoxLayout())
self._qwidget.layout().addWidget(self._scroll_area)
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
QtW.QScroller.grabGesture(self._scroll_area, QtW.QScroller.LeftMouseButtonGesture)
self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
class _ButtonContainer(ContainerBase):
def __init__(self, layout="vertical", btn_text=""):
QBaseWidget.__init__(self, QtW.QWidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._qwidget = QtW.QPushButton()
self._inner_widget = QtW.QWidget()
self._inner_widget.setParent(self._qwidget, self._inner_widget.windowFlags())
self._inner_widget.setLayout(self._layout)
self._qwidget.setText(btn_text)
self._qwidget.clicked.connect(lambda x: self._inner_widget.show())
_VERTICAL_SETTING = {"expanded-arrow": Qt.ArrowType.DownArrow,
"collapsed-arrow": Qt.ArrowType.RightArrow,
"align": Qt.AlignTop,
"text-align": "left",
"layout": QtW.QVBoxLayout
}
_HORIZONTAL_SETTING = {"expanded-arrow": Qt.ArrowType.RightArrow,
"collapsed-arrow": Qt.ArrowType.LeftArrow,
"align": Qt.AlignLeft,
"text-align": "center",
"layout": QtW.QHBoxLayout
}
class _QCollapsible(QtW.QWidget):
def sizeHint(self) -> QSize:
if self.isVisible():
return super().sizeHint()
else:
return QSize(0, 0)
class _Collapsibles(ContainerBase):
_setting: dict[str, Any]
def __init__(self, layout="vertical", btn_text=""):
QBaseWidget.__init__(self, QtW.QWidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._get_setting()
self._qwidget = QtW.QWidget()
self._qwidget.setLayout(self._setting["layout"]())
self._inner_widget = _QCollapsible(self._qwidget)
self._inner_widget.setLayout(self._layout)
self._qwidget.layout().setSpacing(0)
self._layout.setContentsMargins(0, 0, 0, 0)
self._expand_btn = QtW.QToolButton(self._qwidget)
self._expand_btn.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self._expand_btn.setArrowType(self._setting["collapsed-arrow"])
self._expand_btn.setText(btn_text)
self._expand_btn.setCheckable(True)
self._expand_btn.setChecked(False)
self._expand_btn.setStyleSheet(f"""
QToolButton {{
border: none;
text-align: {self._setting['text-align']};
}}
""")
self._expand_btn.clicked.connect(self._mgui_change_expand)
self._mgui_change_expand()
self._qwidget.layout().addWidget(self._expand_btn, 0, self._setting["align"])
self._qwidget.layout().addWidget(self._inner_widget, 0, self._setting["align"])
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
@property
def collapsed(self) -> bool:
return not self._expand_btn.isChecked()
def _collapse(self):
self._inner_widget.setVisible(False)
self._expand_btn.setArrowType(self._setting["collapsed-arrow"])
def _expand(self):
self._inner_widget.setVisible(True)
self._expand_btn.setArrowType(self._setting["expanded-arrow"])
def _mgui_change_expand(self):
if self.collapsed:
self._collapse()
else:
self._expand()
def _get_setting(self):
raise NotImplementedError()
class _VCollapsibleContainer(_Collapsibles):
def _get_setting(self):
self._setting = _VERTICAL_SETTING
class _HCollapsibleContainer(_Collapsibles):
def _get_setting(self):
self._setting = _HORIZONTAL_SETTING
class _ListContainer(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
self._listwidget = QtW.QListWidget(self._qwidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._layout.setContentsMargins(0, 0, 0, 0)
self._layout.addWidget(self._listwidget)
self._qwidget.setLayout(self._layout)
self._listwidget.setAcceptDrops(True)
self._listwidget.setDragEnabled(True)
self._listwidget.setDragDropMode(QtW.QAbstractItemView.DragDropMode.InternalMove)
if layout == "horizontal":
self._listwidget.setFlow(QtW.QListView.LeftToRight)
else:
self._listwidget.setFlow(QtW.QListView.TopToBottom)
def _mgui_insert_widget(self, position: int, widget: Widget):
item = QtW.QListWidgetItem(self._listwidget)
item.setSizeHint(widget.native.sizeHint())
self._listwidget.insertItem(position, item)
self._listwidget.setItemWidget(item, widget.native)
def _mgui_remove_widget(self, widget: Widget):
for i in range(self._listwidget.count()):
item = self._listwidget.item(i)
w = self._listwidget.itemWidget(item)
if widget.native is w:
self._listwidget.removeItemWidget(item)
self._listwidget.takeItem(i)
break
else:
raise ValueError(f"Widget {widget} not found in the list.")
widget.native.setParent(None)
class _SubWindowsContainer(ContainerBase):
# The close button in QMdiArea completely deletes the sub window widget. This accident
# can be avoided by defining a custom window flag.
_NoCloseButtonFlag = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowMinMaxButtonsHint
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
self._mdiarea = QtW.QMdiArea(self._qwidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._layout.addWidget(self._mdiarea)
self._qwidget.setLayout(self._layout)
def _mgui_insert_widget(self, position: int, widget: Widget):
# position does not have any effect
self._mdiarea.addSubWindow(widget.native, self._NoCloseButtonFlag)
def _mgui_remove_widget(self, widget: Widget):
self._mdiarea.removeSubWindow(widget.native)
widget.native.setParent(None)
class _GroupBoxContainer(ContainerBase):
def __init__(self, layout="vertical"):
QBaseWidget.__init__(self, QtW.QWidget)
# To precisely control margins, _layout should not be set to the QGroupBox widget.
self._groupbox = QtW.QGroupBox(self._qwidget)
if layout == "horizontal":
self._layout: QtW.QLayout = QtW.QHBoxLayout()
else:
self._layout = QtW.QVBoxLayout()
self._inner_widget = QtW.QWidget(self._groupbox)
self._inner_widget.setLayout(self._layout)
self._groupbox.setLayout(QtW.QHBoxLayout())
self._groupbox.layout().addWidget(self._inner_widget)
self._qwidget.setLayout(QtW.QVBoxLayout())
self._qwidget.layout().addWidget(self._groupbox)
self._qwidget.layout().setContentsMargins(0, 0, 0, 0)
def _set_title(self, title: str):
self._groupbox.setTitle(title)
class _FrameContainer(_GroupBoxContainer):
def __init__(self, layout="vertical"):
super().__init__(layout=layout)
self._groupbox.setTitle("")
@wrap_container(base=_Splitter)
class SplitterContainer(ContainerWidget):
"""A Container equipped with splitter"""
@wrap_container(base=_ToolBox)
class ToolBoxContainer(ContainerWidget):
"""A Tool box Widget."""
@property
def current_index(self):
return self.native.currentIndex()
@current_index.setter
def current_index(self, index: int):
self.native.setCurrentIndex(index)
@wrap_container(base=_Tab)
class TabbedContainer(ContainerWidget):
"""A tab categorized Container Widget."""
@property
def current_index(self):
return self._widget._tab_widget.currentIndex()
@current_index.setter
def current_index(self, index: int):
self._widget._tab_widget.setCurrentIndex(index)
@wrap_container(base=_Stack)
class StackedContainer(ContainerWidget):
"""A stacked Container Widget"""
@property
def current_index(self):
return self._widget._stacked_widget.currentIndex()
@current_index.setter
def current_index(self, index: int):
self._widget._stacked_widget.setCurrentIndex(index)
@wrap_container(base=_ScrollableContainer)
class ScrollableContainer(ContainerWidget):
"""A scrollable Container Widget."""
@wrap_container(base=_DraggableContainer)
class DraggableContainer(ContainerWidget):
"""A draggable Container Widget."""
@wrap_container(base=_ButtonContainer)
class ButtonContainer(ContainerWidget):
"""A Container Widget hidden in a button."""
@property
def btn_text(self):
return self._widget._qwidget.text()
@btn_text.setter
def btn_text(self, text: str):
self._widget._qwidget.setText(text)
@wrap_container(base=_VCollapsibleContainer)
class CollapsibleContainer(ContainerWidget):
"""A collapsible Container Widget."""
@property
def btn_text(self):
return self._widget._expand_btn.text()
@btn_text.setter
def btn_text(self, text: str):
self._widget._expand_btn.setText(text)
@property
def collapsed(self) -> bool:
return self._widget.collapsed
@collapsed.setter
def collapsed(self, value: bool):
if value:
self._widget._collapse()
else:
self._widget._expand()
@wrap_container(base=_HCollapsibleContainer)
class HCollapsibleContainer(ContainerWidget):
"""A collapsible Container Widget."""
@property
def btn_text(self):
return self._widget._expand_btn.text()
@btn_text.setter
def btn_text(self, text: str):
self._widget._expand_btn.setText(text)
@property
def collapsed(self) -> bool:
return self._widget.collapsed
@collapsed.setter
def collapsed(self, value: bool):
if value:
self._widget._collapse()
else:
self._widget._expand()
@wrap_container(base=_ListContainer)
class ListContainer(ContainerWidget):
"""A Container Widget that support drag and drop."""
def _post_init(self):
self._widget._listwidget.model().rowsMoved.connect(self._drag_and_drop_happened)
return super()._post_init()
def _drag_and_drop_happened(self, e=None):
"""Sort widget list when item drag/drop happens."""
l = []
for i in range(self._widget._listwidget.count()):
item = self._widget._listwidget.item(i)
w = self._widget._listwidget.itemWidget(item)
for widget in self._list:
# if widget is a _LabeledWidget, inserted widget item will
# be the parent of the widget in "_list".
if widget.native is w or widget.native.parent() is w:
l.append(widget)
break
self._list = l
@property
def current_index(self):
return self._widget._listwidget.currentRow()
@current_index.setter
def current_index(self, index: int):
self._widget._listwidget.setCurrentRow(index)
@wrap_container(base=_SubWindowsContainer)
class SubWindowsContainer(ContainerWidget):
"""A window-in-window container"""
@wrap_container(base=_GroupBoxContainer)
class GroupBoxContainer(ContainerWidget):
"""A QGroupBox like container"""
@property
def name(self):
return self._name
@name.setter
def name(self, value: str):
self._name = value
self._widget._set_title(value.replace("_", " "))
@wrap_container(base=_FrameContainer)
class FrameContainer(ContainerWidget):
"""A QGroupBox like container without title."""
| 35.628885
| 97
| 0.64852
|
b01edffa4e178342041a6ca5d2904014575d1da9
| 24,276
|
py
|
Python
|
tests/test_agglomerative.py
|
leolani/cltl-face-recognition
|
b98e4791c9943b4a4a91d00e2ede5ead2d5fa61f
|
[
"MIT"
] | null | null | null |
tests/test_agglomerative.py
|
leolani/cltl-face-recognition
|
b98e4791c9943b4a4a91d00e2ede5ead2d5fa61f
|
[
"MIT"
] | null | null | null |
tests/test_agglomerative.py
|
leolani/cltl-face-recognition
|
b98e4791c9943b4a4a91d00e2ede5ead2d5fa61f
|
[
"MIT"
] | null | null | null |
import dataclasses
import unittest
import numpy as np
from cltl.vector_id.clusterid import ClusterIdentity
@dataclasses.dataclass
class TestCluster:
labels_: list
class TestClustering:
"""Cluster id is determined by the first dimension of the vector being zero."""
def fit(self, X):
return TestCluster(X[:, 0] == 0)
class TestAgglomerativeVectorId(unittest.TestCase):
def test_empty(self):
vector_id = ClusterIdentity(TestClustering(), 3)
self.assertEqual((0, 3), vector_id._representations.shape)
def test_add_one_dimensional(self):
vector_id = ClusterIdentity(TestClustering(), 3)
vector_id.add(np.array([0,3,4]))
vector_id.add(np.array([0,3,4]))
np.testing.assert_array_almost_equal([[0,3,4], [0,3,4]], vector_id._representations)
np.testing.assert_array_equal([0,3/5,4/5], next(iter(vector_id._centroids.values())))
def test_add_first(self):
vector_id = ClusterIdentity(TestClustering(), 3)
vector_id.add(np.array([[0,3,4]]))
np.testing.assert_array_almost_equal([[0,3,4]], vector_id._representations)
np.testing.assert_array_equal([0,3/5,4/5], next(iter(vector_id._centroids.values())))
def test_add_one_cluster(self):
vector_id = ClusterIdentity(TestClustering(), 3)
vector_id.add(np.array([[0,3,4], [0,3,4]]))
np.testing.assert_array_equal([[0,3,4], [0,3,4]], vector_id._representations)
np.testing.assert_array_almost_equal([0,3/5,4/5], next(iter(vector_id._centroids.values())))
def test_add_two_clusters(self):
vector_id = ClusterIdentity(TestClustering(), 3)
vector_id.add(np.array([[0,3,4], [0,3,4], [5,12,0], [5,12,0]]))
np.testing.assert_array_equal([[0,3,4], [0,3,4], [5,12,0], [5,12,0]], vector_id._representations)
centroids = list(sorted([tuple(cent) for cent in vector_id._centroids.values()]))
self.assertEqual(2, len(centroids))
np.testing.assert_array_almost_equal([0,3/5,4/5], centroids[0])
np.testing.assert_array_almost_equal([5/13,12/13,0], centroids[1])
def test_add_two_clusters_one_by_one(self):
vector_id = ClusterIdentity(TestClustering(), 3)
id_1 = vector_id.add(np.array([[0,3,4]]))
id_2 = vector_id.add(np.array([[0,3,4]]))
id_3 = vector_id.add(np.array([[5,12,0]]))
id_4 = vector_id.add(np.array([[5,12,0]]))
np.testing.assert_array_equal([[0,3,4], [0,3,4], [5,12,0], [5,12,0]], vector_id._representations)
centroids = list(sorted([tuple(cent) for cent in vector_id._centroids.values()]))
self.assertEqual(2, len(centroids))
np.testing.assert_array_almost_equal([0,3/5,4/5], centroids[0])
np.testing.assert_array_almost_equal([5/13,12/13,0], centroids[1])
self.assertEqual(id_1, id_2)
self.assertEqual(id_3, id_4)
self.assertNotEqual(id_1, id_3)
def test_add_two_clusters_agglomerative(self):
vector_id = ClusterIdentity.agglomerative(3, 0.1)
id_1 = vector_id.add(np.array([[0,3,4]]))
id_2 = vector_id.add(np.array([[0,3,4]]))
id_3 = vector_id.add(np.array([[5,12,0]]))
id_4 = vector_id.add(np.array([[5,12,0]]))
np.testing.assert_array_equal([[0,3,4], [0,3,4], [5,12,0], [5,12,0]], vector_id._representations)
centroids = list(sorted([tuple(cent) for cent in vector_id._centroids.values()]))
self.assertEqual(2, len(centroids))
np.testing.assert_array_almost_equal([0,3/5,4/5], centroids[0])
np.testing.assert_array_almost_equal([5/13,12/13,0], centroids[1])
self.assertEqual(id_1, id_2)
self.assertEqual(id_3, id_4)
self.assertNotEqual(id_1, id_3)
def test_add_one_dimensional_no_dim(self):
vector_id = ClusterIdentity(TestClustering(), 0)
vector_id.add(np.array([0,3,4]))
vector_id.add(np.array([0,3,4]))
np.testing.assert_array_almost_equal([[0,3,4], [0,3,4]], vector_id._representations)
np.testing.assert_array_equal([0,3/5,4/5], next(iter(vector_id._centroids.values())))
def test_two_dimensional_no_dim(self):
vector_id = ClusterIdentity(TestClustering(), None)
vector_id.add(np.array([[0,3,4]]))
vector_id.add(np.array([[0,3,4]]))
np.testing.assert_array_almost_equal([[0,3,4], [0,3,4]], vector_id._representations)
np.testing.assert_array_equal([0,3/5,4/5], next(iter(vector_id._centroids.values())))
def test_high_dimensional_runs_without_errors(self):
vector_id = ClusterIdentity.agglomerative(0, 0.1)
embeddings = np.array([[0.04033, 0.00239, 0.07055, 0.09924, -0.04310, 0.07525, -0.01110, 0.01596, 0.06416, 0.05910, -0.04483, 0.05125, -0.05855, -0.05928, -0.00403, 0.02286, 0.00968, -0.03060, -0.01531, -0.03746, 0.03748, 0.06572, 0.02293, -0.00569, -0.01466, -0.00888, -0.00632, 0.03012, 0.01382, -0.01228, 0.01191, 0.16940, 0.03387, 0.02397, 0.00903, 0.02465, 0.00205, -0.07306, 0.02680, -0.02877, 0.02359, 0.04737, -0.04135, -0.05056, -0.01978, -0.01763, 0.03069, 0.00032, -0.08090, 0.00094, -0.00586, 0.04093, 0.02771, 0.02459, 0.06944, 0.00071, -0.03708, -0.04547, -0.10318, 0.05844, 0.05309, 0.01828, -0.03179, -0.03322, -0.00485, -0.00210, -0.04818, 0.00546, 0.01380, -0.03014, 0.02184, 0.02099, 0.06900, 0.02351, -0.01536, -0.01016, -0.05433, 0.08255, -0.04285, 0.05843, -0.08229, 0.00036, 0.02491, -0.02762, 0.00482, -0.12327, -0.03334, -0.03007, 0.02016, -0.05876, 0.00068, -0.09427, -0.01258, -0.04339, 0.03018, 0.00575, 0.04831, -0.03926, 0.10413, -0.03389, 0.06211, 0.01196, -0.02751, -0.00988, 0.00415, -0.06509, -0.00703, -0.06321, 0.07341, -0.05424, -0.01668, 0.00818, -0.00458, 0.00525, -0.03502, 0.06170, 0.01012, 0.00049, -0.01249, -0.02000, -0.01534, 0.10848, -0.02393, 0.02286, 0.07738, 0.08010, -0.01400, 0.02722, -0.00033, -0.02480, 0.05482, -0.01097, 0.11494, 0.04828, -0.01827, 0.00134, -0.00749, 0.02994, 0.02773, 0.04519, -0.02475, 0.05796, 0.05050, 0.04872, -0.01276, -0.02734, -0.04033, 0.01013, 0.00919, -0.02973, 0.04465, 0.00021, 0.05651, 0.09445, -0.01230, -0.05934, -0.01845, 0.10338, 0.03501, 0.03109, 0.01558, -0.05732, 0.02712, -0.01635, -0.03739, -0.00266, -0.00319, -0.09630, -0.02313, -0.03269, -0.03144, -0.01556, 0.02806, 0.00924, -0.02912, 0.01189, 0.01406, -0.05153, -0.06128, 0.00834, -0.00868, -0.00074, -0.00389, -0.00802, -0.07939, 0.01557, 0.12182, -0.00703, -0.01017, 0.01102, 0.01944, -0.04896, -0.00338, 0.01844, -0.05962, -0.02939, -0.05335, -0.01685, 0.02968, -0.03075, -0.01733, -0.06617, 0.05483, 0.01320, -0.04760, 0.03735, 0.02410, 0.02813, -0.00811, -0.02431, -0.04025, 0.00576, 0.00117, -0.01600, 0.00689, -0.01046, -0.08528, 0.03169, -0.07314, 0.03689, 0.01609, 0.00001, -0.00072, -0.00448, 0.05270, -0.00982, 0.04349, -0.09122, -0.04947, -0.01843, -0.03496, -0.03000, 0.01752, 0.09247, 0.02540, 0.06841, 0.06352, -0.01256, 0.02712, -0.04180, 0.06271, 0.04539, 0.00945, 0.07932, -0.01480, 0.03554, -0.01440, 0.04069, 0.01757, 0.02244, 0.02430, -0.00831, 0.05645, 0.06505, 0.07745, 0.01845, -0.02981, -0.04835, -0.01667, -0.02113, -0.05245, 0.05671, -0.04400, -0.01225, -0.04786, 0.00103, -0.04078, -0.08605, -0.00496, -0.04065, 0.04748, -0.00478, 0.03748, -0.04453, 0.08364, -0.04519, -0.00684, 0.05084, -0.02890, -0.00700, -0.02096, 0.04153, 0.03515, -0.01792, -0.03309, 0.05893, 0.02637, -0.00431, 0.07033, 0.00499, -0.00054, 0.05145, 0.04387, -0.02458, -0.00671, 0.03880, -0.03839, -0.02496, -0.04868, -0.01856, -0.04192, 0.00546, -0.00336, 0.00726, -0.06631, 0.00260, -0.05498, 0.02930, -0.03243, 0.03494, 0.02274, -0.07325, -0.10807, 0.02638, -0.07572, -0.02212, 0.03082, -0.00272, -0.04384, -0.04343, 0.01300, 0.04498, 0.09513, 0.01833, 0.08962, -0.03986, -0.07123, 0.03996, -0.02510, 0.00112, -0.02113, 0.04241, -0.05953, 0.08315, -0.06508, 0.06429, 0.01899, 0.01246, -0.05562, -0.00176, 0.02880, -0.02638, 0.03155, 0.01540, 0.05119, -0.00766, -0.04481, -0.01422, 0.04744, -0.12099, -0.00500, -0.04346, -0.02157, 0.01607, -0.00244, 0.02529, 0.02959, 0.00014, 0.13309, 0.08373, -0.03935, -0.00256, 0.00113, -0.01074, 0.00136, -0.01882, 0.02913, -0.01240, 0.00419, -0.00051, -0.01412, 0.04257, -0.06524, -0.00483, -0.01558, 0.02257, -0.04074, 0.00540, -0.00393, -0.06017, -0.00727, 0.04464, 0.14538, 0.03216, 0.03478, 0.02100, -0.04942, 0.01112, -0.04777, 0.04297, 0.01418, -0.07953, -0.02569, 0.01094, -0.07679, -0.00175, -0.02997, -0.04855, -0.12326, -0.00889, -0.09008, 0.05064, 0.03513, 0.06133, -0.03390, 0.01198, -0.01841, 0.02175, 0.01087, 0.03350, -0.07962, 0.02406, -0.04911, 0.01107, 0.02777, -0.07081, -0.08089, -0.00920, 0.05952, 0.03411, -0.00990, 0.01099, 0.04342, 0.01350, 0.05692, 0.01096, 0.00301, -0.03264, 0.01046, 0.02887, 0.00121, -0.00910, -0.00247, -0.01692, -0.01378, -0.02340, 0.00238, -0.11213, 0.00418, 0.04075, 0.05929, -0.03632, 0.04193, -0.05112, 0.04744, -0.05729, -0.02945, -0.01829, -0.00158, -0.03728, 0.04031, 0.02916, -0.01572, -0.03900, -0.00022, 0.02546, 0.03716, -0.04563, -0.03336, -0.03434, -0.00337, -0.01006, -0.02266, 0.07467, 0.07370, 0.00888, 0.07410, -0.00395, -0.01964, 0.04145, -0.02950, 0.01563, -0.02839, -0.00493, 0.00565, 0.01605, -0.03027, -0.02687, -0.00613, 0.04908, -0.02012, 0.01820, -0.01714, 0.08532, 0.00312, 0.03582, -0.08793, -0.08372, 0.02182, -0.02731, -0.06593, -0.04387, 0.04224, 0.02507, 0.05928, -0.02970, 0.07124, -0.06781, -0.01801, 0.03498, 0.01998, 0.03776, 0.05945, 0.07820, -0.02244, -0.07771, 0.00959, -0.06342, 0.04917, -0.02134, 0.04325, 0.03237],
[0.04033, 0.00239, 0.07055, 0.09924, -0.04310, 0.07525, -0.01110, 0.01596, 0.06416, 0.05910, -0.04483, 0.05125, -0.05855, -0.05928, -0.00403, 0.02286, 0.00968, -0.03060, -0.01531, -0.03746, 0.03748, 0.06572, 0.02293, -0.00569, -0.01466, -0.00888, -0.00632, 0.03012, 0.01382, -0.01228, 0.01191, 0.16940, 0.03387, 0.02397, 0.00903, 0.02465, 0.00205, -0.07306, 0.02680, -0.02877, 0.02359, 0.04737, -0.04135, -0.05056, -0.01978, -0.01763, 0.03069, 0.00032, -0.08090, 0.00094, -0.00586, 0.04093, 0.02771, 0.02459, 0.06944, 0.00071, -0.03708, -0.04547, -0.10318, 0.05844, 0.05309, 0.01828, -0.03179, -0.03322, -0.00485, -0.00210, -0.04818, 0.00546, 0.01380, -0.03014, 0.02184, 0.02099, 0.06900, 0.02351, -0.01536, -0.01016, -0.05433, 0.08255, -0.04285, 0.05843, -0.08229, 0.00036, 0.02491, -0.02762, 0.00482, -0.12327, -0.03334, -0.03007, 0.02016, -0.05876, 0.00068, -0.09427, -0.01258, -0.04339, 0.03018, 0.00575, 0.04831, -0.03926, 0.10413, -0.03389, 0.06211, 0.01196, -0.02751, -0.00988, 0.00415, -0.06509, -0.00703, -0.06321, 0.07341, -0.05424, -0.01668, 0.00818, -0.00458, 0.00525, -0.03502, 0.06170, 0.01012, 0.00049, -0.01249, -0.02000, -0.01534, 0.10848, -0.02393, 0.02286, 0.07738, 0.08010, -0.01400, 0.02722, -0.00033, -0.02480, 0.05482, -0.01097, 0.11494, 0.04828, -0.01827, 0.00134, -0.00749, 0.02994, 0.02773, 0.04519, -0.02475, 0.05796, 0.05050, 0.04872, -0.01276, -0.02734, -0.04033, 0.01013, 0.00919, -0.02973, 0.04465, 0.00021, 0.05651, 0.09445, -0.01230, -0.05934, -0.01845, 0.10338, 0.03501, 0.03109, 0.01558, -0.05732, 0.02712, -0.01635, -0.03739, -0.00266, -0.00319, -0.09630, -0.02313, -0.03269, -0.03144, -0.01556, 0.02806, 0.00924, -0.02912, 0.01189, 0.01406, -0.05153, -0.06128, 0.00834, -0.00868, -0.00074, -0.00389, -0.00802, -0.07939, 0.01557, 0.12182, -0.00703, -0.01017, 0.01102, 0.01944, -0.04896, -0.00338, 0.01844, -0.05962, -0.02939, -0.05335, -0.01685, 0.02968, -0.03075, -0.01733, -0.06617, 0.05483, 0.01320, -0.04760, 0.03735, 0.02410, 0.02813, -0.00811, -0.02431, -0.04025, 0.00576, 0.00117, -0.01600, 0.00689, -0.01046, -0.08528, 0.03169, -0.07314, 0.03689, 0.01609, 0.00001, -0.00072, -0.00448, 0.05270, -0.00982, 0.04349, -0.09122, -0.04947, -0.01843, -0.03496, -0.03000, 0.01752, 0.09247, 0.02540, 0.06841, 0.06352, -0.01256, 0.02712, -0.04180, 0.06271, 0.04539, 0.00945, 0.07932, -0.01480, 0.03554, -0.01440, 0.04069, 0.01757, 0.02244, 0.02430, -0.00831, 0.05645, 0.06505, 0.07745, 0.01845, -0.02981, -0.04835, -0.01667, -0.02113, -0.05245, 0.05671, -0.04400, -0.01225, -0.04786, 0.00103, -0.04078, -0.08605, -0.00496, -0.04065, 0.04748, -0.00478, 0.03748, -0.04453, 0.08364, -0.04519, -0.00684, 0.05084, -0.02890, -0.00700, -0.02096, 0.04153, 0.03515, -0.01792, -0.03309, 0.05893, 0.02637, -0.00431, 0.07033, 0.00499, -0.00054, 0.05145, 0.04387, -0.02458, -0.00671, 0.03880, -0.03839, -0.02496, -0.04868, -0.01856, -0.04192, 0.00546, -0.00336, 0.00726, -0.06631, 0.00260, -0.05498, 0.02930, -0.03243, 0.03494, 0.02274, -0.07325, -0.10807, 0.02638, -0.07572, -0.02212, 0.03082, -0.00272, -0.04384, -0.04343, 0.01300, 0.04498, 0.09513, 0.01833, 0.08962, -0.03986, -0.07123, 0.03996, -0.02510, 0.00112, -0.02113, 0.04241, -0.05953, 0.08315, -0.06508, 0.06429, 0.01899, 0.01246, -0.05562, -0.00176, 0.02880, -0.02638, 0.03155, 0.01540, 0.05119, -0.00766, -0.04481, -0.01422, 0.04744, -0.12099, -0.00500, -0.04346, -0.02157, 0.01607, -0.00244, 0.02529, 0.02959, 0.00014, 0.13309, 0.08373, -0.03935, -0.00256, 0.00113, -0.01074, 0.00136, -0.01882, 0.02913, -0.01240, 0.00419, -0.00051, -0.01412, 0.04257, -0.06524, -0.00483, -0.01558, 0.02257, -0.04074, 0.00540, -0.00393, -0.06017, -0.00727, 0.04464, 0.14538, 0.03216, 0.03478, 0.02100, -0.04942, 0.01112, -0.04777, 0.04297, 0.01418, -0.07953, -0.02569, 0.01094, -0.07679, -0.00175, -0.02997, -0.04855, -0.12326, -0.00889, -0.09008, 0.05064, 0.03513, 0.06133, -0.03390, 0.01198, -0.01841, 0.02175, 0.01087, 0.03350, -0.07962, 0.02406, -0.04911, 0.01107, 0.02777, -0.07081, -0.08089, -0.00920, 0.05952, 0.03411, -0.00990, 0.01099, 0.04342, 0.01350, 0.05692, 0.01096, 0.00301, -0.03264, 0.01046, 0.02887, 0.00121, -0.00910, -0.00247, -0.01692, -0.01378, -0.02340, 0.00238, -0.11213, 0.00418, 0.04075, 0.05929, -0.03632, 0.04193, -0.05112, 0.04744, -0.05729, -0.02945, -0.01829, -0.00158, -0.03728, 0.04031, 0.02916, -0.01572, -0.03900, -0.00022, 0.02546, 0.03716, -0.04563, -0.03336, -0.03434, -0.00337, -0.01006, -0.02266, 0.07467, 0.07370, 0.00888, 0.07410, -0.00395, -0.01964, 0.04145, -0.02950, 0.01563, -0.02839, -0.00493, 0.00565, 0.01605, -0.03027, -0.02687, -0.00613, 0.04908, -0.02012, 0.01820, -0.01714, 0.08532, 0.00312, 0.03582, -0.08793, -0.08372, 0.02182, -0.02731, -0.06593, -0.04387, 0.04224, 0.02507, 0.05928, -0.02970, 0.07124, -0.06781, -0.01801, 0.03498, 0.01998, 0.03776, 0.05945, 0.07820, -0.02244, -0.07771, 0.00959, -0.06342, 0.04917, -0.02134, 0.04325, 0.03237],
[0.02892, 0.01239, 0.06904, 0.10118, -0.02539, 0.07344, -0.00923, 0.02611, 0.06155, 0.06609, -0.04307, 0.05594, -0.05395, -0.05007, 0.00031, 0.03520, -0.00577, -0.02814, -0.00269, -0.04223, 0.06196, 0.06396, 0.02535, 0.00702, -0.02523, -0.01090, -0.02258, 0.02856, 0.02846, -0.00285, 0.00963, 0.16410, 0.02590, 0.02256, 0.00615, 0.01398, 0.02125, -0.08144, 0.02230, -0.03225, 0.03765, 0.03224, -0.04608, -0.04299, -0.01251, -0.02514, 0.02386, 0.00573, -0.06156, -0.00639, 0.00604, 0.04942, 0.02815, 0.03745, 0.05497, 0.00174, -0.05225, -0.03044, -0.10221, 0.07933, 0.05343, 0.00353, -0.03898, -0.02526, 0.00189, 0.00410, -0.04996, -0.00231, 0.01187, -0.03422, 0.02346, 0.01522, 0.06910, 0.01348, 0.00128, -0.00886, -0.04078, 0.08003, -0.05794, 0.05112, -0.06415, -0.00686, 0.03857, -0.03015, 0.00311, -0.12569, -0.02077, -0.03448, 0.01948, -0.05612, 0.01959, -0.07930, -0.03030, -0.04492, 0.01647, 0.02214, 0.05075, -0.02099, 0.11370, -0.03972, 0.06092, 0.02521, -0.02703, -0.01003, 0.00595, -0.08890, -0.00262, -0.04979, 0.08475, -0.06805, -0.00140, 0.00885, -0.01290, -0.00974, -0.03571, 0.06825, 0.02018, -0.00003, 0.00120, -0.02436, -0.01846, 0.10365, -0.03352, 0.01550, 0.05997, 0.08899, 0.00082, 0.01776, 0.00896, -0.03590, 0.06514, -0.00904, 0.10284, 0.03760, -0.02353, -0.01495, -0.02716, 0.02007, 0.04145, 0.04884, -0.01825, 0.06778, 0.04925, 0.05329, -0.01801, -0.01802, -0.03471, 0.00139, 0.00840, -0.02923, 0.02716, 0.00948, 0.05660, 0.12103, -0.01066, -0.06979, -0.02736, 0.08562, 0.03934, 0.03827, 0.01491, -0.04906, 0.02268, -0.01566, -0.02556, 0.01524, 0.00295, -0.09084, -0.04112, -0.03255, -0.04540, 0.00716, 0.02494, 0.01591, -0.03283, 0.01725, 0.00914, -0.05802, -0.04675, -0.00706, -0.00547, -0.01689, -0.00232, -0.02345, -0.09448, 0.01360, 0.11957, -0.00198, -0.00295, -0.00046, 0.01409, -0.03203, 0.01677, 0.02561, -0.05951, -0.03784, -0.06084, -0.01853, 0.04854, -0.02540, -0.00405, -0.07095, 0.05765, 0.01319, -0.05088, 0.04687, 0.03290, 0.02855, -0.02171, -0.01476, -0.04762, 0.01217, 0.01038, -0.01467, 0.01835, 0.00156, -0.09282, 0.02592, -0.06296, 0.02736, 0.00032, 0.00534, -0.00784, -0.01305, 0.03847, -0.01238, 0.04436, -0.09184, -0.03949, -0.00590, -0.04203, -0.01994, 0.02481, 0.10413, 0.01734, 0.08008, 0.06446, -0.01551, 0.00897, -0.03008, 0.05995, 0.07432, -0.00044, 0.07618, -0.00964, 0.02145, -0.01426, 0.04250, 0.02899, 0.02961, 0.03156, -0.00864, 0.05388, 0.08591, 0.06232, 0.00470, -0.03393, -0.04092, 0.00506, -0.01653, -0.04799, 0.05307, -0.04500, -0.01052, -0.04031, 0.01675, -0.03941, -0.06101, -0.01497, -0.02164, 0.04749, -0.00138, 0.04757, -0.04463, 0.07097, -0.04524, -0.00669, 0.03584, -0.03499, -0.01290, -0.02871, 0.02307, 0.03487, -0.01594, -0.03183, 0.05729, 0.00549, -0.02286, 0.06479, 0.00635, -0.00541, 0.05281, 0.06490, -0.00431, 0.01079, 0.03848, -0.03457, -0.02578, -0.03751, -0.01442, -0.04553, -0.00291, 0.01023, -0.00236, -0.05831, -0.00275, -0.05826, 0.02847, -0.01855, 0.01856, 0.00722, -0.06207, -0.09809, 0.03391, -0.04967, -0.01502, 0.04573, -0.01160, -0.03362, -0.03710, 0.02103, 0.03824, 0.08679, 0.00463, 0.07986, -0.02182, -0.07972, 0.02909, -0.01727, 0.00262, -0.01641, 0.04066, -0.02770, 0.07716, -0.07818, 0.04754, 0.01946, 0.01306, -0.06755, 0.00823, 0.01056, -0.04248, 0.02747, 0.03132, 0.06666, -0.00127, -0.05665, -0.00158, 0.05879, -0.10661, -0.00518, -0.02763, -0.01107, 0.02895, 0.00237, 0.01585, 0.02414, 0.01013, 0.13103, 0.06717, -0.04798, 0.00828, -0.00906, -0.00358, 0.00184, -0.03741, 0.01852, -0.00835, -0.00087, -0.00815, -0.01999, 0.05968, -0.05872, -0.00859, -0.00531, 0.02715, -0.04705, -0.00684, -0.00925, -0.06641, -0.00791, 0.04100, 0.13947, 0.02792, 0.02961, 0.02630, -0.04625, 0.00889, -0.06984, 0.06152, 0.01818, -0.07037, -0.03451, 0.00826, -0.09336, -0.00921, -0.02133, -0.04283, -0.12100, -0.00574, -0.09671, 0.04782, 0.01671, 0.04920, -0.04150, 0.01889, 0.00443, 0.01866, 0.00136, 0.03953, -0.09029, 0.02823, -0.06941, 0.01975, 0.01669, -0.07498, -0.08415, -0.00396, 0.06438, 0.03577, -0.00241, 0.00403, 0.03149, 0.02596, 0.05991, 0.01763, -0.01346, -0.02878, 0.00782, 0.03779, 0.00240, 0.00753, -0.01187, -0.01739, -0.00959, -0.01361, 0.00142, -0.10783, -0.00972, 0.03533, 0.04468, -0.02207, 0.04387, -0.03239, 0.04154, -0.05679, -0.01492, -0.02030, -0.00074, -0.04791, 0.02151, 0.03442, -0.01083, -0.01846, 0.00382, 0.03529, 0.03504, -0.07250, -0.02562, -0.04813, -0.02211, -0.02131, -0.01206, 0.08506, 0.05903, -0.00402, 0.08577, -0.01530, -0.00867, 0.05325, -0.02096, 0.01049, -0.03004, -0.01568, 0.01337, 0.01352, -0.02663, -0.04555, -0.02050, 0.06758, -0.00345, 0.03270, -0.01304, 0.08042, 0.00325, 0.04651, -0.07734, -0.07054, 0.02896, -0.02378, -0.06576, -0.04744, 0.05630, 0.02033, 0.07144, -0.04003, 0.06372, -0.08130, -0.00083, 0.03400, 0.01527, 0.05078, 0.06392, 0.05919, -0.02696, -0.07252, -0.00300, -0.06393, 0.02744, -0.03356, 0.05106, 0.01642],
[0.00301, 0.01980, 0.02526, 0.08707, -0.03825, 0.03706, 0.01231, -0.04443, 0.08058, 0.08016, -0.08023, 0.03012, -0.06987, 0.00292, -0.03454, 0.04167, -0.02099, -0.02780, -0.02799, -0.02222, 0.02216, 0.05898, -0.00420, -0.00122, 0.01617, -0.00065, 0.02156, 0.00609, 0.03158, -0.03731, -0.00867, 0.16330, 0.04699, 0.06543, 0.02812, -0.01104, 0.03131, -0.05881, 0.01563, -0.05821, 0.03758, 0.04258, -0.04367, -0.04314, -0.01046, -0.00581, 0.01848, 0.02866, -0.03920, 0.00594, 0.04909, 0.01028, 0.03971, 0.01972, 0.01572, -0.01848, -0.04765, -0.04797, -0.10060, 0.06017, 0.05142, -0.02156, 0.01637, -0.00220, -0.03862, 0.04269, -0.02313, -0.00674, 0.03153, -0.02647, 0.04231, -0.00238, 0.03962, 0.00804, 0.01426, 0.00626, -0.02581, 0.07277, -0.01288, 0.03166, -0.04249, 0.02453, 0.03942, -0.05435, 0.00365, -0.12359, -0.00762, -0.02489, 0.01503, -0.03804, 0.01482, -0.09906, 0.00476, -0.03890, 0.00833, 0.02092, -0.00591, -0.00252, 0.08603, -0.03639, 0.05676, 0.00623, -0.00397, -0.05091, 0.02681, -0.02545, -0.01398, -0.02580, 0.07699, -0.05578, -0.01785, 0.00267, 0.01723, -0.00974, -0.01544, 0.07322, 0.02426, 0.05081, 0.01736, -0.04235, 0.01082, 0.04822, -0.00495, 0.02194, 0.05785, 0.08306, 0.02316, 0.03842, 0.00931, -0.04812, 0.02690, -0.04104, 0.12348, 0.04883, 0.01535, -0.02456, -0.00945, 0.06651, 0.05242, 0.03146, 0.01042, 0.05959, 0.02539, 0.03886, -0.00392, -0.02041, -0.03199, 0.00664, -0.01002, 0.00890, 0.08169, 0.02374, 0.05006, 0.09092, -0.01983, -0.06332, -0.02515, 0.08685, 0.05741, 0.01545, 0.04516, -0.01312, -0.00512, 0.02489, -0.01729, 0.02650, 0.03809, -0.07181, 0.00551, 0.00877, -0.04692, 0.03147, 0.02151, -0.00672, -0.03295, 0.00956, 0.00217, -0.04699, -0.06473, 0.01351, -0.00546, -0.00511, -0.03593, -0.00472, -0.07508, 0.01174, 0.08194, 0.03873, -0.00886, -0.00735, -0.02901, -0.03082, 0.03133, 0.02646, -0.04729, -0.01440, -0.02492, -0.02171, 0.07006, -0.03921, -0.01942, -0.06808, 0.07346, 0.02709, -0.04486, 0.03182, -0.01028, 0.02593, -0.04363, -0.00615, -0.01876, -0.01552, -0.03234, -0.00091, 0.00516, -0.01500, -0.07374, 0.05309, -0.05647, 0.09266, 0.00455, -0.02981, -0.01817, 0.02838, 0.07184, 0.00870, 0.00279, -0.09360, -0.03429, -0.04415, -0.08157, -0.00425, 0.00626, 0.07986, -0.00747, 0.05306, 0.05180, -0.05034, 0.01147, -0.04784, 0.04976, 0.05669, 0.00419, 0.08467, 0.02329, 0.00468, -0.07050, 0.07885, 0.01272, 0.01100, 0.01521, -0.03520, 0.03102, 0.05072, 0.02512, -0.01778, -0.03262, -0.05039, -0.04319, -0.01440, -0.04749, 0.04833, -0.08283, -0.03095, -0.05953, 0.05053, -0.03244, -0.05661, -0.00939, 0.00122, 0.06019, 0.04283, 0.07068, -0.04271, 0.07133, -0.05971, -0.03041, 0.01428, -0.02028, -0.01436, 0.01745, 0.01094, -0.00028, 0.00494, -0.09653, 0.07037, 0.01450, -0.05608, 0.07973, 0.04807, 0.03536, 0.02571, 0.04628, 0.00286, 0.02988, 0.03103, -0.00065, -0.03346, -0.04815, -0.06137, -0.01851, 0.02752, -0.02768, -0.00967, -0.02525, 0.00870, -0.05806, 0.03590, -0.03904, -0.01950, -0.01229, -0.07079, -0.04694, 0.02228, -0.07656, -0.01553, 0.04063, 0.02056, -0.02595, -0.00061, 0.00301, 0.06353, 0.06846, 0.05541, 0.10408, 0.00581, -0.11689, 0.04512, 0.00255, -0.03881, -0.04250, 0.10198, -0.05177, 0.11499, -0.07948, 0.06238, 0.01868, 0.05451, -0.08599, 0.03904, 0.01109, -0.02391, 0.01331, 0.00244, 0.04326, -0.00714, -0.04692, -0.01947, 0.03226, -0.10518, 0.02198, -0.06559, -0.02566, 0.03266, -0.03576, 0.01706, 0.01023, 0.01434, 0.13100, 0.02553, -0.04959, -0.01304, -0.01013, -0.00162, 0.01094, -0.00203, 0.03979, -0.00759, -0.00984, 0.03527, -0.05675, 0.04397, -0.07642, 0.01838, -0.01230, -0.00020, -0.03639, 0.00679, -0.03341, -0.04589, 0.01508, 0.04012, 0.11716, 0.01208, 0.03689, 0.02974, -0.04841, -0.00710, -0.04253, 0.02848, -0.01307, -0.08110, -0.03218, -0.02152, -0.04846, -0.00062, -0.00422, -0.02657, -0.13152, 0.03211, -0.08104, 0.00753, 0.00662, 0.03154, -0.03655, -0.01962, 0.00208, 0.03393, -0.00298, 0.03335, -0.08249, 0.05726, -0.02676, 0.03427, -0.00876, -0.02830, -0.07917, -0.00354, 0.05993, 0.01882, -0.02362, 0.00671, 0.01712, 0.03071, 0.08472, 0.01710, -0.01445, -0.01925, 0.01344, -0.00359, 0.02990, -0.00957, 0.00141, -0.02243, -0.04182, -0.03302, 0.00600, -0.12942, -0.02792, 0.02687, 0.06445, -0.02985, 0.04846, -0.04175, 0.06355, -0.02963, -0.04841, 0.00318, 0.00293, -0.07642, -0.00460, 0.02437, -0.01900, 0.00312, -0.01605, 0.05242, 0.03680, -0.03525, -0.05226, -0.05087, -0.02071, -0.02734, 0.01003, 0.09703, 0.03219, 0.04502, 0.03570, 0.02261, -0.02165, 0.04358, -0.05981, 0.02757, 0.02922, -0.00217, 0.00901, -0.01623, -0.00336, -0.01608, 0.00738, 0.04244, -0.00395, 0.01614, -0.02128, 0.09502, -0.02093, 0.01663, -0.08324, -0.08566, 0.00828, -0.02045, -0.03394, -0.04493, 0.06993, 0.02578, -0.01257, -0.03750, 0.06890, -0.05528, -0.04549, 0.03466, 0.05628, 0.03459, 0.06806, 0.06389, -0.04482, -0.10843, 0.00774, -0.02564, 0.00995, -0.00388, 0.02106, -0.00077]])
vector_id.add(embeddings)
vector_id.add(embeddings)
| 192.666667
| 4,899
| 0.634289
|
ce91b61adc4815a8d3175c6de81472e51964a173
| 7,407
|
dart
|
Dart
|
lib/src/dio/interceptor_builder.dart
|
tjarvstrand/stash_dio
|
7d1217842b63f235a3788c4eefe5ae1e35caafa3
|
[
"MIT"
] | 4
|
2020-07-18T15:16:19.000Z
|
2020-10-21T19:44:00.000Z
|
lib/src/dio/interceptor_builder.dart
|
tjarvstrand/stash_dio
|
7d1217842b63f235a3788c4eefe5ae1e35caafa3
|
[
"MIT"
] | 2
|
2021-03-19T10:34:52.000Z
|
2021-04-05T20:05:16.000Z
|
lib/src/dio/interceptor_builder.dart
|
tjarvstrand/stash_dio
|
7d1217842b63f235a3788c4eefe5ae1e35caafa3
|
[
"MIT"
] | 2
|
2020-10-21T19:53:44.000Z
|
2021-03-14T15:16:30.000Z
|
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import 'package:stash/stash_api.dart';
import 'cache_interceptor.dart';
import 'cache_value.dart';
import 'header_value.dart';
/// Function to call with the parsed header values
typedef _ParseHeadCallback = void Function(Duration maxAge, Duration maxStale);
/// A [Interceptor] builder class
class CacheInterceptorBuilder {
/// A map of [RegExp] to [Cache] for each of he patterns
final Map<RegExp, Cache> _cacheMap = {};
/// The callback that will be executed before the request is initiated.
InterceptorSendCallback get onRequest => _onRequest;
/// The callback that will be executed on success.
InterceptorSuccessCallback get onResponse => _onResponse;
/// The callback that will be executed on error.
InterceptorErrorCallback get onError => _onError;
/// Registers a [Cache] under a specific pattern
///
/// * [pattern]: The pattern
/// * [cache]: The cache
void cache(String pattern, Cache cache) {
_cacheMap[RegExp(pattern)] = cache;
}
/// Returns a [Cache] for the current [Uri] or null if none was configured
///
/// * [uri]: The [Uri] being called
///
/// Returns the [Cache] if any
Cache _getCache(Uri uri) {
var input = '${uri?.host}${uri?.path}?${uri.query}';
for (var entry in _cacheMap.entries) {
if (entry.key.hasMatch(input)) {
return entry.value;
}
}
return null;
}
/// Converts bytes to a hexadecimal string
///
/// * [bytes]: The bytes
///
/// Return the hexadecimal string
String _hex(List<int> bytes) {
final buffer = StringBuffer();
for (var part in bytes) {
if (part & 0xff != part) {
throw FormatException('$part is not a byte integer');
}
buffer.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
}
return buffer.toString().toUpperCase();
}
/// Creates a MD5 out of String
///
/// * [input]: The input string
///
/// Return the MD5 hash of string
String _toMd5(String input) {
return _hex(md5.convert(utf8.encode(input)).bytes);
}
/// Returns the key for the current [RequestOptions]
///
/// * [options]: The [RequestOptions]
///
/// Returns the key
String _getKey(RequestOptions options) => _toMd5(
'${options.uri?.host}${options.uri?.path}?${options.uri?.query}_${options.data?.toString()}');
/// Builds a [Response] out of [CacheValue]
///
/// * [value]: The [CacheValue]
/// * [options]: The [RequestOptions]
///
/// Returns a [Response]
Response _responseFromCacheValue(CacheValue value, RequestOptions options) {
Headers headers;
if (value.headers != null) {
headers = Headers.fromMap((Map<String, List<dynamic>>.from(
jsonDecode(utf8.decode(value.headers))))
.map((k, v) => MapEntry(k, List<String>.from(v))));
}
if (headers == null) {
headers = Headers();
options.headers.forEach((k, v) => headers.add(k, v ?? ''));
}
dynamic data = value.data;
if (options.responseType != ResponseType.bytes) {
data = jsonDecode(utf8.decode(data));
}
return Response(
data: data, headers: headers, statusCode: value.statusCode ?? 200);
}
/// Intercepts a request and checks if it's present on the cache
///
/// * [options]: The [RequestOptions]
///
/// Returns the response after a HTTP request or the cached response if
/// available on cache
dynamic _onRequest(RequestOptions options) async {
var cache = _getCache(options.uri);
if (cache != null) {
var value = await cache.get(_getKey(options));
if (value != null) {
return _responseFromCacheValue(value as CacheValue, options);
}
}
return options;
}
/// Parses a duration out of a parameter map
///
/// * [parameters]: The parameters
/// * [key]: The key of the parameter to extract
///
/// Returns the [Duration] if available or null is not available
Duration _tryGetDurationFromMap(Map<String, String> parameters, String key) {
if (null != parameters && parameters.containsKey(key)) {
var value = int.tryParse(parameters[key]);
if (value != null && value >= 0) {
return Duration(seconds: value);
}
}
return null;
}
/// Parses the response header
///
/// * [response]: The [Response]
/// * [callback]: A callback to invoke upon sucessfull parsing
void _tryParseHead(Response response, _ParseHeadCallback callback) {
Duration maxAge;
Duration maxStale;
var cacheControl = response.headers.value('cache-control');
if (cacheControl != null) {
// try to get maxAge and maxStale from cacheControl
var parameters = HeaderValue.parse('cache-control: $cacheControl',
parameterSeparator: '', valueSeparator: '=')
.parameters;
maxAge = _tryGetDurationFromMap(parameters, 's-maxage');
maxAge ??= _tryGetDurationFromMap(parameters, 'max-age');
// if staleTime has value, don't get max-stale anymore.
maxStale ??= _tryGetDurationFromMap(parameters, 'max-stale');
} else {
// try to get expiryTime from expires
var expires = response.headers.value('expires');
if (expires != null && expires.length > 4) {
var endTime = parseHttpDate(expires).toLocal();
if (null != endTime && endTime.compareTo(DateTime.now()) >= 0) {
maxAge = endTime.difference(DateTime.now());
}
}
}
callback(maxAge, maxStale);
}
/// Intercepts the received from a HTTP call and stores on cache
///
/// * [response]: The [Response]
///
/// Returns [Response] after the interception
dynamic _onResponse(Response response) async {
if (response.statusCode >= 200 && response.statusCode < 300) {
var cache = _getCache(response.request.uri);
if (cache != null) {
var options = response.request;
Duration maxAge;
DateTime staleDate;
if (maxAge == null) {
_tryParseHead(response, (_maxAge, _staleTime) {
maxAge = _maxAge;
staleDate =
_staleTime != null ? DateTime.now().add(_staleTime) : null;
});
}
List<int> data;
if (options.responseType == ResponseType.bytes) {
data = response.data;
} else {
data = utf8.encode(jsonEncode(response.data));
}
await cache.put(
_getKey(response.request),
CacheValue(
statusCode: response.statusCode,
headers: utf8.encode(jsonEncode(response.headers.map)),
staleDate: staleDate,
data: data),
expiryDuration: maxAge);
}
}
return response;
}
/// Intercepts the call triggered upon error and returns if available the
/// cached response
///
/// * [e]: The [DioError]
///
/// Returns the error
dynamic _onError(DioError e) async {
var cache = _getCache(e.request.uri);
if (cache != null) {
CacheValue value = await cache.get(_getKey(e.request));
if (value != null && !value.staleDateExceeded()) {
return _responseFromCacheValue(value, e.request);
}
}
return e;
}
/// Builds the [Interceptor]
Interceptor build() {
return CacheInterceptor.builder(this);
}
}
| 30.356557
| 100
| 0.623194
|
00133daeeb68f376c4c4770941502db5cdeb9f50
| 558
|
swift
|
Swift
|
Renetik/Renetik/Classes/Json/JsonObject/CSJsonObject+Create.swift
|
rene-dohan/renetik-library-ios
|
2ccb49e1950affa0d06c5de8bd69b499e387ae2f
|
[
"MIT"
] | 1
|
2020-03-13T15:20:25.000Z
|
2020-03-13T15:20:25.000Z
|
Renetik/Renetik/Classes/Json/JsonObject/CSJsonObject+Create.swift
|
rene-dohan/renetik-library-ios
|
2ccb49e1950affa0d06c5de8bd69b499e387ae2f
|
[
"MIT"
] | null | null | null |
Renetik/Renetik/Classes/Json/JsonObject/CSJsonObject+Create.swift
|
rene-dohan/renetik-library-ios
|
2ccb49e1950affa0d06c5de8bd69b499e387ae2f
|
[
"MIT"
] | null | null | null |
//
// Created by Rene Dohan on 12/9/19.
// Copyright (c) 2019 Renetik. All rights reserved.
//
import RenetikObjc
import Renetik
extension CSJsonObject {
func createJsonDataList<T: CSJsonObject>(_ type: T.Type, _ key: String, defaultDataList: [T]? = nil) -> [T] {
let mapDataArray: [[String: CSAnyProtocol?]]? = getList(key)
var jsonDataArray: [T] = [T]()
mapDataArray?.enumerated().forEach { index, item in
jsonDataArray.add(type.init().load(data: item, index: index))
}
return jsonDataArray
}
}
| 31
| 113
| 0.637993
|
45b1886c7e798a63824d72254c25f8df02461215
| 7,178
|
py
|
Python
|
tests/test_dask_image/test_ndinterp/test_spline_filter.py
|
anlavandier/dask-image
|
a858c61ac5beb7de7d7644d7e85714b5c16c2a7a
|
[
"BSD-3-Clause"
] | 144
|
2018-03-02T16:52:10.000Z
|
2022-03-29T11:41:06.000Z
|
tests/test_dask_image/test_ndinterp/test_spline_filter.py
|
anlavandier/dask-image
|
a858c61ac5beb7de7d7644d7e85714b5c16c2a7a
|
[
"BSD-3-Clause"
] | 184
|
2018-03-02T19:43:26.000Z
|
2022-03-31T10:20:05.000Z
|
tests/test_dask_image/test_ndinterp/test_spline_filter.py
|
anlavandier/dask-image
|
a858c61ac5beb7de7d7644d7e85714b5c16c2a7a
|
[
"BSD-3-Clause"
] | 35
|
2018-03-02T16:37:48.000Z
|
2021-12-10T20:47:11.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from packaging import version
import dask
import dask.array as da
import numpy as np
import pytest
import scipy
import scipy.ndimage
import dask_image.ndinterp
# mode lists for the case with prefilter = False
_supported_modes = ['constant', 'nearest', 'reflect', 'mirror']
_unsupported_modes = ['wrap']
# additional modes are present in SciPy >= 1.6.0
if version.parse(scipy.__version__) >= version.parse('1.6.0'):
_supported_modes += ['grid-constant', 'grid-mirror', 'grid-wrap']
def validate_spline_filter(n=2,
axis_size=64,
interp_order=3,
interp_mode='constant',
chunksize=32,
output=np.float64,
random_seed=0,
use_cupy=False,
axis=None,
input_as_non_dask_array=False,
depth=None):
"""
Compare the outputs of `scipy.ndimage.spline_transform`
and `dask_image.ndinterp.spline_transform`. If axis is not None, then
`spline_transform1d` is tested instead.
"""
if (
np.dtype(output) != np.float64
and version.parse(scipy.__version__) < version.parse('1.4.0')
):
pytest.skip("bug in output dtype handling in SciPy < 1.4")
# define test image
np.random.seed(random_seed)
image = np.random.random([axis_size] * n)
if version.parse(dask.__version__) < version.parse("2020.1.0"):
# older dask will fail if any chunks have size smaller than depth
_depth = dask_image.ndinterp._get_default_depth(interp_order)
rem = axis_size % chunksize
if chunksize < _depth or (rem != 0 and rem < _depth):
pytest.skip("older dask doesn't automatically rechunk")
if input_as_non_dask_array:
if use_cupy:
import cupy as cp
image_da = cp.asarray(image)
else:
image_da = image
else:
# transform into dask array
image_da = da.from_array(image, chunks=[chunksize] * n)
if use_cupy:
import cupy as cp
image_da = image_da.map_blocks(cp.asarray)
if axis is not None:
scipy_func = scipy.ndimage.spline_filter1d
dask_image_func = dask_image.ndinterp.spline_filter1d
kwargs = {'axis': axis}
else:
scipy_func = scipy.ndimage.spline_filter
dask_image_func = dask_image.ndinterp.spline_filter
kwargs = {}
# transform with scipy
image_t_scipy = scipy_func(
image,
output=output,
order=interp_order,
mode=interp_mode,
**kwargs)
# transform with dask-image
image_t_dask = dask_image_func(
image_da,
output=output,
order=interp_order,
mode=interp_mode,
depth=depth,
**kwargs)
image_t_dask_computed = image_t_dask.compute()
rtol = atol = 1e-6
out_dtype = np.dtype(output)
assert image_t_scipy.dtype == image_t_dask_computed.dtype == out_dtype
assert np.allclose(image_t_scipy, image_t_dask_computed,
rtol=rtol, atol=atol)
@pytest.mark.parametrize("n", [1, 2, 3])
@pytest.mark.parametrize("axis_size", [64])
@pytest.mark.parametrize("interp_order", range(2, 6))
@pytest.mark.parametrize("interp_mode", _supported_modes)
@pytest.mark.parametrize("chunksize", [32, 15])
def test_spline_filter_general(
n,
axis_size,
interp_order,
interp_mode,
chunksize,
):
validate_spline_filter(
n=n,
axis_size=axis_size,
interp_order=interp_order,
interp_mode=interp_mode,
chunksize=chunksize,
axis=None,
)
@pytest.mark.cupy
@pytest.mark.parametrize("n", [2])
@pytest.mark.parametrize("axis_size", [32])
@pytest.mark.parametrize("interp_order", range(2, 6))
@pytest.mark.parametrize("interp_mode", _supported_modes[::2])
@pytest.mark.parametrize("chunksize", [16])
@pytest.mark.parametrize("axis", [None, -1])
@pytest.mark.parametrize("input_as_non_dask_array", [False, True])
def test_spline_filter_cupy(
n,
axis_size,
interp_order,
interp_mode,
chunksize,
axis,
input_as_non_dask_array,
):
pytest.importorskip("cupy", minversion="6.0.0")
validate_spline_filter(
n=n,
axis_size=axis_size,
interp_order=interp_order,
interp_mode=interp_mode,
chunksize=chunksize,
axis=axis,
input_as_non_dask_array=input_as_non_dask_array,
use_cupy=True,
)
@pytest.mark.parametrize("n", [1, 2, 3])
@pytest.mark.parametrize("axis_size", [48, 27])
@pytest.mark.parametrize("interp_order", range(2, 6))
@pytest.mark.parametrize("interp_mode", _supported_modes)
@pytest.mark.parametrize("chunksize", [33])
@pytest.mark.parametrize("axis", [0, 1, -1])
def test_spline_filter1d_general(
n,
axis_size,
interp_order,
interp_mode,
chunksize,
axis,
):
if axis == 1 and n < 2:
pytest.skip(msg="skip axis=1 for 1d signals")
validate_spline_filter(
n=n,
axis_size=axis_size,
interp_order=interp_order,
interp_mode=interp_mode,
chunksize=chunksize,
axis=axis,
)
@pytest.mark.parametrize("axis", [None, -1])
def test_spline_filter_non_dask_array_input(axis):
validate_spline_filter(
axis=axis,
input_as_non_dask_array=True,
)
@pytest.mark.parametrize("depth", [None, 24])
@pytest.mark.parametrize("axis", [None, -1])
def test_spline_filter_non_default_depth(depth, axis):
validate_spline_filter(
axis=axis,
depth=depth,
)
@pytest.mark.parametrize("depth", [(16, 32), [18]])
def test_spline_filter1d_invalid_depth(depth):
with pytest.raises(ValueError):
validate_spline_filter(
axis=-1,
depth=depth,
)
@pytest.mark.parametrize("axis_size", [32])
@pytest.mark.parametrize("interp_order", range(2, 6))
@pytest.mark.parametrize("interp_mode", _unsupported_modes)
@pytest.mark.parametrize("axis", [None, -1])
def test_spline_filter_unsupported_modes(
axis_size,
interp_order,
interp_mode,
axis,
):
with pytest.raises(NotImplementedError):
validate_spline_filter(
axis_size=axis_size,
interp_order=interp_order,
interp_mode=interp_mode,
axis=axis,
)
@pytest.mark.parametrize(
"output", [np.float64, np.float32, "float32", np.dtype(np.float32)]
)
@pytest.mark.parametrize("axis", [None, -1])
def test_spline_filter_output_dtype(output, axis):
validate_spline_filter(
axis_size=32,
interp_order=3,
output=output,
axis=axis,
)
@pytest.mark.parametrize("axis", [None, -1])
def test_spline_filter_array_output_unsupported(axis):
n = 2
axis_size = 32
shape = (axis_size,) * n
with pytest.raises(TypeError):
validate_spline_filter(
n=n,
axis_size=axis_size,
interp_order=3,
output=np.empty(shape),
axis=axis,
)
| 27.086792
| 74
| 0.631931
|
d30e86b6a8d03a9ae8581bf7274c03b8e121557d
| 2,687
|
cshtml
|
C#
|
ProjectsControl/Views/Customers/Search.cshtml
|
stevengazo/ProjectsControl
|
a55b4d685538deff0116073c7b54154d3a1a6440
|
[
"MIT"
] | null | null | null |
ProjectsControl/Views/Customers/Search.cshtml
|
stevengazo/ProjectsControl
|
a55b4d685538deff0116073c7b54154d3a1a6440
|
[
"MIT"
] | null | null | null |
ProjectsControl/Views/Customers/Search.cshtml
|
stevengazo/ProjectsControl
|
a55b4d685538deff0116073c7b54154d3a1a6440
|
[
"MIT"
] | null | null | null |
@model IEnumerable<ProjectsControl.Models.Customer>
@{
ViewData["Title"] = "Busqueda";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Busqueda de Clientes
</h2>
<div>
<a asp-controller="Customers" asp-action="Create">Registrar Cliente</a> | <a asp-controller="Customers" asp-action="Index">Listar Clientes </a>
</div>
<form asp-controller="Customers" asp-action="Search" method="get" >
<div class="form-group row">
<div class="col-4">
<input style="background-color: #f5f5f5;" type="text" name="IdToSearch" class="form-control rounded" placeholder="Cedula" />
</div>
<div class="col">
<input style="background-color: #f5f5f5;" type="text" name="NameToSearch" class="form-control rounded" placeholder="Nombre"/>
</div>
<div class="col">
<select style="background-color: #f5f5f5;" name="TypeToSearch" class="form-control rounded">
<option value="">Seleccione una opcion...</option>
@foreach (var item in ViewBag.TypesOfCustomers)
{
<option value="@item">@item</option>
}
</select>
</div>
<div class="col">
<input type="submit" value="Buscar" class="btn-outline-dark form-control" />
</div>
</div>
</form>
<div >
<p style="position:center; color:red;">@ViewBag.Message</p>
</div>
<table class="table table-hover table-striped table-responsive-sm table-bordered" style="font-size: 13px;text-align:center">
<thead>
<tr>
<th>
Cedula
</th>
<th>
Nombre
</th>
<th>
Sector
</th>
<th>
Acciones
</th>
</tr>
</thead>
<tbody style="font-size: 12px;">
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CustomerId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sector)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.CustomerId">Editar</a> |
<a asp-action="Details" asp-route-id="@item.CustomerId">Detalles</a> |
<a style="color:red" asp-action="Delete" asp-route-id="@item.CustomerId">Eliminar</a>
</td>
</tr>
}
</tbody>
</table>
| 31.244186
| 147
| 0.491626
|
9a998692ce6446c780f03cbad19906369ec8cb59
| 87
|
sh
|
Shell
|
run.sh
|
david-hagar/CubeDots
|
1c146653fe8abbef3420835ca0ceed1b07224c4c
|
[
"Apache-2.0"
] | null | null | null |
run.sh
|
david-hagar/CubeDots
|
1c146653fe8abbef3420835ca0ceed1b07224c4c
|
[
"Apache-2.0"
] | null | null | null |
run.sh
|
david-hagar/CubeDots
|
1c146653fe8abbef3420835ca0ceed1b07224c4c
|
[
"Apache-2.0"
] | null | null | null |
java -classpath target/CubeDots-1.0.jar com.purediscovery.vennlayout.ui.MainViewWindow
| 43.5
| 86
| 0.850575
|
5de81372c4ff0fa17b5851ca48828317269fde1f
| 2,496
|
cc
|
C++
|
cpp/art/scoped_thread_state_change.cc
|
fettdrac/ArtHook
|
76205461bbc620e9d516cbfa317c459e9e4620e6
|
[
"Apache-2.0"
] | 23
|
2019-08-13T04:55:20.000Z
|
2021-12-21T13:28:49.000Z
|
cpp/art/scoped_thread_state_change.cc
|
fettdrac/ArtHook
|
76205461bbc620e9d516cbfa317c459e9e4620e6
|
[
"Apache-2.0"
] | 1
|
2021-07-04T16:08:49.000Z
|
2021-07-04T16:08:49.000Z
|
cpp/art/scoped_thread_state_change.cc
|
fettdrac/ArtHook
|
76205461bbc620e9d516cbfa317c459e9e4620e6
|
[
"Apache-2.0"
] | 4
|
2019-08-22T01:49:11.000Z
|
2021-09-15T14:30:54.000Z
|
#include "scoped_thread_state_change.h"
#include "../base/log.h"
#include "../base/jni_helper.h"
#include "ARTSymbol.h"
namespace whale {
namespace art {
static volatile long kNoGCDaemonsGuard = 0;
jclass ScopedNoGCDaemons::java_lang_Daemons;
jmethodID ScopedNoGCDaemons::java_lang_Daemons_start;
jmethodID ScopedNoGCDaemons::java_lang_Daemons_stop;
void ScopedNoGCDaemons::Load(JNIEnv *env) {
java_lang_Daemons = reinterpret_cast<jclass>(env->NewGlobalRef(
env->FindClass("java/lang/Daemons")));
if (java_lang_Daemons == nullptr) {
JNIExceptionClear(env);
LOGE("java/lang/Daemons API is unavailable.");
return;
}
java_lang_Daemons_start = env->GetStaticMethodID(java_lang_Daemons, "start", "()V");
if (java_lang_Daemons_start == nullptr) {
JNIExceptionClear(env);
java_lang_Daemons_start = env->GetStaticMethodID(java_lang_Daemons, "startPostZygoteFork",
"()V");
}
if (java_lang_Daemons_start == nullptr) {
LOGE("java/lang/Daemons API is available but no start/startPostZygoteFork method.");
JNIExceptionClear(env);
}
java_lang_Daemons_stop = env->GetStaticMethodID(java_lang_Daemons, "stop", "()V");
JNIExceptionClear(env);
}
ScopedNoGCDaemons::ScopedNoGCDaemons(JNIEnv *env) : env_(env) {
if (java_lang_Daemons_start != nullptr) {
if (__sync_sub_and_fetch(&kNoGCDaemonsGuard, 1) <= 0) {
env_->CallStaticVoidMethod(java_lang_Daemons, java_lang_Daemons_stop);
JNIExceptionClear(env_);
}
}
}
ScopedNoGCDaemons::~ScopedNoGCDaemons() {
if (java_lang_Daemons_stop != nullptr) {
if (__sync_add_and_fetch(&kNoGCDaemonsGuard, 1) == 1) {
env_->CallStaticVoidMethod(java_lang_Daemons, java_lang_Daemons_start);
JNIExceptionClear(env_);
}
}
}
ScopedSuspendAll::ScopedSuspendAll() {
ManualControl(true);
}
ScopedSuspendAll::~ScopedSuspendAll() {
ManualControl(false);
}
void ScopedSuspendAll::ManualControl(bool suspend) {
ArtSymbolList *symbols = ARTSymbol::GetSymbol();
bool supported=(symbols->suspend_vm && symbols->resume_vm);
if (!supported) {
LOGE("Suspend VM API is unavailable.");
return;
}
if(suspend) {
symbols->suspend_vm();
}else{
symbols->resume_vm();
}
}
} // namespace art
} // namespace whale
| 30.439024
| 98
| 0.654647
|
cd70de6c4d2f82b7111060fd0557434d96044968
| 1,306
|
cshtml
|
C#
|
Views/Parts.AssociativyTagNodes.cshtml
|
Lombiq/Associativy-Tag-Nodes
|
c74546f45d6aefc1ef4e8a2f3a5cf8e1e9e1233d
|
[
"BSD-2-Clause"
] | null | null | null |
Views/Parts.AssociativyTagNodes.cshtml
|
Lombiq/Associativy-Tag-Nodes
|
c74546f45d6aefc1ef4e8a2f3a5cf8e1e9e1233d
|
[
"BSD-2-Clause"
] | null | null | null |
Views/Parts.AssociativyTagNodes.cshtml
|
Lombiq/Associativy-Tag-Nodes
|
c74546f45d6aefc1ef4e8a2f3a5cf8e1e9e1233d
|
[
"BSD-2-Clause"
] | null | null | null |
@using Orchard.ContentManagement;
@{
Style.Include("associativy-tag-nodes.css");
var part = (Associativy.TagNodes.Models.AssociativyTagNodesPart)Model.ContentPart;
var contentManager = part.ContentItem.ContentManager;
var allTagNodes = part.ConnectedTagNodes.SelectMany(kvp => kvp.Value);
var projectionRoute = part.TagNodeListingProjection != null ? contentManager.GetItemMetadata(part.TagNodeListingProjection).DisplayRouteValues : null;
var nodeHtmls = new List<IHtmlString>();
foreach (var node in allTagNodes)
{
if (nodeHtmls.Any())
{
nodeHtmls.Add(new HtmlString(", "));
}
var nodeDisplayText = contentManager.GetItemMetadata(node).DisplayText;
if (projectionRoute != null)
{
projectionRoute["TagNode"] = node.As<Associativy.Models.IAssociativyNodeLabelAspect>().Label;
nodeHtmls.Add(Html.RouteLink(nodeDisplayText, projectionRoute));
}
else
{
nodeHtmls.Add(new HtmlString(nodeDisplayText));
}
}
}
@if (nodeHtmls.Any())
{
<span class="associativy-tag-nodes-connected-nodes">
@foreach (var htmlString in nodeHtmls)
{
@htmlString
}
</span>
}
| 31.095238
| 155
| 0.628637
|
79675d2264b7dc90e3e93d2ec7bc6821eb2f7f19
| 5,093
|
php
|
PHP
|
packages/admin/src/Http/Livewire/Components/Settings/Attributes/AttributeEdit.php
|
DanielSpravtsev/getcandy
|
ca9119644338d5704bb85f73a0928d1fefbbddf0
|
[
"MIT"
] | null | null | null |
packages/admin/src/Http/Livewire/Components/Settings/Attributes/AttributeEdit.php
|
DanielSpravtsev/getcandy
|
ca9119644338d5704bb85f73a0928d1fefbbddf0
|
[
"MIT"
] | null | null | null |
packages/admin/src/Http/Livewire/Components/Settings/Attributes/AttributeEdit.php
|
DanielSpravtsev/getcandy
|
ca9119644338d5704bb85f73a0928d1fefbbddf0
|
[
"MIT"
] | null | null | null |
<?php
namespace GetCandy\Hub\Http\Livewire\Components\Settings\Attributes;
use GetCandy\Facades\FieldTypeManifest;
use GetCandy\Hub\Http\Livewire\Traits\Notifies;
use GetCandy\Hub\Http\Livewire\Traits\WithLanguages;
use GetCandy\Models\Attribute;
use GetCandy\Models\AttributeGroup;
use Illuminate\Support\Str;
use Livewire\Component;
class AttributeEdit extends Component
{
use WithLanguages;
use Notifies;
/**
* The attribute group.
*
* @var string
*/
public ?AttributeGroup $group = null;
/**
* The attribute instance.
*
* @var \GetCandy\Models\Attribute
*/
public ?Attribute $attribute = null;
/**
* Whether the panel should be visible.
*
* @var bool
*/
public bool $panelVisible = true;
/**
* Whether the user has input a handle manually.
*
* @var bool
*/
public bool $manualHandle = false;
/**
* {@inheritDoc}
*/
public function mount()
{
$this->attribute = $this->attribute ?: new Attribute([
'searchable' => true,
'filterable' => false,
'required' => false,
'section' => 'main',
'system' => false,
'type' => get_class($this->fieldTypes->first()),
]);
if ($this->attribute->id) {
$this->group = $this->attribute->attributeGroup;
}
}
public function updatedPanelVisible($val)
{
$this->emit('attribute-edit.closed');
}
/**
* {@inheritDoc}
*/
public function rules()
{
$rules = [
'attribute.name' => 'required',
"attribute.name.{$this->defaultLanguage->code}" => 'required|string|max:255',
'attribute.handle' => 'required',
'attribute.required' => 'nullable|boolean',
'attribute.searchable' => 'nullable|boolean',
'attribute.filterable' => 'nullable|boolean',
'attribute.configuration' => 'nullable|array',
'attribute.section' => 'string',
'attribute.system' => 'boolean',
'attribute.type' => 'required',
'attribute.validation_rules' => 'nullable|string',
];
if ($this->getFieldType()) {
$fieldTypeOptions = $this->getFieldTypeConfig()['options'] ?? [];
foreach ($fieldTypeOptions as $field => $validation) {
$rules["attribute.configuration.{$field}"] = $validation;
}
}
return $rules;
}
/**
* Return the available field types.
*
* @return \Illuminate\Support\Collection
*/
public function getFieldTypesProperty()
{
return FieldTypeManifest::getTypes();
}
/**
* Return the selected field type.
*
* @return
*/
public function getFieldType()
{
return app()->make($this->attribute->type);
}
/**
* Return the config for the field type.
*
* @return void
*/
public function getFieldTypeConfig()
{
return $this->getFieldType()?->getConfig() ?: null;
}
/**
* Format the handle on update to a slug.
*
* @return void
*/
public function updatedAttributeHandle()
{
$this->attribute->handle = Str::slug($this->attribute->handle);
}
public function formatHandle()
{
if (! $this->manualHandle && ! $this->attribute->handle) {
$this->attribute->handle = Str::slug(
$this->attribute->name[$this->defaultLanguage->code] ?? null
);
}
}
/**
* Save the attribute.
*
* @return void
*/
public function save()
{
$this->validate();
if (! $this->attribute->id) {
$this->attribute->attribute_type = $this->group->attributable_type;
$this->attribute->attribute_group_id = $this->group->id;
$this->attribute->position = Attribute::whereAttributeGroupId(
$this->group->id
)->count() + 1;
$this->attribute->save();
$this->notify(
__('adminhub::notifications.attribute-edit.created')
);
$this->emit('attribute-edit.created', $this->attribute->id);
return;
}
$this->attribute->save();
$this->notify(
__('adminhub::notifications.attribute-edit.updated')
);
$this->emit('attribute-edit.updated', $this->attribute->id);
}
/**
* Render the livewire component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('adminhub::livewire.components.settings.attributes.attribute-edit')
->layout('adminhub::layouts.base');
}
}
| 26.526042
| 89
| 0.514628
|
7beff6b15c1901c5b75ee5d97b8618cb8408adf2
| 7,525
|
cc
|
C++
|
source/blender/blenkernel/intern/node_tree_multi_function.cc
|
MiriamStout/blender-1
|
8b660ea0ecd2a8faa81012c7f849b86cff9bfac6
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1
|
2020-07-22T13:51:21.000Z
|
2020-07-22T13:51:21.000Z
|
source/blender/blenkernel/intern/node_tree_multi_function.cc
|
MiriamStout/blender-1
|
8b660ea0ecd2a8faa81012c7f849b86cff9bfac6
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
source/blender/blenkernel/intern/node_tree_multi_function.cc
|
MiriamStout/blender-1
|
8b660ea0ecd2a8faa81012c7f849b86cff9bfac6
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "BKE_node_tree_multi_function.hh"
namespace blender {
namespace bke {
/* Maybe this should be moved to BKE_node.h. */
static std::optional<fn::MFDataType> try_get_multi_function_data_type_of_socket(
const bNodeSocket *bsocket)
{
if (bsocket->typeinfo->get_mf_data_type == nullptr) {
return {};
}
return bsocket->typeinfo->get_mf_data_type();
}
static void insert_dummy_node(CommonMFNetworkBuilderData &common, const DNode &dnode)
{
constexpr uint stack_capacity = 10;
Vector<fn::MFDataType, stack_capacity> input_types;
Vector<StringRef, stack_capacity> input_names;
Vector<const DInputSocket *, stack_capacity> input_dsockets;
for (const DInputSocket *dsocket : dnode.inputs()) {
if (dsocket->is_available()) {
std::optional<fn::MFDataType> data_type = try_get_multi_function_data_type_of_socket(
dsocket->bsocket());
if (data_type.has_value()) {
input_types.append(*data_type);
input_names.append(dsocket->name());
input_dsockets.append(dsocket);
}
}
}
Vector<fn::MFDataType, stack_capacity> output_types;
Vector<StringRef, stack_capacity> output_names;
Vector<const DOutputSocket *, stack_capacity> output_dsockets;
for (const DOutputSocket *dsocket : dnode.outputs()) {
if (dsocket->is_available()) {
std::optional<fn::MFDataType> data_type = try_get_multi_function_data_type_of_socket(
dsocket->bsocket());
if (data_type.has_value()) {
output_types.append(*data_type);
output_names.append(dsocket->name());
output_dsockets.append(dsocket);
}
}
}
fn::MFDummyNode &dummy_node = common.network.add_dummy(
dnode.name(), input_types, output_types, input_names, output_names);
common.network_map.add(input_dsockets, dummy_node.inputs());
common.network_map.add(output_dsockets, dummy_node.outputs());
}
static bool has_data_sockets(const DNode &dnode)
{
for (const DInputSocket *socket : dnode.inputs()) {
if (is_multi_function_data_socket(socket->bsocket())) {
return true;
}
}
for (const DOutputSocket *socket : dnode.outputs()) {
if (is_multi_function_data_socket(socket->bsocket())) {
return true;
}
}
return false;
}
/**
* Expands all function nodes in the multi-function network. Nodes that don't have an expand
* function, but do have data sockets, will get corresponding dummy nodes.
*/
static void insert_nodes(CommonMFNetworkBuilderData &common)
{
for (const DNode *dnode : common.tree.nodes()) {
const bNodeType *node_type = dnode->node_ref().bnode()->typeinfo;
if (node_type->expand_in_mf_network != nullptr) {
NodeMFNetworkBuilder builder{common, *dnode};
node_type->expand_in_mf_network(builder);
}
else if (has_data_sockets(*dnode)) {
insert_dummy_node(common, *dnode);
}
}
}
static void insert_group_inputs(CommonMFNetworkBuilderData &common)
{
for (const DGroupInput *group_input : common.tree.group_inputs()) {
bNodeSocket *bsocket = group_input->bsocket();
if (is_multi_function_data_socket(bsocket)) {
bNodeSocketType *socktype = bsocket->typeinfo;
BLI_assert(socktype->expand_in_mf_network != nullptr);
SocketMFNetworkBuilder builder{common, *group_input};
socktype->expand_in_mf_network(builder);
fn::MFOutputSocket *from_socket = builder.built_socket();
BLI_assert(from_socket != nullptr);
common.network_map.add(*group_input, *from_socket);
}
}
}
static fn::MFOutputSocket *try_find_origin(CommonMFNetworkBuilderData &common,
const DInputSocket &to_dsocket)
{
Span<const DOutputSocket *> from_dsockets = to_dsocket.linked_sockets();
Span<const DGroupInput *> from_group_inputs = to_dsocket.linked_group_inputs();
uint total_linked_amount = from_dsockets.size() + from_group_inputs.size();
BLI_assert(total_linked_amount <= 1);
if (total_linked_amount == 0) {
return nullptr;
}
if (from_dsockets.size() == 1) {
return &common.network_map.lookup(*from_dsockets[0]);
}
else {
return &common.network_map.lookup(*from_group_inputs[0]);
}
}
static void insert_links(CommonMFNetworkBuilderData &common)
{
for (const DInputSocket *to_dsocket : common.tree.input_sockets()) {
if (!to_dsocket->is_available()) {
continue;
}
if (!is_multi_function_data_socket(to_dsocket->bsocket())) {
continue;
}
fn::MFOutputSocket *from_socket = try_find_origin(common, *to_dsocket);
if (from_socket == nullptr) {
continue;
}
Span<fn::MFInputSocket *> to_sockets = common.network_map.lookup(*to_dsocket);
BLI_assert(to_sockets.size() >= 1);
fn::MFDataType from_type = from_socket->data_type();
fn::MFDataType to_type = to_sockets[0]->data_type();
if (from_type != to_type) {
/* Todo: Try inserting implicit conversion. */
}
for (fn::MFInputSocket *to_socket : to_sockets) {
common.network.add_link(*from_socket, *to_socket);
}
}
}
static void insert_unlinked_input(CommonMFNetworkBuilderData &common, const DInputSocket &dsocket)
{
bNodeSocket *bsocket = dsocket.bsocket();
bNodeSocketType *socktype = bsocket->typeinfo;
BLI_assert(socktype->expand_in_mf_network != nullptr);
SocketMFNetworkBuilder builder{common, dsocket};
socktype->expand_in_mf_network(builder);
fn::MFOutputSocket *from_socket = builder.built_socket();
BLI_assert(from_socket != nullptr);
for (fn::MFInputSocket *to_socket : common.network_map.lookup(dsocket)) {
common.network.add_link(*from_socket, *to_socket);
}
}
static void insert_unlinked_inputs(CommonMFNetworkBuilderData &common)
{
Vector<const DInputSocket *> unlinked_data_inputs;
for (const DInputSocket *dsocket : common.tree.input_sockets()) {
if (dsocket->is_available()) {
if (is_multi_function_data_socket(dsocket->bsocket())) {
if (!dsocket->is_linked()) {
insert_unlinked_input(common, *dsocket);
}
}
}
}
}
/**
* Expands all function nodes contained in the given node tree within the given multi-function
* network.
*
* Returns a mapping between the original node tree and the generated nodes/sockets for further
* processing.
*/
MFNetworkTreeMap insert_node_tree_into_mf_network(fn::MFNetwork &network,
const DerivedNodeTree &tree,
ResourceCollector &resources)
{
MFNetworkTreeMap network_map{tree};
CommonMFNetworkBuilderData common{resources, network, network_map, tree};
insert_nodes(common);
insert_group_inputs(common);
insert_links(common);
insert_unlinked_inputs(common);
return network_map;
}
} // namespace bke
} // namespace blender
| 32.15812
| 98
| 0.706179
|
d6d45fc632870dbff42a6a5cad3d23cb4905580c
| 5,938
|
dart
|
Dart
|
lib/features/home/data/models/location_model.freezed.dart
|
Alg0r1thmic/rick-and-morty-info
|
0d1bbe679490f97a4e8d930a388d586ab42a4488
|
[
"MIT"
] | 1
|
2021-02-03T16:44:02.000Z
|
2021-02-03T16:44:02.000Z
|
lib/features/home/data/models/location_model.freezed.dart
|
Alg0r1thmic/rick-and-morty-info
|
0d1bbe679490f97a4e8d930a388d586ab42a4488
|
[
"MIT"
] | null | null | null |
lib/features/home/data/models/location_model.freezed.dart
|
Alg0r1thmic/rick-and-morty-info
|
0d1bbe679490f97a4e8d930a388d586ab42a4488
|
[
"MIT"
] | null | null | null |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies
part of 'location_model.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
LocationModel _$LocationModelFromJson(Map<String, dynamic> json) {
return _LocationModel.fromJson(json);
}
/// @nodoc
class _$LocationModelTearOff {
const _$LocationModelTearOff();
// ignore: unused_element
_LocationModel call(
{@required String id,
@required String name,
@required String type,
@required String dimension}) {
return _LocationModel(
id: id,
name: name,
type: type,
dimension: dimension,
);
}
// ignore: unused_element
LocationModel fromJson(Map<String, Object> json) {
return LocationModel.fromJson(json);
}
}
/// @nodoc
// ignore: unused_element
const $LocationModel = _$LocationModelTearOff();
/// @nodoc
mixin _$LocationModel {
String get id;
String get name;
String get type;
String get dimension;
Map<String, dynamic> toJson();
$LocationModelCopyWith<LocationModel> get copyWith;
}
/// @nodoc
abstract class $LocationModelCopyWith<$Res> {
factory $LocationModelCopyWith(
LocationModel value, $Res Function(LocationModel) then) =
_$LocationModelCopyWithImpl<$Res>;
$Res call({String id, String name, String type, String dimension});
}
/// @nodoc
class _$LocationModelCopyWithImpl<$Res>
implements $LocationModelCopyWith<$Res> {
_$LocationModelCopyWithImpl(this._value, this._then);
final LocationModel _value;
// ignore: unused_field
final $Res Function(LocationModel) _then;
@override
$Res call({
Object id = freezed,
Object name = freezed,
Object type = freezed,
Object dimension = freezed,
}) {
return _then(_value.copyWith(
id: id == freezed ? _value.id : id as String,
name: name == freezed ? _value.name : name as String,
type: type == freezed ? _value.type : type as String,
dimension: dimension == freezed ? _value.dimension : dimension as String,
));
}
}
/// @nodoc
abstract class _$LocationModelCopyWith<$Res>
implements $LocationModelCopyWith<$Res> {
factory _$LocationModelCopyWith(
_LocationModel value, $Res Function(_LocationModel) then) =
__$LocationModelCopyWithImpl<$Res>;
@override
$Res call({String id, String name, String type, String dimension});
}
/// @nodoc
class __$LocationModelCopyWithImpl<$Res>
extends _$LocationModelCopyWithImpl<$Res>
implements _$LocationModelCopyWith<$Res> {
__$LocationModelCopyWithImpl(
_LocationModel _value, $Res Function(_LocationModel) _then)
: super(_value, (v) => _then(v as _LocationModel));
@override
_LocationModel get _value => super._value as _LocationModel;
@override
$Res call({
Object id = freezed,
Object name = freezed,
Object type = freezed,
Object dimension = freezed,
}) {
return _then(_LocationModel(
id: id == freezed ? _value.id : id as String,
name: name == freezed ? _value.name : name as String,
type: type == freezed ? _value.type : type as String,
dimension: dimension == freezed ? _value.dimension : dimension as String,
));
}
}
@JsonSerializable()
/// @nodoc
class _$_LocationModel implements _LocationModel {
const _$_LocationModel(
{@required this.id,
@required this.name,
@required this.type,
@required this.dimension})
: assert(id != null),
assert(name != null),
assert(type != null),
assert(dimension != null);
factory _$_LocationModel.fromJson(Map<String, dynamic> json) =>
_$_$_LocationModelFromJson(json);
@override
final String id;
@override
final String name;
@override
final String type;
@override
final String dimension;
@override
String toString() {
return 'LocationModel(id: $id, name: $name, type: $type, dimension: $dimension)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other is _LocationModel &&
(identical(other.id, id) ||
const DeepCollectionEquality().equals(other.id, id)) &&
(identical(other.name, name) ||
const DeepCollectionEquality().equals(other.name, name)) &&
(identical(other.type, type) ||
const DeepCollectionEquality().equals(other.type, type)) &&
(identical(other.dimension, dimension) ||
const DeepCollectionEquality()
.equals(other.dimension, dimension)));
}
@override
int get hashCode =>
runtimeType.hashCode ^
const DeepCollectionEquality().hash(id) ^
const DeepCollectionEquality().hash(name) ^
const DeepCollectionEquality().hash(type) ^
const DeepCollectionEquality().hash(dimension);
@override
_$LocationModelCopyWith<_LocationModel> get copyWith =>
__$LocationModelCopyWithImpl<_LocationModel>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$_$_LocationModelToJson(this);
}
}
abstract class _LocationModel implements LocationModel {
const factory _LocationModel(
{@required String id,
@required String name,
@required String type,
@required String dimension}) = _$_LocationModel;
factory _LocationModel.fromJson(Map<String, dynamic> json) =
_$_LocationModel.fromJson;
@override
String get id;
@override
String get name;
@override
String get type;
@override
String get dimension;
@override
_$LocationModelCopyWith<_LocationModel> get copyWith;
}
| 28.411483
| 246
| 0.665039
|
49a7b3f98c11d54dd69d204ce32f1d39f37c7558
| 1,755
|
lua
|
Lua
|
world/Plugins/Core/tell.lua
|
yangchuansheng/dockercraft
|
b606ddae081a2c461de243f3a0c0acaa9103df9c
|
[
"Apache-2.0"
] | 119
|
2015-11-24T04:29:15.000Z
|
2022-03-23T06:43:14.000Z
|
world/Plugins/Core/tell.lua
|
rtannert/dockercraft
|
520171a32a84bad7bbd2eb5cc27ab0166b46bbc4
|
[
"Apache-2.0"
] | 1
|
2016-05-26T21:47:38.000Z
|
2016-05-26T21:47:38.000Z
|
world/Plugins/Core/tell.lua
|
rtannert/dockercraft
|
520171a32a84bad7bbd2eb5cc27ab0166b46bbc4
|
[
"Apache-2.0"
] | 16
|
2016-09-26T07:38:00.000Z
|
2022-01-07T21:15:37.000Z
|
function HandleTellCommand(Split, Player)
if (Split[2] == nil) or (Split[3] == nil) then
SendMessage( Player, "Usage: "..Split[1].." <player> <message ...>")
return true
end
local FoundPlayer = false
local SendMessage = function(OtherPlayer)
if (OtherPlayer:GetName() == Split[2]) then
local newSplit = table.concat( Split, " ", 3 )
SendMessageSuccess( Player, "Message to player " .. Split[2] .. " sent!" )
OtherPlayer:SendMessagePrivateMsg(newSplit, Player:GetName())
lastsender[OtherPlayer:GetName()] = Player:GetName()
FoundPlayer = true
end
end
cRoot:Get():ForEachPlayer(SendMessage)
if not FoundPlayer then
SendMessageFailure( Player, 'Player "' ..Split[2].. '" not found')
end
return true;
end
function HandleRCommand(Split,Player)
if Split[2] == nil then
Player:SendMessageInfo("Usage: "..Split[1].." <message ...>")
else
local SendMessage = function(OtherPlayer)
if (OtherPlayer:GetName() == lastsender[Player:GetName()]) then
local newSplit = table.concat( Split, " ", 2 )
Player:SendMessageSuccess( "Message to player " .. lastsender[Player:GetName()] .. " sent!" )
OtherPlayer:SendMessagePrivateMsg(newSplit, Player:GetName())
lastsender[OtherPlayer:GetName()] = Player:GetName()
return true
end
end
if lastsender[Player:GetName()] == nil then
Player:SendMessageFailure("No last sender found")
else
if (not(cRoot:Get():FindAndDoWithPlayer(lastsender[Player:GetName()], SendMessage))) then
Player:SendMessageFailure("Player not found")
end
end
end
return true
end
| 31.339286
| 109
| 0.623362
|
ef1e2e1ba96f99019a5b7dc975bfa8105c3fee44
| 21,197
|
c
|
C
|
customer_app/pinedio_st7789/pinedio_st7789/display.c
|
lupyuen/bl_iot_sdk
|
bf0353acfef4e30afee914c74e9f8023e6ca06c0
|
[
"Apache-2.0"
] | 21
|
2020-12-26T08:28:10.000Z
|
2022-02-15T00:23:53.000Z
|
customer_app/pinedio_st7789/pinedio_st7789/display.c
|
lupyuen/bl_iot_sdk
|
bf0353acfef4e30afee914c74e9f8023e6ca06c0
|
[
"Apache-2.0"
] | 4
|
2021-09-04T02:15:21.000Z
|
2021-11-15T01:12:40.000Z
|
customer_app/pinedio_st7789/pinedio_st7789/display.c
|
lupyuen/bl_iot_sdk
|
bf0353acfef4e30afee914c74e9f8023e6ca06c0
|
[
"Apache-2.0"
] | 4
|
2021-03-19T07:31:46.000Z
|
2021-12-02T15:01:24.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Display Driver for ST7789 SPI in 3-Wire (9-bit) Mode.
// Normally we connect to ST7789 in 4-Wire (8-bit) Mode: https://lupyuen.github.io/images/st7789-4wire.jpg
// But for PineDio Stack we use 3-Wire (9-bit) Mode: https://lupyuen.github.io/images/st7789-3wire.jpg
// This means we will pack 9-bit data into bytes for transmitting over 8-bit SPI.
// We will send in multiples of 9 bytes (9 bits x 8), padded with the NOP Command (code 0x00).
// Based on https://gitlab.com/lupyuen/pinetime_lvgl_mynewt/-/blob/master/src/pinetime/display.c
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <FreeRTOS.h> // For vTaskDelay
#include <task.h> // For vTaskDelay
#include <device/vfs_spi.h> // For spi_ioc_transfer_t
#include <hal/soc/spi.h> // For hal_spi_transfer
#include <bl_gpio.h> // For bl_gpio_output_set
#include <bl602_glb.h> // For GLB_GPIO_Func_Init
#include "display.h" // For Display Pins and Functions
#include "demo.h"
/// SPI Device Instance. TODO: Move to demo.h
extern spi_dev_t spi_device;
/// Screen Size
#define ROW_COUNT LV_VER_RES_MAX // 240 rows of pixels
#define COL_COUNT LV_HOR_RES_MAX // 240 columns of pixels
#define BYTES_PER_PIXEL (LV_COLOR_DEPTH / 8) // 2 bytes per pixel (RGB565 colour)
/// ST7789 Colour Settings
#define INVERTED 1 // Display colours are inverted
#define RGB 1 // Display colours are RGB
/// ST7789 Commands. From https://github.com/almindor/st7789/blob/master/src/instruction.rs
#define NOP 0x00
#define SWRESET 0x01
#define RDDID 0x04
#define RDDST 0x09
#define SLPIN 0x10
#define SLPOUT 0x11
#define PTLON 0x12
#define NORON 0x13
#define INVOFF 0x20
#define INVON 0x21
#define DISPOFF 0x28
#define DISPON 0x29
#define CASET 0x2A
#define RASET 0x2B
#define RAMWR 0x2C
#define RAMRD 0x2E
#define PTLAR 0x30
#define VSCRDER 0x33
#define MADCTL 0x36
#define VSCAD 0x37
#define COLMOD 0x3A
/// ST7789 Orientation. From https://github.com/almindor/st7789/blob/master/src/lib.rs#L42-L52
#define Portrait 0x00 // No inverting
#define Landscape 0x60 // Invert column and page/column order
#define PortraitSwapped 0xC0 // Invert page and column order
#define LandscapeSwapped 0xA0 // Invert page and page/column order
static int set_orientation(uint8_t orientation);
static void set_data_command(uint8_t data_command0);
static int transmit_unpacked(const uint8_t *data, uint16_t len);
static int transmit_packed(const uint8_t *data, uint16_t len);
static void pack_byte(uint8_t u);
static void copy_bits(uint8_t src, uint8_t src_start_bit, uint8_t src_end_bit,
uint16_t dest_index, uint8_t dest_start_bit);
static void delay_ms(uint32_t ms);
/// RGB565 Image. Converted by https://github.com/lupyuen/pinetime-graphic
/// from PNG file https://github.com/lupyuen/lupyuen.github.io/blob/master/images/display-jewel.png
static const uint8_t image_data[] = { // Should be 115,200 bytes
#include "image.inc"
};
/// SPI Buffer for unpacked 8-bit data. We always copy pixels from Flash ROM to RAM
/// before transmitting, because Flash ROM may be too slow for DMA at 4 MHz.
/// Contains 10 rows of 240 pixels of 2 bytes each (16-bit colour).
uint8_t spi_unpacked_buf[BUFFER_ROWS * COL_COUNT * BYTES_PER_PIXEL];
/// SPI Buffer for packed 9-bit data
/// Contains 10 rows of 240 pixels of 2 bytes each (16-bit colour).
uint8_t spi_packed_buf[BUFFER_ROWS * COL_COUNT * BYTES_PER_PIXEL * 4]; // TODO
/// SPI Receive Buffer. We don't actually receive data, but SPI Transfer needs this.
/// Contains 10 rows of 240 pixels of 2 bytes each (16-bit colour).
static uint8_t spi_rx_buf[BUFFER_ROWS * COL_COUNT * BYTES_PER_PIXEL * 4]; // TODO
/// Initialise the ST7789 display controller and switch on backlight.
/// Assumes that SPI port 0 has been initialised.
/// Assumes that DISPLAY_CS_PIN, DISPLAY_BLK_PIN, DISPLAY_DEBUG_CS_PIN have been configured for GPIO Output.
/// Based on https://github.com/almindor/st7789/blob/master/src/lib.rs
int init_display(void) {
// Switch on backlight
int rc = backlight_on(); assert(rc == 0);
#ifdef NOTUSED
// Reset the display controller through the Reset Pin
rc = hard_reset(); assert(rc == 0);
#endif // NOTUSED
// Software Reset: Reset the display controller through firmware (ST7789 Datasheet Page 163)
// https://www.rhydolabz.com/documents/33/ST7789.pdf
rc = write_command(SWRESET, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0);
delay_ms(200); // Need to wait at least 200 milliseconds
// Sleep Out: Disable sleep (ST7789 Datasheet Page 184)
rc = write_command(SLPOUT, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0);
delay_ms(200); // Need to wait at least 200 milliseconds
// Vertical Scrolling Definition: 0 TSA, 320 VSA, 0 BSA (ST7789 Datasheet Page 208)
static const uint8_t VSCRDER_PARA[] = { 0x00, 0x00, 0x14, 0x00, 0x00, 0x00 };
rc = write_command(VSCRDER, VSCRDER_PARA, sizeof(VSCRDER_PARA)); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
// Normal Display Mode On (ST7789 Datasheet Page 187)
rc = write_command(NORON, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0);
delay_ms(10); // Need to wait at least 10 milliseconds
// Display Inversion: Invert the display colours (light becomes dark and vice versa) (ST7789 Datasheet Pages 188, 190)
if (INVERTED) {
rc = write_command(INVON, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
} else {
rc = write_command(INVOFF, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
}
// Set display orientation to Portrait
rc = set_orientation(Portrait); assert(rc == 0);
// Interface Pixel Format: 16-bit RGB565 colour (ST7789 Datasheet Page 224)
static const uint8_t COLMOD_PARA[] = { 0x55 };
rc = write_command(COLMOD, COLMOD_PARA, sizeof(COLMOD_PARA)); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
// Display On: Turn on display (ST7789 Datasheet Page 196)
rc = write_command(DISPON, NULL, 0); assert(rc == 0);
rc = flush_display(); assert(rc == 0);
delay_ms(200); // Need to wait at least 200 milliseconds
return 0;
}
/// Display image on ST7789 display controller
int display_image(void) {
// Render each batch of 10 rows
printf("Displaying image...\r\n");
for (uint8_t row = 0; row < ROW_COUNT; row += BUFFER_ROWS) {
// Compute the (left, top) and (right, bottom) coordinates of the 10-row window
uint8_t top = row;
uint8_t bottom = (row + BUFFER_ROWS - 1) < ROW_COUNT
? (row + BUFFER_ROWS - 1)
: (ROW_COUNT - 1);
uint8_t left = 0;
uint8_t right = COL_COUNT - 1;
// Compute the image offset and how many bytes we will transmit
uint32_t offset = ((top * COL_COUNT) + left) * BYTES_PER_PIXEL;
uint16_t len = (bottom - top + 1) * (right - left + 1) * BYTES_PER_PIXEL;
// Copy the image pixels from Flash ROM to RAM, because Flash ROM may be too slow for DMA at 4 MHz
////memcpy(spi_unpacked_buf, image_data + offset, len);
memset(spi_unpacked_buf, 0xAA, len); //// TODO: Test RGB565 colour 0xAAAA
// Set the display window
int rc = set_window(left, top, right, bottom); assert(rc == 0);
// Memory Write: Write the bytes from RAM to display (ST7789 Datasheet Page 202)
rc = write_command(RAMWR, NULL, 0); assert(rc == 0);
rc = write_data(spi_unpacked_buf, len); assert(rc == 0);
rc = flush_display(); assert(rc == 0);
delay_ms(10); //// TODO: Remove this delay
}
printf("Image displayed\r\n");
return 0;
}
/// Set the ST7789 display window to the coordinates (left, top), (right, bottom)
int set_window(uint8_t left, uint8_t top, uint8_t right, uint8_t bottom) {
assert(left < COL_COUNT && right < COL_COUNT && top < ROW_COUNT && bottom < ROW_COUNT);
assert(left <= right);
assert(top <= bottom);
// Set Address Window Columns (ST7789 Datasheet Page 198)
int rc = write_command(CASET, NULL, 0); assert(rc == 0);
uint8_t col_para[4] = { 0x00, left, 0x00, right };
rc = write_data(col_para, 4); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
// Set Address Window Rows (ST7789 Datasheet Page 200)
rc = write_command(RASET, NULL, 0); assert(rc == 0);
uint8_t row_para[4] = { 0x00, top, 0x00, bottom };
rc = write_data(row_para, 4); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
return 0;
}
/// Set the display orientation: Portrait, Landscape, PortraitSwapped or LandscapeSwapped
static int set_orientation(uint8_t orientation) {
// Memory Data Access Control (ST7789 Datasheet Page 215)
if (RGB) {
uint8_t orientation_para[1] = { orientation };
int rc = write_command(MADCTL, orientation_para, 1); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
} else {
uint8_t orientation_para[1] = { orientation | 0x08 };
int rc = write_command(MADCTL, orientation_para, 1); assert(rc == 0);
rc = flush_display(); assert(rc == 0); ////
}
return 0;
}
/// Write unpacked 8-bit ST7789 command and parameters to SPI Buffer. `params` is the array of parameter bytes, `len` is the number of parameters.
int write_command(uint8_t command, const uint8_t *params, uint16_t len) {
// Set Data / Command Bit to Low to tell ST7789 this is a command
set_data_command(0);
// Transmit the command byte
int rc = transmit_unpacked(&command, 1);
assert(rc == 0);
// Transmit the parameters as data bytes
if (params != NULL && len > 0) {
rc = write_data(params, len);
assert(rc == 0);
}
return 0;
}
/// Write unpacked 8-bit ST7789 data to SPI Buffer. `data` is the array of bytes to be transmitted, `len` is the number of bytes.
int write_data(const uint8_t *data, uint16_t len) {
// Set Data / Command Bit to High to tell ST7789 this is data
set_data_command(1);
// Transmit the data bytes
int rc = transmit_unpacked(data, len);
assert(rc == 0);
return 0;
}
/// 0 if we sending a command byte, 1 if we are sending data bytes
static uint8_t data_command = 0;
/// 0 if we sending a command byte, 1 if we are sending data bytes
static void set_data_command(uint8_t data_command0) {
assert(data_command0 == 0 || data_command0 == 1);
data_command = data_command0;
// Previously for 4-Wire 8-bit mode:
// int rc = bl_gpio_output_set(DISPLAY_DC_PIN, data_command0); assert(rc == 0);
}
/// Number of bytes used in spi_unpacked_buf
static uint16_t spi_unpacked_len = 0;
/// Number of bytes used in spi_packed_buf
static uint16_t spi_packed_len = 0;
/// Write unpacked 8-bit data to the packed SPI Buffer. `data` is the array of bytes to be written. `len` is the number of bytes.
static int transmit_unpacked(const uint8_t *data, uint16_t len) {
if (len == 0) { return 0; } // Nothing to transmit
for (uint16_t i = 0; i < len; i++) {
// Pack the byte into the packed SPI Buffer
pack_byte(data[i]);
}
return 0;
}
/*
To pack 9-bit data into bytes, we do this for every 8 bytes of unpacked data:
(Most Significant Bit first)
If Unpacked Length mod 8 is...
0:
DC -> P0 bit 7
U bits 1 to 7 -> P0 bits 0 to 6
U bits 0 to 0 -> P1 bits 7 to 7
1:
DC -> P0 bit 6
U bits 2 to 7 -> P0 bits 0 to 5
U bits 0 to 1 -> P1 bits 6 to 7
2:
DC -> P0 bit 5
U bits 3 to 7 -> P0 bits 0 to 4
U bits 0 to 2 -> P1 bits 5 to 7
...
6:
DC -> P0 bit 1
U bits 7 to 7 -> P0 bits 0 to 0
U bits 0 to 6 -> P1 bits 1 to 7
7:
DC -> P0 bit 0
U bits 0 to 7 -> P1 bits 0 to 7
Where...
DC is the Data/Command bit (0 = command, 1 = data)
U is the unpacked 8-bit data byte,
P0 is the current byte of the packed data,
P1 is the next byte of the packed data.
*/
/// Pack the unpacked byte into the packed SPI Buffer
static void pack_byte(uint8_t u) {
// MOD is the unpacked length mod 8
uint8_t mod = spi_unpacked_len % 8;
spi_unpacked_len += 1;
// Grow the packed data length.
// For MOD=0: We will write 2 new packed bytes (partial).
// For MOD=1 to 7: We will write 1 new packed byte (partial or full).
if (mod == 0) { spi_packed_len += 2; }
else { spi_packed_len += 1; }
// P0 is the second-last byte of the packed data
uint16_t p0_index = spi_packed_len - 2;
assert(p0_index < spi_packed_len);
assert(p0_index < sizeof(spi_packed_buf));
// P1 is the last byte of the packed data
uint16_t p1_index = p0_index + 1;
assert(p1_index < spi_packed_len);
assert(p1_index < sizeof(spi_packed_buf));
// For MOD=0: DC -> P0 bit 7
// For MOD=1: DC -> P0 bit 6
// For MOD=6: DC -> P0 bit 1
// For MOD=7: DC -> P0 bit 0
uint8_t dc_bit = 7 - mod;
copy_bits( // Copy the bits...
data_command, // From Data/Command bit (0 = command, 1 = data)
0, // Start at bit 0
0, // End at bit 0
p0_index, // To destination P0
dc_bit // At DC Bit
);
// For MOD=0: U bits 1 to 7 -> P0 bits 0 to 6
// For MOD=1: U bits 2 to 7 -> P0 bits 0 to 5
// For MOD=6: U bits 7 to 7 -> P0 bits 0 to 0
// For MOD=7: No change to P0
if (mod < 7) {
uint8_t u_start = (mod + 1) % 8;
uint8_t u_end = 7;
uint8_t p0_start = 0;
copy_bits( // Copy the bits...
u, // From unpacked byte
u_start, // Start at this bit
u_end, // End at this bit
p0_index, // To destination P0
p0_start // Start at this bit
);
}
// For MOD=0: U bits 0 to 0 -> P1 bits 7 to 7
// For MOD=1: U bits 0 to 1 -> P1 bits 6 to 7
// For MOD=6: U bits 0 to 6 -> P1 bits 1 to 7
// For MOD=7: U bits 0 to 7 -> P1 bits 0 to 7
uint8_t u_start = 0;
uint8_t u_end = mod;
uint8_t p1_start = 7 - mod;
copy_bits( // Copy the bits...
u, // From unpacked byte
u_start, // Start at this bit
u_end, // End at this bit
p1_index, // To destination P1
p1_start // Start at this bit
);
}
/// Copy the bits from src, starting at bit src_start_bit, ending at bit src_end_bit,
/// to spi_packed_buf[dest_index], starting at dest_start_bit.
static void copy_bits(uint8_t src, uint8_t src_start_bit, uint8_t src_end_bit,
uint16_t dest_index, uint8_t dest_start_bit) {
uint8_t num_bits = src_end_bit - src_start_bit + 1;
assert(num_bits <= 8);
assert(src_end_bit <= 7);
assert(src_start_bit <= 7);
assert(src_start_bit <= src_end_bit);
assert(dest_start_bit + num_bits <= 8);
assert(dest_index < spi_packed_len);
assert(dest_index < sizeof(spi_packed_buf));
// Assume src_start_bit=2, src_end_bit=5, dest_start_bit=3, num_bits=4
// If the Src Bits are ??xxxx??, shift the bits to become 00??xxxx
uint8_t src_shift = src >> src_start_bit;
// Mask out the Src Bits: 00??xxxx becomes 0000xxxx
uint8_t src_mask = (1 << num_bits) - 1;
src_shift &= src_mask;
// Shift the bits 0000xxxx to match the Dest Start Bit: 0xxxx000
uint8_t dest_shift = src_shift << dest_start_bit;
// Get the Dest Byte y????yyy
uint8_t dest = spi_packed_buf[dest_index];
// Compute the Dest Mask 01111000
uint8_t dest_mask = ((1 << num_bits) - 1)
<< dest_start_bit;
// Mask out the Dest Bits: y????yyy becomes y0000yyy
dest &= ~dest_mask;
// Merge with the shifted bits to become yxxxxyyy
dest |= dest_shift;
// Update the Dest Byte
spi_packed_buf[dest_index] = dest;
}
/// Transmit the packed SPI Buffer to ST7789
int flush_display(void) {
if (spi_packed_len == 0) { return 0; } // Nothing to transmit
// Fill the remaining packed data with NOP (0x00)
// up to the end of the of the 8-byte unpacked chunk
// TODO: Optimise this
data_command = 0; // Sending a NOP Command
while (spi_unpacked_len % 8 != 0) {
pack_byte(0x00); // Command NOP
}
// We only transmit in chunks of 8 bytes of unpacked data,
// equivalent to 9 bytes of packed data.
assert(spi_unpacked_len % 8 == 0);
assert(spi_packed_len % 9 == 0);
assert(spi_packed_len <= sizeof(spi_packed_buf));
// Tranmsit the packed data
int rc = transmit_packed(spi_packed_buf, spi_packed_len);
// Reset the unpacked and packed lengths
spi_unpacked_len = 0;
spi_packed_len = 0;
return rc;
}
/// Write packed data to the SPI port. `data` is the array of bytes to be written. `len` is the number of bytes.
static int transmit_packed(const uint8_t *data, uint16_t len) {
assert(data != NULL);
if (len == 0) { return 0; }
if (len > sizeof(spi_rx_buf)) { printf("transmit_packed error: Too much data %d\r\n", len); return 1; }
// Dump the data
printf("SPI Tx: %d bytes:\r\n", (int) len); int i;
for (i = 0; i < 20 && i < len; i++) { printf(" %02x", data[i]); }
if (i < len) { printf("..."); }
printf("\r\n");
// Clear the receive buffer
memset(&spi_rx_buf, 0, sizeof(spi_rx_buf));
// Prepare SPI Transfer
static spi_ioc_transfer_t transfer;
memset(&transfer, 0, sizeof(transfer));
transfer.tx_buf = (uint32_t) data; // Transmit Buffer
transfer.rx_buf = (uint32_t) spi_rx_buf; // Receive Buffer
transfer.len = len; // How many bytes
// Select the SPI Peripheral
printf("Set CS pin %d to low\r\n", DISPLAY_CS_PIN);
int rc = bl_gpio_output_set(DISPLAY_CS_PIN, 0);
assert(rc == 0);
// TODO: Remove in production
printf("Set Debug CS pin %d to low\r\n", DISPLAY_DEBUG_CS_PIN);
rc = bl_gpio_output_set(DISPLAY_DEBUG_CS_PIN, 0);
assert(rc == 0);
// Execute the SPI Transfer with the DMA Controller
rc = hal_spi_transfer(
&spi_device, // SPI Device
&transfer, // SPI Transfers
1 // How many transfers (Number of requests, not bytes)
);
assert(rc == 0);
// DMA Controller will transmit and receive the SPI data in the background.
// hal_spi_transfer will wait for the SPI Transfer to complete before returning.
// Now that we're done with the SPI Transfer...
// De-select the SPI Peripheral
rc = bl_gpio_output_set(DISPLAY_CS_PIN, 1);
assert(rc == 0);
printf("Set CS pin %d to high\r\n", DISPLAY_CS_PIN);
// TODO: Remove in production
rc = bl_gpio_output_set(DISPLAY_DEBUG_CS_PIN, 1);
assert(rc == 0);
printf("Set Debug CS pin %d to high\r\n", DISPLAY_DEBUG_CS_PIN);
return 0;
}
#ifdef NOTUSED
/// Reset the display controller
static int hard_reset(void) {
// Toggle the Reset Pin: High, Low, High
int rc;
rc = bl_gpio_output_set(DISPLAY_RST_PIN, 1); assert(rc == 0);
rc = bl_gpio_output_set(DISPLAY_RST_PIN, 0); assert(rc == 0);
rc = bl_gpio_output_set(DISPLAY_RST_PIN, 1); assert(rc == 0);
return 0;
}
#endif // NOTUSED
/// Switch on backlight
int backlight_on(void) {
// Set the Backlight Pin to Low
printf("Set BLK pin %d to low\r\n", DISPLAY_BLK_PIN);
int rc = bl_gpio_output_set(DISPLAY_BLK_PIN, 0);
assert(rc == 0);
return 0;
// Can we have multiple levels of backlight brightness?
// Yes! Configure the Backlight Pin as a PWM Pin (instead of GPIO).
// Set the PWM Duty Cycle to control the brightness.
// See https://lupyuen.github.io/articles/led#from-gpio-to-pulse-width-modulation-pwm
}
/// Switch off backlight
int backlight_off(void) {
// Set the Backlight Pin to High
printf("Set BLK pin %d to high\r\n", DISPLAY_BLK_PIN);
int rc = bl_gpio_output_set(DISPLAY_BLK_PIN, 1);
assert(rc == 0);
return 0;
}
/// Delay for the specified number of milliseconds
static void delay_ms(uint32_t millisec) {
printf("Sleep %d ms\r\n", millisec);
vTaskDelay(millisec / portTICK_PERIOD_MS);
}
| 37.717082
| 146
| 0.649573
|
0770b2722d1212ff8054b14ee5c18325e509a080
| 7,432
|
rb
|
Ruby
|
spec/plugins/software_spec.rb
|
MarkGibbons/ohai_software
|
ccd1b61dbd89a7c876c0fcf2b1c26a76438b2176
|
[
"Apache-2.0"
] | 2
|
2016-03-16T16:42:31.000Z
|
2018-10-15T15:01:54.000Z
|
spec/plugins/software_spec.rb
|
MarkGibbons/ohai_software
|
ccd1b61dbd89a7c876c0fcf2b1c26a76438b2176
|
[
"Apache-2.0"
] | null | null | null |
spec/plugins/software_spec.rb
|
MarkGibbons/ohai_software
|
ccd1b61dbd89a7c876c0fcf2b1c26a76438b2176
|
[
"Apache-2.0"
] | null | null | null |
#
# Cookbook Name:: ohai_software
#
# Copyright 2015, Nordstrom, Inc.
#
# Apache2 license as specified in the License file.
#
require 'ohai'
require 'ostruct'
require 'spec_helper'
describe Ohai::System, 'Software plugin - solaris happy path' do
before(:each) do
@plugin = get_plugin('software.rb')
allow(@plugin).to receive(:collect_os).and_return(:solaris2)
std_stubs
@plugin.run
end
it 'Runs successfully' do
expect { @plugin }.to_not raise_error
end
it 'Returns a Mash' do
expect @plugin.to be_a_kind_of(Mash)
end
it 'should return the vas version' do
expect(@plugin[:software][:vas][:version]).to eq '4.1.0.21267'
end
it 'should return the vmware version' do
expect(@plugin[:software][:vmware][:version]).to eq '8.6.11.26309'
end
it 'should return the vxfs version' do
expect(@plugin[:software][:vxfs][:version]).to eq '5.1SP1RP4'
end
it 'vas should be installed' do
expect(@plugin[:software][:vas][:installed]).to eq true
end
it 'vmware should be installed' do
expect(@plugin[:software][:vmware][:installed]).to eq true
end
it 'vxfs should be installed' do
expect(@plugin[:software][:vxfs][:installed]).to eq true
end
end
describe Ohai::System, 'Software plugin - no version programs found' do
before(:each) do
@plugin = get_plugin('software.rb')
allow(@plugin).to receive(:collect_os).and_return(:linux)
std_stubs
allow(@plugin).to receive(:shell_out).with('modinfo vxfs').and_return(vxfs_version_none)
allow(File).to receive(:executable?).with('/opt/quest/bin/vastool').and_return(false)
allow(File).to receive(:executable?).with('/usr/bin/vmware-toolbox-cmd').and_return(false)
allow(File).to receive(:executable?).with('/usr/ccs/bin/vmware-toolbox-cmd').and_return(false)
allow(File).to receive(:executable?).with('/usr/sbin/vxprint').and_return(false)
@plugin.run
end
it 'Runs successfully' do
expect { @plugin }.to_not raise_error
end
it 'Returns a Mash' do
expect @plugin.to be_a_kind_of(Mash)
end
it 'should not find a vas version' do
expect(@plugin[:software][:vas][:version]).to eq nil
end
it 'should not find a vmware version' do
expect(@plugin[:software][:vmware][:version]).to eq nil
end
it 'should not find a vxfs version' do
expect(@plugin[:software][:vxfs][:version]).to eq nil
end
it 'vas should not be installed' do
expect(@plugin[:software][:vas][:installed]).to eq false
end
it 'vmware should not be installed' do
expect(@plugin[:software][:vmware][:installed]).to eq false
end
it 'vxfs should not be installed' do
expect(@plugin[:software][:vxfs][:installed]).to eq false
end
end
describe Ohai::System, 'Software plugin - linux' do
before(:each) do
@plugin = get_plugin('software.rb')
allow(@plugin).to receive(:collect_os).and_return(:linux)
std_stubs
@plugin.run
end
it 'Runs successfully' do
expect { @plugin }.to_not raise_error
end
it 'should return the vmware version' do
expect(@plugin[:software][:vmware][:version]).to eq '8.6.11.26309'
end
it 'should return the vxfs version' do
expect(@plugin[:software][:vxfs][:version]).to eq '5.0.30.00'
end
end
def std_stubs
puts 'Check the software.rb plugin for errors. Loading failed' unless @plugin
allow(@plugin).to receive(:shell_out).and_return(OpenStruct.new(stdout: 'not stubbed'))
allow(@plugin).to receive(:shell_out).with('/opt/quest/bin/vastool -v').and_return(vas_version)
allow(@plugin).to receive(:shell_out).with('/usr/bin/vmware-toolbox-cmd -v').and_return(vmware_version)
allow(@plugin).to receive(:shell_out).with('modinfo').and_return(vxfs_version_solaris)
allow(@plugin).to receive(:shell_out).with('modinfo vxfs').and_return(vxfs_version_linux)
allow(File).to receive(:executable?).and_call_original
allow(File).to receive(:executable?).with('/opt/quest/bin/vastool').and_return(true)
allow(File).to receive(:executable?).with('/usr/bin/vmware-toolbox-cmd').and_return(true)
allow(File).to receive(:executable?).with('/usr/ccs/bin/vmware-toolbox-cmd').and_return(true)
allow(File).to receive(:executable?).with('/usr/sbin/vxprint').and_return(true)
end
def vmware_version
OpenStruct.new(stdout:
'8.6.11.26309 (build-1310128)
'
)
end
def vxfs_version_none
OpenStruct.new(stdout:
'
'
)
end
def vxfs_version_solaris
OpenStruct.new(stdout:
' 41 7bef6000 51628 316 1 vxdmp (VxVM 5.1SP1RP4 DMP Driver)
42 7ba00000 221b08 317 1 vxio (VxVM 5.1SP1RP4 I/O driver)
44 7beaef40 11a8 318 1 vxspec (VxVM 5.1SP1RP4 control/status d)
229 7bf893f8 d40 319 1 vxportal (VxFS 5.1SP1RP4 portal driver)
230 7a600000 206470 21 1 vxfs (VxFS 5.1SP1RP4 SunOS 5.10)
249 7a26c000 baa8 320 1 fdd (VxQIO 5.1SP1RP4 Quick I/O drive)
'
)
end
def vxfs_version_linux
OpenStruct.new(stdout:
'filename: /lib/modules/2.6.18-194.el5/veritas/vxfs/vxfs.ko
version: 5.0.30.00
description: Veritas file system
author: Symantec Corporation
license: Proprietary. Send bug reports to support@veritas.com
srcversion: EA0089391273696173992B2
depends:
vermagic: 2.6.18-8.el5 SMP mod_unload gcc-4.1
parm: vxfs_ninode:Maximum number of vxfs inodes (int)
parm: vx_ifree_timelag:Seconds before scanning inode free list (long)
parm: vxfs_mbuf:Maximum memory used for vxfs buffer cache (charp)
parm: vxfs_maxdiospace:Maximum memory wired down for direct IO (charp)
parm: vxfs_mindiospace:Minimum memory wired down for direct IO (charp)
parm: vxfs_pmem:Physical memory to use as input for tuning curves (charp)
parm: vxfs_icachechunk:Maximum number of pages for each memory chunk used for VxFS inodes (int)
parm: vx_fiostats_tunable:Memory used for file I/O stats (int)
parm: vx_fiostats_winterval:FCL winterval for file I/O stats (int)
parm: vxfs_naio_threads_max:Maximum number of threads for native AIO (uint)
parm: vxfs_naio_threads_min:Minimum number of threads for native AIO (uint)
parm: vxfs_naio_plug_enable:Throttle native AIO on memory usage (uint)
parm: vxfs_sendfile_chunk:Number of pages to fetch for large sendfile transfers (uint)
parm: vxfs_sendfile_limit:Maximum number of processes in a sendfile main loop (uint)
parm: vxfs_sendfile_nfs:Setting to non-zero changes VxFS behaviour with sendfile from NFS (uint)
parm: vxfs_io_proxy_vxvm:Include VxVM devices in IO hand-off decisions (int)
parm: vxfs_io_proxy_level:Hand-off IO to worker threads for `raw` block devices when less than this number of bytes free on kernel stack (int)
parm: vxfs_io_proxy_pools:Number of IO pools for hand-off. (int)
parm: vxfs_io_proxy_time:If an IO has been waiting on an IO queue for this number of clock ticks, then create a new IO hand-off thread (int)
parm: vxfs_io_proxy_max:Maximum number of threads per IO handoff queue (int)
'
)
end
def vas_version
OpenStruct.new(stdout:
'vastool: QAS Version 4.1.0.21267
Copyright 2014 Quest Software, Inc. ALL RIGHTS RESERVED.
Protected by U.S. Patent Nos. 7,617,501, 7,895,332, 7,904,949, 8,086,710, 8,087,075, 8,245,242. Patents pending.
'
)
end
| 36.610837
| 156
| 0.697121
|
5eddf4004328e9f113c23aa1fe53dd9e101e72ec
| 2,093
|
php
|
PHP
|
app/Http/Controllers/NoticiasController.php
|
tiagomdrs/ProjetoLaravel
|
35139bccdd09facd0ac1036f0bd04b17ef0cd21d
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/NoticiasController.php
|
tiagomdrs/ProjetoLaravel
|
35139bccdd09facd0ac1036f0bd04b17ef0cd21d
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/NoticiasController.php
|
tiagomdrs/ProjetoLaravel
|
35139bccdd09facd0ac1036f0bd04b17ef0cd21d
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\facades\Input;
use App\Noticias;
use DB;
class NoticiasController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$noticias = DB::select('select * from noticias');
return view('Noticias.mostrar',['noticias' => $noticias]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('Noticias.criar');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$titulo = Input::get('titulo');
$auxiliar = Input::get('auxiliar');
$corpo = Input::get('corpo');
DB::insert('insert into noticias (tt_principal,tt_auxiliar,corpo,id_adm) values (?,?,?,?)',[$titulo,$auxiliar,$corpo,1]);
return redirect()->to(route('admin.home'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Noticias::find($id)->delete();
return redirect()->to(route('admin.home'));
}
}
| 21.57732
| 129
| 0.564262
|
259286746035039fdfe5fd51b85f315a44073482
| 1,536
|
js
|
JavaScript
|
devtools/commands/devRuner/MigrationRunner.js
|
rajafunctor/starter-kit-tasks
|
339123062d7b50ca40e4200823bd0a757253a416
|
[
"MIT"
] | 8
|
2021-06-16T08:00:07.000Z
|
2022-03-18T13:55:12.000Z
|
devtools/commands/devRuner/MigrationRunner.js
|
appvantageasia/starter-kit
|
910f230a0a684c29fe96dd2bfb15d9268f4701b5
|
[
"MIT"
] | 157
|
2021-06-16T06:53:07.000Z
|
2022-03-29T17:12:39.000Z
|
devtools/commands/devRuner/MigrationRunner.js
|
rajafunctor/starter-kit-tasks
|
339123062d7b50ca40e4200823bd0a757253a416
|
[
"MIT"
] | 2
|
2021-07-27T02:41:50.000Z
|
2021-09-06T08:45:08.000Z
|
const Enquirer = require('enquirer');
class MigrationRunner {
constructor() {
this.enquirer = new Enquirer();
this.migrationPromise = null;
this.latestPrompt = null;
this.enquirer.on('prompt', prompt => {
this.latestPrompt = prompt;
});
}
async start({ listPendingMigrations, executeDataMigration }, isOutdated) {
const pendingMigrations = await listPendingMigrations();
if (isOutdated() || pendingMigrations.length === 0) {
return;
}
const { doExecute } = await this.enquirer.prompt({
type: 'confirm',
name: 'doExecute',
message: `${pendingMigrations.length} migrations pending, execute now ?`,
});
this.latestPrompt = null;
if (isOutdated() || !doExecute) {
return;
}
this.migrationPromise = executeDataMigration();
try {
await this.migrationPromise;
} finally {
this.migrationPromise = null;
}
}
async stop() {
if (this.latestPrompt) {
try {
await this.latestPrompt.close();
} finally {
this.latestPrompt = null;
}
}
if (this.migrationPromise) {
try {
// wait for it to be done
await this.migrationPromise;
} catch (error) {
// ignore it
}
}
}
}
module.exports = MigrationRunner;
| 24
| 85
| 0.511068
|
d65d1897a7b2d9adc70ce57453d9c766c4d4b278
| 3,722
|
cs
|
C#
|
src/api/LMSService/Service/AuthorService.cs
|
lawrencefej/LibraryManagementAPI
|
c6e1d1919fdde8bddf5d182a004e0c2989c55ed5
|
[
"MIT"
] | null | null | null |
src/api/LMSService/Service/AuthorService.cs
|
lawrencefej/LibraryManagementAPI
|
c6e1d1919fdde8bddf5d182a004e0c2989c55ed5
|
[
"MIT"
] | 26
|
2018-09-13T02:52:17.000Z
|
2022-03-02T11:00:25.000Z
|
src/api/LMSService/Service/AuthorService.cs
|
lawrencefej/LibraryManagementSystem
|
c6e1d1919fdde8bddf5d182a004e0c2989c55ed5
|
[
"MIT"
] | 1
|
2020-03-17T23:41:33.000Z
|
2020-03-17T23:41:33.000Z
|
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using LMSContracts.Interfaces;
using LMSEntities.DataTransferObjects;
using LMSEntities.Helpers;
using LMSEntities.Models;
using LMSRepository.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace LMSService.Service
{
public class AuthorService : IAuthorService
{
// TODO fix to use base api
private readonly DataContext _context;
private readonly ILogger<AuthorService> _logger;
private readonly IMapper _mapper;
public AuthorService(DataContext context, IMapper mapper, ILogger<AuthorService> logger)
{
_context = context;
_logger = logger;
_mapper = mapper;
}
public async Task<AuthorDto> AddAuthor(AuthorDto authorDto)
{
Author author = _mapper.Map<Author>(authorDto);
_context.Add(author);
await _context.SaveChangesAsync();
_logger.LogInformation($"");
return _mapper.Map<AuthorDto>(author);
}
public async Task<LmsResponseHandler<AuthorDto>> DeleteAuthor(int authorId)
{
Author author = await GetAuthor(authorId);
if (author != null)
{
_context.Remove(author);
await _context.SaveChangesAsync();
return LmsResponseHandler<AuthorDto>.Successful();
}
return LmsResponseHandler<AuthorDto>.Failed("");
}
public async Task<LmsResponseHandler<AuthorDto>> EditAuthor(AuthorDto authorDto)
{
Author author = await GetAuthor(authorDto.Id);
if (author != null)
{
_mapper.Map(authorDto, author);
_context.Update(author);
await _context.SaveChangesAsync();
return LmsResponseHandler<AuthorDto>.Successful(_mapper.Map<AuthorDto>(author));
}
return LmsResponseHandler<AuthorDto>.Failed("");
}
public async Task<LmsResponseHandler<AuthorDto>> GetAuthorForController(int authorId)
{
Author author = await GetAuthor(authorId);
if (author != null)
{
AuthorDto authorForReturn = _mapper.Map<AuthorDto>(author);
return LmsResponseHandler<AuthorDto>.Successful(authorForReturn);
}
return LmsResponseHandler<AuthorDto>.Failed("");
}
public async Task<PagedList<AuthorDto>> GetPaginatedAuthors(PaginationParams paginationParams)
{
IQueryable<Author> authors = _context.Authors.AsNoTracking().AsQueryable();
authors = FilterAuthors(paginationParams, authors);
PagedList<Author> authorsToReturn = await PagedList<Author>.CreateAsync(authors, paginationParams.PageNumber, paginationParams.PageSize);
return _mapper.Map<PagedList<AuthorDto>>(authorsToReturn);
}
private async Task<Author> GetAuthor(int authorId)
{
return await _context.Authors.FirstOrDefaultAsync(a => a.Id == authorId);
}
private static IQueryable<Author> FilterAuthors(PaginationParams paginationParams, IQueryable<Author> authors)
{
if (!string.IsNullOrEmpty(paginationParams.SearchString))
{
authors = authors
.Where(x => x.FullName.Contains(paginationParams.SearchString));
}
authors = paginationParams.SortDirection == "desc" ? authors.OrderByDescending(x => x.FullName) : authors.OrderBy(x => x.FullName);
return authors;
}
}
}
| 32.649123
| 149
| 0.624395
|
90a779e07dde1468fb701a88613b466aab4f2b81
| 3,014
|
h
|
C
|
org.yafra.clibs/include/Xbae/Methods.h
|
yafraorg/yafra-tdb-c
|
c81c965a4a8947e7d6bad497ca09768243fcc26b
|
[
"Apache-2.0"
] | 1
|
2019-01-10T16:44:23.000Z
|
2019-01-10T16:44:23.000Z
|
org.yafra.clibs/include/Xbae/Methods.h
|
yafraorg/yafra-tdb-c
|
c81c965a4a8947e7d6bad497ca09768243fcc26b
|
[
"Apache-2.0"
] | 1
|
2015-03-23T10:30:35.000Z
|
2015-03-23T10:30:35.000Z
|
org.yafra.clibs/include/Xbae/Methods.h
|
yafraorg/yafra-tdb-c
|
c81c965a4a8947e7d6bad497ca09768243fcc26b
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright(c) 1992 Bell Communications Research, Inc. (Bellcore)
* All rights reserved
* Permission to use, copy, modify and distribute this material for
* any purpose and without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies, and that the name of Bellcore not be used in advertising
* or publicity pertaining to this material without the specific,
* prior written permission of an authorized representative of
* Bellcore.
*
* BELLCORE MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES, EX-
* PRESS OR IMPLIED, WITH RESPECT TO THE SOFTWARE, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR ANY PARTICULAR PURPOSE, AND THE WARRANTY AGAINST IN-
* FRINGEMENT OF PATENTS OR OTHER INTELLECTUAL PROPERTY RIGHTS. THE
* SOFTWARE IS PROVIDED "AS IS", AND IN NO EVENT SHALL BELLCORE OR
* ANY OF ITS AFFILIATES BE LIABLE FOR ANY DAMAGES, INCLUDING ANY
* LOST PROFITS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES RELAT-
* ING TO THE SOFTWARE.
*/
#ifndef _Xbae_Methods_h
#define _Xbae_Methods_h
#include <Xbae/Macros.h>
/*
* Methods.h created by Andrew Lister (7 August, 1995)
*/
void xbaeResize P(( XbaeMatrixWidget mw ));
/*
* New Matrix methods
*/
void xbaeSetCell P(( XbaeMatrixWidget mw, int row, int column,
const String value, Boolean update_text ));
void xbaeEditCell P(( XbaeMatrixWidget mw, int row, int column ));
void xbaeSelectCell P(( XbaeMatrixWidget mw, int row, int column ));
void xbaeSelectRow P(( XbaeMatrixWidget mw, int row ));
void xbaeSelectColumn P(( XbaeMatrixWidget mw, int column ));
void xbaeDeselectAll P(( XbaeMatrixWidget mw ));
void xbaeDeselectCell P(( XbaeMatrixWidget, int row, int column ));
void xbaeDeselectRow P(( XbaeMatrixWidget mw, int row ));
void xbaeDeselectColumn P(( XbaeMatrixWidget mw, int column ));
String xbaeGetCell P(( XbaeMatrixWidget, int row, int column ));
Boolean xbaeCommitEdit P(( XbaeMatrixWidget mw, Boolean unmap ));
void xbaeCancelEdit P(( XbaeMatrixWidget mw, Boolean unmap ));
void xbaeAddRows P((XbaeMatrixWidget mw, int position, String *rows,
String *labels, Pixel *colors, Pixel *backgrounds,
int num_rows ));
void xbaeDeleteRows P(( XbaeMatrixWidget mw, int position, int num_rows ));
void xbaeAddColumns P(( XbaeMatrixWidget mw, int position, String *columns,
String *labels, short *widths, int *max_lengths,
unsigned char *alignments,
unsigned char *label_alignments, Pixel *colors,
Pixel *backgrounds, int num_columns ));
void xbaeDeleteColumns P(( XbaeMatrixWidget mw, int position,
int num_columns ));
void xbaeSetRowColors P(( XbaeMatrixWidget mw, int position, Pixel *colors,
int num_colors, Boolean bg ));
void xbaeSetColumnColors P(( XbaeMatrixWidget mw, int position,
Pixel *colors, int num_colors, Boolean bg ));
void xbaeSetCellColor P(( XbaeMatrixWidget mw, int row, int column,
Pixel color, Boolean bg ));
#endif
| 44.323529
| 75
| 0.746848
|
d663b37d2e68ee5972bddbc275d0c8a516a88f39
| 306
|
cs
|
C#
|
src/Tools.Net.Cli.Driver/Options/DotNetCliOptions.cs
|
Exizent/dotnet-mongo
|
ac2bd4cb801d8f2407413f7e5dd2a2fb9a78ced3
|
[
"MIT"
] | 1
|
2022-01-14T17:06:27.000Z
|
2022-01-14T17:06:27.000Z
|
src/Tools.Net.Cli.Driver/Options/DotNetCliOptions.cs
|
Exizent/dotnet-mongo
|
ac2bd4cb801d8f2407413f7e5dd2a2fb9a78ced3
|
[
"MIT"
] | 4
|
2022-01-14T16:33:27.000Z
|
2022-02-18T14:53:12.000Z
|
src/Tools.Net.Cli.Driver/Options/DotNetCliOptions.cs
|
Exizent/dotnet-mongo
|
ac2bd4cb801d8f2407413f7e5dd2a2fb9a78ced3
|
[
"MIT"
] | 1
|
2022-01-14T16:34:08.000Z
|
2022-01-14T16:34:08.000Z
|
namespace Tools.Net.Cli.Driver.Options
{
/// <summary>
/// Options for the dotnet cli
/// </summary>
public class DotNetCliOptions
{
/// <summary>
/// The working directory for the cli
/// </summary>
public string WorkingDirectory { get; set; }
}
}
| 21.857143
| 52
| 0.562092
|
db70be86b3609e68e51aeb9c325065b959d7acba
| 1,043
|
php
|
PHP
|
src/Sylius/Bundle/ApiBundle/Context/TokenBasedUserContext.php
|
titomtd/Sylius
|
92e5e60e4355672361c904397f0ebaa7ee3c2938
|
[
"MIT"
] | null | null | null |
src/Sylius/Bundle/ApiBundle/Context/TokenBasedUserContext.php
|
titomtd/Sylius
|
92e5e60e4355672361c904397f0ebaa7ee3c2938
|
[
"MIT"
] | 4
|
2021-03-10T16:33:26.000Z
|
2022-02-27T03:55:37.000Z
|
src/Sylius/Bundle/ApiBundle/Context/TokenBasedUserContext.php
|
titomtd/Sylius
|
92e5e60e4355672361c904397f0ebaa7ee3c2938
|
[
"MIT"
] | 1
|
2020-12-29T08:55:24.000Z
|
2020-12-29T08:55:24.000Z
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ApiBundle\Context;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
final class TokenBasedUserContext implements UserContextInterface
{
/** @var TokenStorageInterface */
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function getUser(): ?UserInterface
{
$token = $this->tokenStorage->getToken();
if ($token === null) {
return null;
}
/** @var UserInterface|string $user */
$user = $token->getUser();
if (is_string($user)) {
return null;
}
return $user;
}
}
| 23.177778
| 87
| 0.658677
|
ed0a208a3357956897f8da25f5ff6917921c868e
| 403
|
h
|
C
|
fcgo_order/Fcgo/Work/Sort/V/Fcgo_SortRightBrandCollectionViewCell.h
|
yanalucky/MBB
|
90d300d57a2716e0444905395c11c686ebb29079
|
[
"Apache-2.0"
] | null | null | null |
fcgo_order/Fcgo/Work/Sort/V/Fcgo_SortRightBrandCollectionViewCell.h
|
yanalucky/MBB
|
90d300d57a2716e0444905395c11c686ebb29079
|
[
"Apache-2.0"
] | null | null | null |
fcgo_order/Fcgo/Work/Sort/V/Fcgo_SortRightBrandCollectionViewCell.h
|
yanalucky/MBB
|
90d300d57a2716e0444905395c11c686ebb29079
|
[
"Apache-2.0"
] | null | null | null |
//
// Fcgo_SortRightBrandCollectionViewCell.h
// Fcgo
//
// Created by huafanxiao on 2017/5/23.
// Copyright © 2017年 huafanxiao. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Fcgo_BrandModel.h"
@interface Fcgo_SortRightBrandCollectionViewCell :UICollectionViewCell
@property (nonatomic,strong) Fcgo_BrandModel *model;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
| 22.388889
| 70
| 0.771712
|
44547b2aba9054d13531c96df6084aae47fe2f62
| 176
|
py
|
Python
|
Source Code/03_play_youtube_video.py
|
insanecodes/Python
|
e3e022fa5ff83e418dae32c661296224fc8ded36
|
[
"MIT"
] | 22
|
2020-10-11T13:56:25.000Z
|
2021-11-10T12:53:10.000Z
|
Source Code/03_play_youtube_video.py
|
insanecodes/Python
|
e3e022fa5ff83e418dae32c661296224fc8ded36
|
[
"MIT"
] | null | null | null |
Source Code/03_play_youtube_video.py
|
insanecodes/Python
|
e3e022fa5ff83e418dae32c661296224fc8ded36
|
[
"MIT"
] | 8
|
2020-10-16T12:58:29.000Z
|
2021-12-30T01:28:16.000Z
|
import vlc
import pafy
url = input("Paste your YouTube URL here:>> ")
video = pafy.new(url)
best = video.getbest()
media = vlc.MediaPlayer(best.url)
media.play()
| 16
| 47
| 0.659091
|
12f9489219607db534653ba979a545e3a9de354d
| 1,100
|
cs
|
C#
|
src/DotNetty.NetUV/Channels/ReadStreamConsumer.cs
|
yyjdelete/SpanNetty
|
6d6f394431d5891cd871977075d0fc52d9759920
|
[
"MIT"
] | 4
|
2021-12-06T23:03:21.000Z
|
2022-01-31T21:30:19.000Z
|
src/DotNetty.NetUV/Channels/ReadStreamConsumer.cs
|
yyjdelete/SpanNetty
|
6d6f394431d5891cd871977075d0fc52d9759920
|
[
"MIT"
] | null | null | null |
src/DotNetty.NetUV/Channels/ReadStreamConsumer.cs
|
yyjdelete/SpanNetty
|
6d6f394431d5891cd871977075d0fc52d9759920
|
[
"MIT"
] | 1
|
2021-12-06T13:59:54.000Z
|
2021-12-06T13:59:54.000Z
|
/*
* Copyright (c) Johnny Z. All rights reserved.
*
* https://github.com/StormHub/NetUV
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.NetUV.Channels
{
using System;
using DotNetty.NetUV.Handles;
internal sealed class ReadStreamConsumer<T> : IStreamConsumer<T>
where T : StreamHandle
{
private readonly Action<T, IStreamReadCompletion> readAction;
public ReadStreamConsumer(Action<T, IStreamReadCompletion> readAction)
{
if (readAction is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readAction); }
this.readAction = readAction;
}
public void Consume(T stream, IStreamReadCompletion readCompletion) =>
this.readAction(stream, readCompletion);
}
}
| 30.555556
| 109
| 0.699091
|
6b14d84b53310e8630eb881e24e8b30423e8fe12
| 109
|
js
|
JavaScript
|
shared/ecc/ecc_config/index.js
|
kuissoftech/mogulsocial_react_redux
|
bd528c9a80b3da7a2edf981a6652b35d91078b6b
|
[
"MIT"
] | 1
|
2017-12-16T15:07:54.000Z
|
2017-12-16T15:07:54.000Z
|
shared/ecc/ecc_config/index.js
|
kuissoftech/mogulsocial_react_redux
|
bd528c9a80b3da7a2edf981a6652b35d91078b6b
|
[
"MIT"
] | null | null | null |
shared/ecc/ecc_config/index.js
|
kuissoftech/mogulsocial_react_redux
|
bd528c9a80b3da7a2edf981a6652b35d91078b6b
|
[
"MIT"
] | null | null | null |
module.exports = {
address_prefix: process.env.npm_config__graphene_ecc_default_address_prefix || 'STM'
}
| 36.333333
| 88
| 0.798165
|
29a1373d98bf48cc3946b4f8612d55192f6b5b44
| 7,908
|
rs
|
Rust
|
pac/atsam4ls8c/src/scif/oscctrl0.rs
|
Dridus/atsam-pac
|
ded876950da787b4f91ce345be84f9222c47c56f
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
pac/atsam4ls8c/src/scif/oscctrl0.rs
|
Dridus/atsam-pac
|
ded876950da787b4f91ce345be84f9222c47c56f
|
[
"Apache-2.0",
"MIT"
] | 8
|
2021-04-11T08:21:36.000Z
|
2021-10-12T07:59:54.000Z
|
pac/atsam4ls8c/src/scif/oscctrl0.rs
|
Dridus/atsam-pac
|
ded876950da787b4f91ce345be84f9222c47c56f
|
[
"Apache-2.0",
"MIT"
] | 2
|
2021-04-11T17:36:07.000Z
|
2021-05-29T05:32:08.000Z
|
#[doc = "Register `OSCCTRL0` reader"]
pub struct R(crate::R<OSCCTRL0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<OSCCTRL0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<OSCCTRL0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<OSCCTRL0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `OSCCTRL0` writer"]
pub struct W(crate::W<OSCCTRL0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<OSCCTRL0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<OSCCTRL0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<OSCCTRL0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `MODE` reader - Oscillator Mode"]
pub struct MODE_R(crate::FieldReader<bool, bool>);
impl MODE_R {
pub(crate) fn new(bits: bool) -> Self {
MODE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MODE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MODE` writer - Oscillator Mode"]
pub struct MODE_W<'a> {
w: &'a mut W,
}
impl<'a> MODE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "Field `GAIN` reader - Gain"]
pub struct GAIN_R(crate::FieldReader<u8, u8>);
impl GAIN_R {
pub(crate) fn new(bits: u8) -> Self {
GAIN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for GAIN_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `GAIN` writer - Gain"]
pub struct GAIN_W<'a> {
w: &'a mut W,
}
impl<'a> GAIN_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 1)) | ((value as u32 & 0x03) << 1);
self.w
}
}
#[doc = "Field `AGC` reader - Automatic Gain Control"]
pub struct AGC_R(crate::FieldReader<bool, bool>);
impl AGC_R {
pub(crate) fn new(bits: bool) -> Self {
AGC_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for AGC_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `AGC` writer - Automatic Gain Control"]
pub struct AGC_W<'a> {
w: &'a mut W,
}
impl<'a> AGC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `STARTUP` reader - Oscillator Start-up Time"]
pub struct STARTUP_R(crate::FieldReader<u8, u8>);
impl STARTUP_R {
pub(crate) fn new(bits: u8) -> Self {
STARTUP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for STARTUP_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `STARTUP` writer - Oscillator Start-up Time"]
pub struct STARTUP_W<'a> {
w: &'a mut W,
}
impl<'a> STARTUP_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | ((value as u32 & 0x0f) << 8);
self.w
}
}
#[doc = "Field `OSCEN` reader - Oscillator Enable"]
pub struct OSCEN_R(crate::FieldReader<bool, bool>);
impl OSCEN_R {
pub(crate) fn new(bits: bool) -> Self {
OSCEN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for OSCEN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OSCEN` writer - Oscillator Enable"]
pub struct OSCEN_W<'a> {
w: &'a mut W,
}
impl<'a> OSCEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
impl R {
#[doc = "Bit 0 - Oscillator Mode"]
#[inline(always)]
pub fn mode(&self) -> MODE_R {
MODE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 1:2 - Gain"]
#[inline(always)]
pub fn gain(&self) -> GAIN_R {
GAIN_R::new(((self.bits >> 1) & 0x03) as u8)
}
#[doc = "Bit 3 - Automatic Gain Control"]
#[inline(always)]
pub fn agc(&self) -> AGC_R {
AGC_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 8:11 - Oscillator Start-up Time"]
#[inline(always)]
pub fn startup(&self) -> STARTUP_R {
STARTUP_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bit 16 - Oscillator Enable"]
#[inline(always)]
pub fn oscen(&self) -> OSCEN_R {
OSCEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Oscillator Mode"]
#[inline(always)]
pub fn mode(&mut self) -> MODE_W {
MODE_W { w: self }
}
#[doc = "Bits 1:2 - Gain"]
#[inline(always)]
pub fn gain(&mut self) -> GAIN_W {
GAIN_W { w: self }
}
#[doc = "Bit 3 - Automatic Gain Control"]
#[inline(always)]
pub fn agc(&mut self) -> AGC_W {
AGC_W { w: self }
}
#[doc = "Bits 8:11 - Oscillator Start-up Time"]
#[inline(always)]
pub fn startup(&mut self) -> STARTUP_W {
STARTUP_W { w: self }
}
#[doc = "Bit 16 - Oscillator Enable"]
#[inline(always)]
pub fn oscen(&mut self) -> OSCEN_W {
OSCEN_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Oscillator Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [oscctrl0](index.html) module"]
pub struct OSCCTRL0_SPEC;
impl crate::RegisterSpec for OSCCTRL0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [oscctrl0::R](R) reader structure"]
impl crate::Readable for OSCCTRL0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [oscctrl0::W](W) writer structure"]
impl crate::Writable for OSCCTRL0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets OSCCTRL0 to value 0"]
impl crate::Resettable for OSCCTRL0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 28.548736
| 416
| 0.56563
|
b62f45ccac8119efe0674f0012423db9199423b1
| 1,057
|
html
|
HTML
|
Generated/index/System.Management.Automation/R/6b551d638ac1965a.html
|
Alex-ABPerson/PSSourceBrowser
|
dc7389c4cb47f00dbfffb04fc1905e2fc935110f
|
[
"Apache-2.0"
] | null | null | null |
Generated/index/System.Management.Automation/R/6b551d638ac1965a.html
|
Alex-ABPerson/PSSourceBrowser
|
dc7389c4cb47f00dbfffb04fc1905e2fc935110f
|
[
"Apache-2.0"
] | null | null | null |
Generated/index/System.Management.Automation/R/6b551d638ac1965a.html
|
Alex-ABPerson/PSSourceBrowser
|
dc7389c4cb47f00dbfffb04fc1905e2fc935110f
|
[
"Apache-2.0"
] | null | null | null |
<!DOCTYPE html>
<html><head><title>ResolveITypeName</title><link rel="stylesheet" href="../../styles.css"/><script src="../../scripts.js"></script></head><body onload="ro();">
<div class="rH">3 references to ResolveITypeName</div><div class="rA">System.Management.Automation (3)</div><div class="rG" id="System.Management.Automation"><div class="rF"><div class="rN">engine\parser\Compiler.cs (1)</div>
<a href="../engine/parser/Compiler.cs.html#1620"><b>1620</b>var generatorType = TypeResolver.<i>ResolveITypeName</i>(generatorTypeAst.TypeName, out Exception exception);</a>
</div>
<div class="rF"><div class="rN">engine\parser\TypeResolver.cs (1)</div>
<a href="../engine/parser/TypeResolver.cs.html#503"><b>503</b>return <i>ResolveITypeName</i>(iTypeName, out exception);</a>
</div>
<div class="rF"><div class="rN">engine\runtime\Operations\MiscOps.cs (1)</div>
<a href="../engine/runtime/Operations/MiscOps.cs.html#2109"><b>2109</b>var result = TypeResolver.<i>ResolveITypeName</i>(typeName, out exception);</a>
</div>
</div>
</body></html>
| 81.307692
| 226
| 0.700095
|
c5c287a4327c9a93c7bcb25b5c02d76e93215b03
| 251
|
swift
|
Swift
|
Sources/YotiButtonSDK/Extensions/String+Localization.swift
|
getyoti/ios-sdk-button
|
c6213ea526a63607db9f7f4f1292a9c2cda6aadb
|
[
"MIT"
] | 5
|
2018-05-21T16:48:06.000Z
|
2021-09-29T09:41:10.000Z
|
Sources/YotiButtonSDK/Extensions/String+Localization.swift
|
getyoti/ios-sdk-button
|
c6213ea526a63607db9f7f4f1292a9c2cda6aadb
|
[
"MIT"
] | 7
|
2018-05-03T14:30:35.000Z
|
2020-02-27T17:53:32.000Z
|
Sources/YotiButtonSDK/Extensions/String+Localization.swift
|
getyoti/ios-sdk-button
|
c6213ea526a63607db9f7f4f1292a9c2cda6aadb
|
[
"MIT"
] | 5
|
2018-07-02T09:20:47.000Z
|
2021-08-12T08:10:40.000Z
|
//
// Copyright © 2021 Yoti Ltd. All rights reserved.
//
import Foundation
extension String {
func localization(stockValue: String) -> String {
Bundle.main.localizedString(forKey: self, value: stockValue, table: "YotiButtonSDK")
}
}
| 20.916667
| 92
| 0.693227
|
8dbb7c9f780eab8525031177395bc61f4c0d72dd
| 1,141
|
js
|
JavaScript
|
dist/tml.js
|
yanishoss/tml-js
|
955c6b015d7a0e448e7e3d0f33013060fc650be7
|
[
"MIT"
] | null | null | null |
dist/tml.js
|
yanishoss/tml-js
|
955c6b015d7a0e448e7e3d0f33013060fc650be7
|
[
"MIT"
] | 1
|
2021-05-11T17:10:41.000Z
|
2021-05-11T17:10:41.000Z
|
dist/tml.js
|
yanishoss/tml-js
|
955c6b015d7a0e448e7e3d0f33013060fc650be7
|
[
"MIT"
] | null | null | null |
var e=new global.Go;WebAssembly.instantiateStreaming||(WebAssembly.instantiateStreaming=function(e,t){try{return Promise.resolve(e).then(function(e){return Promise.resolve(e.arrayBuffer()).then(function(e){return Promise.resolve(WebAssembly.instantiate(e,t))})})}catch(e){return Promise.reject(e)}});var t=new Error("WASM module is not ready yet");"TML_parse"in global||function(t){try{return Promise.resolve(function(t,r){try{var n=Promise.resolve(WebAssembly.instantiateStreaming(fetch("https://cdn.jsdelivr.net/gh/yanishoss/tml/bin/main.wasm"),e.importObject)).then(function(t){return Promise.resolve(e.run(t.instance)).then(function(){})})}catch(e){return r(e)}return n&&n.then?n.then(void 0,r):n}(0,function(e){throw e}))}catch(e){return Promise.reject(e)}}().then(function(){}).catch(function(e){throw e}),exports.onReady=function(){},exports.parse=function(e,r){if(!("TML_parse"in global))throw t;var n=TML_parse(e,r);if(void 0!==n.Error)throw new Error(n.Error());return n},exports.withDefaultConfig=function(){if(!("TML_withDefaultConfig"in global))throw t;return TML_withDefaultConfig(input,conf)};
//# sourceMappingURL=tml.js.map
| 380.333333
| 1,108
| 0.761613
|
33b9c6263a36255ff02a643f5e65b3a75a8e9119
| 303
|
h
|
C
|
MLCalendarSample/MLCalendarBackground.h
|
sjndhkl/Calendar-OSX
|
82d5f55972e5a0a2ce446a7e71e4e03b36693e86
|
[
"MIT"
] | 595
|
2015-02-25T23:39:04.000Z
|
2021-06-03T18:56:28.000Z
|
MLCalendarSample/MLCalendarBackground.h
|
sjndhkl/Calendar-OSX
|
82d5f55972e5a0a2ce446a7e71e4e03b36693e86
|
[
"MIT"
] | 16
|
2019-04-24T17:32:58.000Z
|
2021-02-22T22:20:43.000Z
|
MLCalendarSample/MLCalendarBackground.h
|
sjndhkl/Calendar-OSX
|
82d5f55972e5a0a2ce446a7e71e4e03b36693e86
|
[
"MIT"
] | 38
|
2015-02-26T03:04:25.000Z
|
2022-02-08T03:35:23.000Z
|
//
// MLCalendarView.h
// ModernLookOSX
//
// Created by András Gyetván on 2015. 03. 08..
// Copyright (c) 2015. DroidZONE. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface MLCalendarBackground : NSView
@property (nonatomic, strong) NSColor* backgroundColor;
- (void) commonInit;
@end
| 17.823529
| 55
| 0.706271
|
58c3957f77a31bc9893e50cbe849a9e50f002055
| 1,361
|
php
|
PHP
|
resources/views/components/tab/tabs.blade.php
|
BCleverly/backend
|
a4d73009fd8f1c7b918d7380b5dc361542e62f38
|
[
"MIT"
] | null | null | null |
resources/views/components/tab/tabs.blade.php
|
BCleverly/backend
|
a4d73009fd8f1c7b918d7380b5dc361542e62f38
|
[
"MIT"
] | null | null | null |
resources/views/components/tab/tabs.blade.php
|
BCleverly/backend
|
a4d73009fd8f1c7b918d7380b5dc361542e62f38
|
[
"MIT"
] | null | null | null |
@props([
'active',
'containerClasses' => '',
'tabsContainerClasses' => ''
])
<div
{{ $attributes->merge(['class' => ' ' . $containerClasses]) }}
x-data="{
'activeTab': '{{ $active }}',
tabs: [],
tabHeadings: [],
toggleTabs() {
this.tabs.forEach(
tab => tab.__x.$data.showIfActive(this.activeTab)
);
}
}"
x-init="() => {
tabs = [...$refs.tabs.children];
tabHeadings = tabs.map(tab => tab.__x.$data.name);
toggleTabs();
}">
<div class="border-b flex">
<div class="flex-1">
<template x-for="(tab, index) in tabHeadings" x-key="index" class="">
<a href="#"
:class="tab === activeTab ? 'text-blue-500 border-blue-500' : ''"
class="inline-block p-4 mr-2 border-b-2 border-gray-100 hover:text-blue-500 hover:border-blue-500"
x-text="tab"
x-on:click.prevent="activeTab = tab; toggleTabs();"
></a>
</template>
</div>
@isset($tabButtons)
<div class="p-2 flex justify-center">
{{ $tabButtons }}
</div>
@endisset
</div>
<div x-cloak x-ref="tabs" class="{{ $tabsContainerClasses }}">
{{ $slot }}
</div>
</div>
| 31.651163
| 118
| 0.462895
|
a40e585c06e2afee6eb0a11492c521b511efed13
| 1,912
|
php
|
PHP
|
resources/views/Search/distributions.blade.php
|
b0janix/Coupons
|
a34e051d7de3183b2b79ed27751b4a85cd7fe937
|
[
"MIT"
] | null | null | null |
resources/views/Search/distributions.blade.php
|
b0janix/Coupons
|
a34e051d7de3183b2b79ed27751b4a85cd7fe937
|
[
"MIT"
] | null | null | null |
resources/views/Search/distributions.blade.php
|
b0janix/Coupons
|
a34e051d7de3183b2b79ed27751b4a85cd7fe937
|
[
"MIT"
] | null | null | null |
@extends('Layouts.master')
@section('content')
{!!Form::open(['route' => 'present.distribution'])!!}
<br>
{!!Form::text('year',date('Y'),['id'=>'year'])!!}
<br><br>
{!!Form::select('month',['January'=>'January','February'=>'February','March'=>'March',
'April'=>'April','May'=>'May','June'=>'June','July'=>'July','August'=>'August',
'September'=>'September','October'=>'October','November'=>'November','December'=>'December'], null,
['placeholder' => 'Pick a month...'])
!!}
<br><br>
{!! Form::select('meal', ['breakfast'=>'breakfast','lunch'=>'lunch','supper'=>'supper'],null,['placeholder' => 'Pick a meal...']) !!}
<br><br>
<h4>Coupon Number                
Account Number              
Worker Name                   
Department</h4>
{!! Form::input('number', 'couponNumber') !!}
{!! Form::input('number', 'accountNumber') !!}
{!! Form::text('workerName',null,['id'=>'wname']) !!}
{!!Form::select('department',['Visokogradba'=>'Visokogradba','Niskogradba'=>'Niskogradba','Mehanizacija'=>'Mehanizacija',
'Laboratorija'=>'Laboratorija','Gamatroniks'=>'Gamatroniks','Direkcija'=>'Direkcija','Komercija'=>'Komercija','Ugostitelska Dejnost'=>'Ugostitelska Dejnost'], null,['placeholder' => 'Pick a department...'])!!}
{!!Form::submit('Search')!!}
{!!Form::close()!!}
<br>
@if(count($result[0])>0)
@for($i=0;$i < count($result[0]);$i++)
<div class="present-results">
{{$result[0][$i]->year}} {{$result[0][$i]->month}} {{$result[0][$i]->meal}} {{$result[1][$i]}} {{$result[0][$i]->accountNumber}}
{{$result[0][$i]->workerName}} {{$result[2][$i]}}
</div>
@endfor
@endif
@if(count($result[0])==0)
<p>There are no results for the provided parameters.</p>
@endif
<br>
<a href="{{ URL::previous() }}">Back</a>
@endsection
| 45.52381
| 209
| 0.639644
|
d3931643f19b71597d97e0765c44d6e411fa2661
| 1,180
|
rb
|
Ruby
|
acceptance/tests/resource/package/does_not_exist.rb
|
trlinkin/puppet
|
2d376842e84a155544d7ab6a4ebb10887e0e5ae0
|
[
"Apache-2.0"
] | 1
|
2015-11-06T00:31:26.000Z
|
2015-11-06T00:31:26.000Z
|
acceptance/tests/resource/package/does_not_exist.rb
|
rajcybage/puppet
|
2df32374cbcb3725e8244c32fe32efcda64bb2c6
|
[
"Apache-2.0"
] | null | null | null |
acceptance/tests/resource/package/does_not_exist.rb
|
rajcybage/puppet
|
2df32374cbcb3725e8244c32fe32efcda64bb2c6
|
[
"Apache-2.0"
] | null | null | null |
# Redmine (#22529)
test_name "Puppet returns only resource package declaration when querying an uninstalled package" do
resource_declaration_regex = %r@package \{ 'not-installed-on-this-host':
ensure => '(?:purged|absent)',
\}@m
package_apply_regex = %r@Notice: Compiled catalog for .* in environment production in \d+\.\d{2} seconds(?:\e\[0m)?
(?:\e\[m)?Notice: Finished catalog run in \d+\.\d{2} seconds@m
agents.each do |agent|
step "test puppet resource package" do
on(agent, puppet('resource', 'package', 'not-installed-on-this-host')) do
assert_match(resource_declaration_regex, stdout)
end
end
end
# Until #3707 is fixed and purged rpm/yum packages no longer give spurious creation notices
# Also skipping solaris, windows whose providers do not have purgeable implemented.
confine_block(:to, :platform => /debian|ubuntu/) do
agents.each do |agent|
step "test puppet apply" do
on(agent, puppet('apply', '-e', %Q|"package {'not-installed-on-this-host': ensure => purged }"|)) do
assert_match(package_apply_regex, stdout)
assert_equal('', stderr)
end
end
end
end
end
| 34.705882
| 117
| 0.676271
|
5c88b8e2b3630b6524200eb61a6fda6c3385fd3f
| 3,276
|
rs
|
Rust
|
sway-core/src/parse_tree/use_statement.rs
|
a5f9t4/sway
|
db55dacc3f39414a56fac94436358b29323b5895
|
[
"Apache-2.0"
] | null | null | null |
sway-core/src/parse_tree/use_statement.rs
|
a5f9t4/sway
|
db55dacc3f39414a56fac94436358b29323b5895
|
[
"Apache-2.0"
] | null | null | null |
sway-core/src/parse_tree/use_statement.rs
|
a5f9t4/sway
|
db55dacc3f39414a56fac94436358b29323b5895
|
[
"Apache-2.0"
] | null | null | null |
use crate::build_config::BuildConfig;
use crate::error::*;
use crate::span;
use crate::Ident;
use crate::Rule;
use pest::iterators::Pair;
#[derive(Debug, Clone)]
pub enum ImportType<'sc> {
Star,
Item(Ident<'sc>),
}
/// A [UseStatement] is a statement that imports something from a module into the local namespace.
#[derive(Debug, Clone)]
pub struct UseStatement<'sc> {
pub(crate) call_path: Vec<Ident<'sc>>,
pub(crate) import_type: ImportType<'sc>,
// If `is_absolute` is true, then this use statement is an absolute path from
// the project root namespace. If not, then it is relative to the current namespace.
pub(crate) is_absolute: bool,
pub(crate) alias: Option<Ident<'sc>>,
}
impl<'sc> UseStatement<'sc> {
pub(crate) fn parse_from_pair(
pair: Pair<'sc, Rule>,
config: Option<&BuildConfig>,
) -> CompileResult<'sc, Self> {
let mut errors = vec![];
let mut warnings = vec![];
let stmt = pair.into_inner().next().unwrap();
let is_absolute = stmt.as_rule() == Rule::absolute_use_statement;
let mut stmt = stmt.into_inner();
let _use_keyword = stmt.next();
let import_path = if is_absolute {
stmt.clone().nth(1).expect("Guaranteed by grammar")
} else {
stmt.clone().next().expect("Guaranteed by grammar")
};
let mut import_path_buf = vec![];
let mut import_path_vec = import_path.into_inner().collect::<Vec<_>>();
let last_item = import_path_vec.pop().unwrap();
let import_type = match last_item.as_rule() {
Rule::star => ImportType::Star,
Rule::ident => ImportType::Item(check!(
Ident::parse_from_pair(last_item, config),
return err(warnings, errors),
warnings,
errors
)),
_ => unreachable!(),
};
for item in import_path_vec.into_iter() {
if item.as_rule() == Rule::star {
errors.push(CompileError::NonFinalAsteriskInPath {
span: span::Span {
span: item.as_span(),
path: config.map(|c| c.path()),
},
});
continue;
} else if item.as_rule() == Rule::ident {
import_path_buf.push(check!(
Ident::parse_from_pair(item, config),
return err(warnings, errors),
warnings,
errors
));
}
}
let mut alias = None;
for item in stmt {
if item.as_rule() == Rule::alias {
let item = item.into_inner().nth(1).unwrap();
let alias_parsed = check!(
Ident::parse_from_pair(item, config),
continue,
warnings,
errors
);
alias = Some(alias_parsed);
}
}
ok(
UseStatement {
call_path: import_path_buf,
import_type,
is_absolute,
alias,
},
Vec::new(),
Vec::new(),
)
}
}
| 32.76
| 98
| 0.509463
|
e403e730ea1c329938202a19f31ac83abf3cd415
| 1,873
|
cs
|
C#
|
Example/Framework/Network/PlayerConnectionState.cs
|
sboron/godot4-fast-paced-network-fps-tps
|
f8f5bdfa3f9d0b7a4f19cabb542db59bf91ca23f
|
[
"MIT"
] | 11
|
2022-03-26T00:21:47.000Z
|
2022-03-29T15:30:24.000Z
|
Example/Framework/Network/PlayerConnectionState.cs
|
sboron/godot4-fast-paced-network-fps-tps
|
f8f5bdfa3f9d0b7a4f19cabb542db59bf91ca23f
|
[
"MIT"
] | 1
|
2022-03-30T23:31:49.000Z
|
2022-03-30T23:31:49.000Z
|
Example/Framework/Network/PlayerConnectionState.cs
|
sboron/godot4-fast-paced-network-fps-tps
|
f8f5bdfa3f9d0b7a4f19cabb542db59bf91ca23f
|
[
"MIT"
] | null | null | null |
/*
* Created on Mon Mar 28 2022
*
* The MIT License (MIT)
* Copyright (c) 2022 Stefan Boronczyk, Striked GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Godot;
using LiteNetLib.Utils;
using System.Runtime.Serialization;
namespace Framework.Network
{
/// <summary>
/// Connection states of the player
/// </summary>
public enum PlayerConnectionState
{
/// <summary>
/// Only for pre-connection
/// </summary>
Unknown = 0,
/// <summary>
/// When player is connected
/// </summary>
Connected = 1,
/// <summary>
/// When player have completly loading the server world
/// </summary>
Initialized = 2,
/// <summary>
/// When the player is disconnected
/// </summary>
Disconnected = 3
}
}
| 34.685185
| 123
| 0.679124
|
025d5becc1800753c745a2f50bd8fff48ec14c45
| 5,806
|
kt
|
Kotlin
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Replyd.kt
|
ravitejasc/compose-icons
|
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
|
[
"MIT"
] | 230
|
2020-11-11T14:52:11.000Z
|
2022-03-31T05:04:52.000Z
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Replyd.kt
|
ravitejasc/compose-icons
|
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
|
[
"MIT"
] | 17
|
2021-03-02T00:00:32.000Z
|
2022-03-02T16:01:03.000Z
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Replyd.kt
|
ravitejasc/compose-icons
|
09f752ef051b1c47e60554f3893bbed5ddd8bc1f
|
[
"MIT"
] | 18
|
2021-02-08T06:18:41.000Z
|
2022-03-22T21:48:23.000Z
|
package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.Replyd: ImageVector
get() {
if (_replyd != null) {
return _replyd!!
}
_replyd = Builder(name = "Replyd", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(5.0f, 5.0f)
lineTo(5.0f, 27.0f)
lineTo(27.0f, 27.0f)
lineTo(27.0f, 5.0f)
lineTo(5.0f, 5.0f)
close()
moveTo(7.0f, 7.0f)
lineTo(25.0f, 7.0f)
lineTo(25.0f, 25.0f)
lineTo(7.0f, 25.0f)
lineTo(7.0f, 7.0f)
close()
moveTo(17.7305f, 17.0098f)
curveTo(16.8605f, 17.0098f, 16.1907f, 17.2598f, 15.7207f, 17.7598f)
curveTo(15.2407f, 18.2498f, 15.0f, 19.0f, 15.0f, 20.0f)
curveTo(15.0f, 20.94f, 15.2106f, 21.6692f, 15.6406f, 22.1992f)
curveTo(16.0606f, 22.7292f, 16.7304f, 23.0f, 17.6504f, 23.0f)
curveTo(18.0904f, 23.0f, 18.5006f, 22.9405f, 18.8906f, 22.8105f)
curveTo(19.2806f, 22.6905f, 19.5903f, 22.5296f, 19.8203f, 22.3496f)
lineTo(19.3301f, 21.3906f)
curveTo(19.1901f, 21.4906f, 19.0095f, 21.5897f, 18.7695f, 21.6797f)
curveTo(18.5195f, 21.7697f, 18.2397f, 21.8203f, 17.9297f, 21.8203f)
curveTo(17.4297f, 21.8203f, 17.0696f, 21.7009f, 16.8496f, 21.4609f)
curveTo(16.6196f, 21.2209f, 16.5005f, 20.8609f, 16.4805f, 20.3809f)
lineTo(19.8906f, 20.3809f)
curveTo(19.9206f, 20.1809f, 19.9507f, 20.0005f, 19.9707f, 19.8105f)
curveTo(19.9907f, 19.6305f, 20.0f, 19.4608f, 20.0f, 19.3008f)
curveTo(20.0f, 18.8608f, 19.9305f, 18.4992f, 19.8105f, 18.1992f)
curveTo(19.6805f, 17.9092f, 19.5108f, 17.67f, 19.3008f, 17.5f)
curveTo(19.0808f, 17.32f, 18.8403f, 17.1991f, 18.5703f, 17.1191f)
curveTo(18.3003f, 17.0491f, 18.0205f, 17.0098f, 17.7305f, 17.0098f)
close()
moveTo(13.6602f, 17.0391f)
curveTo(13.3602f, 17.0391f, 13.1009f, 17.1095f, 12.8809f, 17.2695f)
curveTo(12.6609f, 17.4195f, 12.4894f, 17.6302f, 12.3594f, 17.9102f)
lineTo(12.3203f, 17.9102f)
lineTo(12.1406f, 17.1602f)
lineTo(11.0f, 17.1602f)
lineTo(11.0f, 22.8398f)
lineTo(12.4805f, 22.8398f)
lineTo(12.4805f, 19.1699f)
curveTo(12.5405f, 18.9499f, 12.6601f, 18.7709f, 12.8301f, 18.6309f)
curveTo(13.0101f, 18.5009f, 13.2302f, 18.4297f, 13.4902f, 18.4297f)
curveTo(13.6802f, 18.4297f, 13.8909f, 18.4708f, 14.1309f, 18.5508f)
lineTo(14.3301f, 17.1602f)
curveTo(14.0801f, 17.0802f, 13.8502f, 17.0391f, 13.6602f, 17.0391f)
close()
moveTo(22.0703f, 17.1191f)
curveTo(21.7903f, 17.1191f, 21.5802f, 17.1996f, 21.4102f, 17.3496f)
curveTo(21.2402f, 17.5096f, 21.1602f, 17.7205f, 21.1602f, 17.9805f)
curveTo(21.1602f, 18.2505f, 21.2402f, 18.4591f, 21.4102f, 18.6191f)
curveTo(21.5802f, 18.7791f, 21.7903f, 18.8594f, 22.0703f, 18.8594f)
curveTo(22.3503f, 18.8594f, 22.58f, 18.7791f, 22.75f, 18.6191f)
curveTo(22.92f, 18.4591f, 23.0f, 18.2505f, 23.0f, 17.9805f)
curveTo(23.0f, 17.7205f, 22.92f, 17.5096f, 22.75f, 17.3496f)
curveTo(22.58f, 17.1996f, 22.3603f, 17.1191f, 22.0703f, 17.1191f)
close()
moveTo(17.6992f, 18.1895f)
curveTo(18.0392f, 18.1895f, 18.2797f, 18.2995f, 18.4297f, 18.5195f)
curveTo(18.5897f, 18.7395f, 18.6491f, 19.0509f, 18.6191f, 19.4609f)
lineTo(16.5098f, 19.4609f)
curveTo(16.5498f, 19.0809f, 16.6598f, 18.7691f, 16.8398f, 18.5391f)
curveTo(17.0298f, 18.3091f, 17.3092f, 18.1895f, 17.6992f, 18.1895f)
close()
moveTo(22.0703f, 21.2305f)
curveTo(21.7903f, 21.2305f, 21.5802f, 21.3009f, 21.4102f, 21.4609f)
curveTo(21.2402f, 21.6109f, 21.1602f, 21.8198f, 21.1602f, 22.0898f)
curveTo(21.1602f, 22.3598f, 21.2402f, 22.5705f, 21.4102f, 22.7305f)
curveTo(21.5802f, 22.8905f, 21.7903f, 22.9609f, 22.0703f, 22.9609f)
curveTo(22.3503f, 22.9609f, 22.58f, 22.8905f, 22.75f, 22.7305f)
curveTo(22.92f, 22.5705f, 23.0f, 22.3498f, 23.0f, 22.0898f)
curveTo(23.0f, 21.8198f, 22.92f, 21.6109f, 22.75f, 21.4609f)
curveTo(22.58f, 21.3009f, 22.3603f, 21.2305f, 22.0703f, 21.2305f)
close()
}
}
.build()
return _replyd!!
}
private var _replyd: ImageVector? = null
| 55.295238
| 93
| 0.563383
|
b8d2322bd31bd1ef25c5547d1bf3c8bb5a294a33
| 1,218
|
h
|
C
|
nvblox/include/nvblox/core/impl/variadic_template_tools_impl.h
|
Isarm/nvblox
|
9065b8ec973500d1bbd4abc219558e44b4b55ef6
|
[
"Apache-2.0"
] | 83
|
2022-03-23T16:14:00.000Z
|
2022-03-31T13:54:26.000Z
|
nvblox/include/nvblox/core/impl/variadic_template_tools_impl.h
|
Isarm/nvblox
|
9065b8ec973500d1bbd4abc219558e44b4b55ef6
|
[
"Apache-2.0"
] | 4
|
2022-03-30T08:58:24.000Z
|
2022-03-31T14:04:06.000Z
|
nvblox/include/nvblox/core/impl/variadic_template_tools_impl.h
|
Isarm/nvblox
|
9065b8ec973500d1bbd4abc219558e44b4b55ef6
|
[
"Apache-2.0"
] | 5
|
2022-03-25T00:57:08.000Z
|
2022-03-31T09:29:43.000Z
|
/*
Copyright 2022 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
namespace nvblox {
// Unique type
template <class T1, class T2, class... Trest>
struct unique_types<T1, T2, Trest...> {
static constexpr bool value = unique_types<T1, T2>::value &&
unique_types<T1, Trest...>::value &&
unique_types<T2, Trest...>::value;
};
template <class T1, class T2>
struct unique_types<T1, T2> {
static constexpr bool value = !std::is_same<T1, T2>::value;
};
template <class T1>
struct unique_types<T1> {
static constexpr bool value = true;
};
template <>
struct unique_types<> {
static constexpr bool value = true;
};
} // namespace nvblox
| 27.681818
| 72
| 0.699507
|
c72fb579097713011ad7ecb2c64d5572f8833e4e
| 2,529
|
sh
|
Shell
|
jobs/ci-kubernetes-e2e-gke-gci-ci-master.sh
|
smarterclayton/test-infra
|
13bff73612f370ad8096e8a8d731faa5e3697adb
|
[
"Apache-2.0"
] | null | null | null |
jobs/ci-kubernetes-e2e-gke-gci-ci-master.sh
|
smarterclayton/test-infra
|
13bff73612f370ad8096e8a8d731faa5e3697adb
|
[
"Apache-2.0"
] | null | null | null |
jobs/ci-kubernetes-e2e-gke-gci-ci-master.sh
|
smarterclayton/test-infra
|
13bff73612f370ad8096e8a8d731faa5e3697adb
|
[
"Apache-2.0"
] | null | null | null |
#!/bin/bash
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -o errexit
set -o nounset
set -o pipefail
set -o xtrace
readonly testinfra="$(dirname "${0}")/.."
### provider-env
# Use GKE's test endpoint
export CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER="https://test-container.sandbox.googleapis.com/"
# Pull Kubernetes artifacts from this bucket instead of kubernetes-release
export CLOUDSDK_BUCKET="gs://cloud-sdk-testing/ci/staging"
export E2E_MIN_STARTUP_PODS="8"
export FAIL_ON_GCP_RESOURCE_LEAK="true"
export KUBERNETES_PROVIDER="gke"
export ZONE="us-central1-f"
### project-env
# expected empty
### job-env
# Use Google credentials to authenticate to the cluster API server
export CLOUDSDK_CONTAINER_USE_CLIENT_CERTIFICATE=False
export GINKGO_TEST_ARGS="--ginkgo.skip=\[Slow\]|\[Serial\]|\[Disruptive\]|\[Flaky\]|\[Feature:.+\]"
export GINKGO_PARALLEL="y"
# The master branch will always use GCI images built from its
# tip of tree, categorized in family `gci-canary`.
export JENKINS_GCI_HEAD_IMAGE_FAMILY="gci-canary"
export PROJECT="e2e-gke-gci-ci-master"
### post-env
# Assume we're upping, testing, and downing a cluster
export E2E_UP="${E2E_UP:-true}"
export E2E_TEST="${E2E_TEST:-true}"
export E2E_DOWN="${E2E_DOWN:-true}"
export E2E_NAME='bootstrap-e2e'
# Skip gcloud update checking
export CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=true
# Use default component update behavior
export CLOUDSDK_EXPERIMENTAL_FAST_COMPONENT_UPDATE=false
# AWS variables
export KUBE_AWS_INSTANCE_PREFIX="${E2E_NAME}"
# GCE variables
export INSTANCE_PREFIX="${E2E_NAME}"
export KUBE_GCE_NETWORK="${E2E_NAME}"
export KUBE_GCE_INSTANCE_PREFIX="${E2E_NAME}"
# GKE variables
export CLUSTER_NAME="${E2E_NAME}"
export KUBE_GKE_NETWORK="${E2E_NAME}"
# Get golang into our PATH so we can run e2e.go
export PATH="${PATH}:/usr/local/go/bin"
### Runner
readonly runner="${testinfra}/jenkins/dockerized-e2e-runner.sh"
export DOCKER_TIMEOUT="70m"
export KUBEKINS_TIMEOUT="50m"
"${runner}"
| 31.6125
| 99
| 0.774614
|
1a6492d01b283695ff83cd31bcfc228822478899
| 3,192
|
cs
|
C#
|
Source/TK.CustomMap/Api/Google/GmsDirection/GmsDirection.cs
|
joehanna/TK.CustomMap
|
e468e11c165c195fc413ecf2aa6b82cf942a5f6b
|
[
"MIT"
] | 1
|
2022-01-18T16:56:47.000Z
|
2022-01-18T16:56:47.000Z
|
Source/TK.CustomMap/Api/Google/GmsDirection/GmsDirection.cs
|
joehanna/TK.CustomMap
|
e468e11c165c195fc413ecf2aa6b82cf942a5f6b
|
[
"MIT"
] | null | null | null |
Source/TK.CustomMap/Api/Google/GmsDirection/GmsDirection.cs
|
joehanna/TK.CustomMap
|
e468e11c165c195fc413ecf2aa6b82cf942a5f6b
|
[
"MIT"
] | 1
|
2020-10-29T14:06:40.000Z
|
2020-10-29T14:06:40.000Z
|
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TK.CustomMap.Api.Google
{
/// <summary>
/// Calls the Google Maps Directions API to get a route
/// </summary>
public class GmsDirection
{
static string _apiKey;
static GmsDirection _instance;
readonly HttpClient _httpClient;
const string BaseUrl = "https://maps.googleapis.com/maps/api/directions/";
/// <summary>
/// The <see cref="GmsDirection"/> instance
/// </summary>
public static GmsDirection Instance
{
get
{
return _instance ?? (_instance = new GmsDirection());
}
}
/// <summary>
/// Creates a new instance of <see cref="GmsDirection"/>
/// </summary>
GmsDirection()
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri(BaseUrl);
}
/// <summary>
/// Set the API key
/// </summary>
/// <param name="apiKey">Google Maps API key</param>
public static void Init(string apiKey)
{
_apiKey = apiKey;
}
/// <summary>
/// Calculates a route
/// </summary>
/// <param name="origin">The origin</param>
/// <param name="destination">The destination</param>
/// <param name="mode">The travelling mode</param>
/// <param name="language">The language</param>
/// <returns>A <see cref="GmsDirectionResult"/></returns>
public async Task<GmsDirectionResult> CalculateRoute(Position origin, Position destination, GmsDirectionTravelMode mode, string language = null)
{
var response = await _httpClient.GetAsync(BuildQueryString(origin, destination, mode, language));
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<GmsDirectionResult>(await response.Content.ReadAsStringAsync());
}
return null;
}
/// <summary>
/// Builds the query string for the Google Maps Directions API call
/// </summary>
/// <param name="origin">The origin</param>
/// <param name="destination">The destination</param>
/// <param name="mode">The travelling mode</param>
/// <param name="language">The language</param>
/// <returns>The query string</returns>
string BuildQueryString(Position origin, Position destination, GmsDirectionTravelMode mode, string language)
{
StringBuilder strBuilder = new StringBuilder(
string.Format(
"json?origin={0}&destination={1}&mode={2}",
origin.AsString(),
destination.AsString(),
mode.ToString().ToLower()));
if (!string.IsNullOrWhiteSpace(language))
{
strBuilder.AppendFormat("&language={0}", language);
}
strBuilder.AppendFormat("&key={0}", _apiKey);
return strBuilder.ToString();
}
}
}
| 35.865169
| 152
| 0.56485
|
6dc8fc31107b3e84709fa5a66fc2c9bdea27ba6a
| 1,956
|
h
|
C
|
courgette/consecutive_range_visitor.h
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
courgette/consecutive_range_visitor.h
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
courgette/consecutive_range_visitor.h
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_
#define COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_
#include <stddef.h>
#include <iterator>
namespace courgette {
// Usage note: First check whether std::unique() would suffice.
//
// ConsecutiveRangeVisitor is a visitor to read equal consecutive items
// ("ranges") between two iterators. The base value of InputIterator must
// implement the == operator.
//
// Example: "AAAAABZZZZOO" consists of ranges ["AAAAA", "B", "ZZZZ", "OO"]. The
// visitor provides accessors to iterate through the ranges, and to access each
// range's value and repeat, i.e., [('A', 5), ('B', 1), ('Z', 4), ('O', 2)].
template <class InputIterator>
class ConsecutiveRangeVisitor {
public:
ConsecutiveRangeVisitor(InputIterator begin, InputIterator end)
: head_(begin), end_(end) {
advance();
}
ConsecutiveRangeVisitor(const ConsecutiveRangeVisitor&) = delete;
ConsecutiveRangeVisitor& operator=(const ConsecutiveRangeVisitor&) = delete;
// Returns whether there are more ranges to traverse.
bool has_more() const { return tail_ != end_; }
// Returns an iterator to an element in the current range.
InputIterator cur() const { return tail_; }
// Returns the number of repeated elements in the current range.
size_t repeat() const { return std::distance(tail_, head_); }
// Advances to the next range.
void advance() {
tail_ = head_;
if (head_ != end_)
while (++head_ != end_ && *head_ == *tail_) {}
}
private:
InputIterator tail_; // The trailing pionter of a range (inclusive).
InputIterator head_; // The leading pointer of a range (exclusive).
InputIterator end_; // Store the end pointer so we know when to stop.
};
} // namespace courgette
#endif // COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_
| 33.152542
| 79
| 0.715746
|
1890676c800ba9de229aa335cd0f0e975ed2e636
| 576
|
tsx
|
TypeScript
|
src/components/index.tsx
|
ZeedKey/NextJS-TestTask
|
ff2a6d4fac251126e0c89b5bee8f1ab9bc3a581f
|
[
"MIT"
] | null | null | null |
src/components/index.tsx
|
ZeedKey/NextJS-TestTask
|
ff2a6d4fac251126e0c89b5bee8f1ab9bc3a581f
|
[
"MIT"
] | 1
|
2021-12-10T06:45:39.000Z
|
2021-12-10T06:45:39.000Z
|
src/components/index.tsx
|
ZeedKey/NextJS-TestTask
|
ff2a6d4fac251126e0c89b5bee8f1ab9bc3a581f
|
[
"MIT"
] | null | null | null |
import { validationSchema } from "./validation/UserDataValidation";
import { operators } from "./storage/operatorStorage";
import { OperatorCard } from "./static/OperatorCard";
import { OperatorForm } from "./static/OperatorForm";
import { Button } from "./customs/Button";
import { Input } from "./customs/Input";
import { MainLayout } from "./static/MainLayout";
import { Footer } from "./static/Footer";
import { Alert } from "./static/Alert";
export {
Button,
Footer,
MainLayout,
OperatorCard,
OperatorForm,
operators,
Input,
Alert,
validationSchema,
};
| 27.428571
| 67
| 0.708333
|
9797c3d1643ba4058664119f32b000caca5a1ae3
| 1,595
|
swift
|
Swift
|
Swift/Courses/CrackingTheCodingInterview/Chapter_1 (Strings & Search)/URLify_1_3.swift
|
devMEremenko/Coding-Challenges
|
803b1dfe00afb6a9e9651db02f9a223cb2f1bd64
|
[
"MIT"
] | 10
|
2019-07-19T06:17:50.000Z
|
2022-01-08T03:00:00.000Z
|
Swift/Courses/CrackingTheCodingInterview/Chapter_1 (Strings & Search)/URLify_1_3.swift
|
devMEremenko/LeetCode
|
803b1dfe00afb6a9e9651db02f9a223cb2f1bd64
|
[
"MIT"
] | null | null | null |
Swift/Courses/CrackingTheCodingInterview/Chapter_1 (Strings & Search)/URLify_1_3.swift
|
devMEremenko/LeetCode
|
803b1dfe00afb6a9e9651db02f9a223cb2f1bd64
|
[
"MIT"
] | 1
|
2019-04-11T10:33:50.000Z
|
2019-04-11T10:33:50.000Z
|
//
// URLify_1_3.swift
// CodingChallenges
//
// Created by Maxim Eremenko on 9/6/18.
// Copyright © 2018 Eremenko Maxim. All rights reserved.
//
import XCTest
class URLifyTests: XCTestCase {
/// Write a method to replace all spaces in a string with '%20'.
///
/// You may assume that the string has sufficient space at the end
/// to hold the additional characters, and that you are given the "true" length
/// of the string.
///
/// Note: Please perform this operation in place
///
/// Example
///
/// Input: "Mr John Smith "
///
/// Output: "Mr%20John%20Smith"
func testUrlify() {
var input = "Mr Max "
urlify(&input, 6)
XCTAssert(input == "Mr%20Max")
}
func testUrlifyEmpty() {
var input = ""
urlify(&input, 0)
XCTAssert(input == "")
}
func testUrlifyWithAllSpaces() {
var input = " "
urlify(&input, 2)
XCTAssert(input == "%20%20")
}
func urlify(_ source: inout String, _ trueLength: Int) {
var lastEditIndex = source.count - 1
for idx in stride(from: trueLength - 1, through: 0, by: -1) {
if source[idx] != " " {
source[lastEditIndex] = source[idx]
lastEditIndex -= 1
} else {
source[lastEditIndex - 2 ..< lastEditIndex + 1] = "%20"
lastEditIndex -= 3
}
}
}
}
| 22.785714
| 83
| 0.490909
|
131d8680d2c820d2080f3d6467dce48543c2a662
| 77
|
ps1
|
PowerShell
|
01/01-Install-AZ-PS.ps1
|
DaraOladapo/AZ103-Jordan
|
0b3f87356230048f7e8f27eb5c4f054f4d98183e
|
[
"MIT"
] | null | null | null |
01/01-Install-AZ-PS.ps1
|
DaraOladapo/AZ103-Jordan
|
0b3f87356230048f7e8f27eb5c4f054f4d98183e
|
[
"MIT"
] | null | null | null |
01/01-Install-AZ-PS.ps1
|
DaraOladapo/AZ103-Jordan
|
0b3f87356230048f7e8f27eb5c4f054f4d98183e
|
[
"MIT"
] | 1
|
2020-05-18T17:06:54.000Z
|
2020-05-18T17:06:54.000Z
|
#Install-Module -Name Az -AllowClobber -Scope CurrentUser
Connect-AzAccount
| 19.25
| 57
| 0.818182
|
a4113542340371e5d7e0e322730379f121ffc01a
| 3,845
|
php
|
PHP
|
admin/template/commentsettings.tpl.php
|
gaoyicoder/ezi2u.cn
|
b0e01e8b06348e15ed9af7b7a7644b462585926d
|
[
"Apache-2.0"
] | null | null | null |
admin/template/commentsettings.tpl.php
|
gaoyicoder/ezi2u.cn
|
b0e01e8b06348e15ed9af7b7a7644b462585926d
|
[
"Apache-2.0"
] | null | null | null |
admin/template/commentsettings.tpl.php
|
gaoyicoder/ezi2u.cn
|
b0e01e8b06348e15ed9af7b7a7644b462585926d
|
[
"Apache-2.0"
] | null | null | null |
<?php mymps_admin_tpl_global_head();?>
<style>
.vbm td li{ margin:10px 0!important;}
</style>
<div id="<?=MPS_SOFTNAME?>" style="padding-bottom:0">
<div class="mpstopic-category">
<div class="panel-tab">
<ul class="clearfix tab-list">
<li><a href="config.php?part=imgcode" <?php if($part == 'imgcode'){?>class="current"<?php }?>>Identifying Code Control</a></li>
<li><a href="config.php?part=checkask" <?php if($part == 'checkask'){?>class="current"<?php }?>>Identifying Question &Answer Settings</a></li>
<li><a href="config.php?part=badwords" <?php if($part == 'badwords'){?>class="current"<?php }?>>Filtering Settings</a></li>
<li><a href="config.php?part=commentsettings" <?php if($part == 'commentsettings'){?>class="current"<?php }?>>Comment Settings</a></li>
</ul>
</div>
</div>
</div>
<form action="?config.php?" method="post">
<input name="part" type="hidden" value="commentsettings">
<input name="action" type="hidden" value="do_post">
<div id="<?=MPS_SOFTNAME?>">
<table border="0" cellspacing="0" cellpadding="0" class="vbm">
<tr class="firstr">
<td colspan="2" align="left">Comment Settings</td>
</tr>
<tr bgcolor="#ffffff">
<td align="left" class="altbg1" width="250">
Comment on Posts/information
</td>
<td align="left" valign="top" style="line-height:25px;">
<label for="information_0"><input type="radio" name="comment[information]" id="information_0" class="checkbox" value="0" <?php if($comment['information'] == 0) echo 'checked';?>>Disable Comment</label><br />
<label for="information_1"><input type="radio" name="comment[information]" id="information_1" class="checkbox" value="1" <?php if($comment['information'] == 1) echo 'checked';?>>Anonymous Comment On</label><br />
<label for="information_2"><input name="comment[information]" type="radio" id="information_2" class="checkbox" value="2" <?php if($comment['information'] == 2) echo 'checked';?>>Member Comment On</label>
</td>
</tr>
<tr bgcolor="#ffffff">
<td align="left" class="altbg1">
Comment on News/news
</td>
<td align="left" valign="top" style="line-height:25px;">
<label for="news_0"><input type="radio" name="comment[news]" id="news_0" class="checkbox" value="0" <?php if($comment['news'] == 0) echo 'checked';?>>Disable Comment</label><br />
<label for="news_1"><input type="radio" name="comment[news]" id="news_1" class="checkbox" value="1" <?php if($comment['news'] == 1) echo 'checked';?>>Anonymous Comment On</label><br />
<label for="news_2"><input name="comment[news]" type="radio" id="news_2" class="checkbox" value="2" <?php if($comment['news'] == 2) echo 'checked';?>>Member Comment On</label>
</td>
</tr>
<tr bgcolor="#ffffff">
<td align="left" class="altbg1">
Comment on Sellers/store
</td>
<td align="left" valign="top" style="line-height:25px;">
<label for="store_0"><input type="radio" name="comment[store]" id="store_0" class="checkbox" value="0" <?php if($comment['store'] == 0) echo 'checked';?>>Disable Comment</label><br />
<label for="store_1"><input type="radio" name="comment[store]" id="store_1" class="checkbox" value="1" <?php if($comment['store'] == 1) echo 'checked';?>>Anonymous Comment On</label><br />
<label for="store_2"><input name="comment[store]" type="radio" id="store_2" class="checkbox" value="2" <?php if($comment['store'] == 2) echo 'checked';?>>Member Comment On</label>
</td>
</tr>
</table>
</div>
<center>
<input class="mymps large" name="<?=CURSCRIPT?>_submit" value="Submit" type="submit" >
</center>
</form>
<?php mymps_admin_tpl_global_foot();?>
| 30.76
| 215
| 0.613784
|
7aa93c0e21cb3de32be415ae5521bb09ac7f447e
| 5,902
|
cs
|
C#
|
src/NHM.MinerPluginToolkitV1/Configs/MinerBenchmarkTimeSettings.cs
|
xizaha/NiceHashMiner
|
7c4ef0aabff6aafb22d44d99a23811337fe862b1
|
[
"MIT"
] | 1,234
|
2017-07-11T17:32:28.000Z
|
2019-07-03T02:13:51.000Z
|
src/NHM.MinerPluginToolkitV1/Configs/MinerBenchmarkTimeSettings.cs
|
xizaha/NiceHashMiner
|
7c4ef0aabff6aafb22d44d99a23811337fe862b1
|
[
"MIT"
] | 1,495
|
2017-07-11T01:22:31.000Z
|
2019-07-04T10:17:14.000Z
|
src/NHM.MinerPluginToolkitV1/Configs/MinerBenchmarkTimeSettings.cs
|
xizaha/NiceHashMiner
|
7c4ef0aabff6aafb22d44d99a23811337fe862b1
|
[
"MIT"
] | 621
|
2017-07-13T02:12:51.000Z
|
2019-07-03T17:18:23.000Z
|
using Newtonsoft.Json;
using NHM.Common;
using NHM.Common.Configs;
using NHM.Common.Enums;
using NHM.MinerPlugin;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NHM.MinerPluginToolkitV1.Configs
{
public class MinerBenchmarkTimeSettings : IInternalSetting
{
[JsonProperty("use_user_settings")]
public bool UseUserSettings { get; set; } = false;
[JsonProperty("max_ticks_enabled")]
public bool MaxTicksEnabled { get; set; } = true;
[JsonProperty("time_general_s")]
public Dictionary<BenchmarkPerformanceType, int> General { get; set; } = new Dictionary<BenchmarkPerformanceType, int> {
{ BenchmarkPerformanceType.Quick, 20 },
{ BenchmarkPerformanceType.Standard, 60 },
{ BenchmarkPerformanceType.Precise, 120 },
};
[JsonProperty("time_per_algorithm_s")]
public Dictionary<BenchmarkPerformanceType, Dictionary<string, int>> PerAlgorithm { get; set; } = new Dictionary<BenchmarkPerformanceType, Dictionary<string, int>> {
{ BenchmarkPerformanceType.Quick, new Dictionary<string, int>() },
{ BenchmarkPerformanceType.Standard, new Dictionary<string, int>() },
{ BenchmarkPerformanceType.Precise, new Dictionary<string, int>() },
};
[JsonProperty("max_ticks_general")]
public Dictionary<BenchmarkPerformanceType, int> GeneralTicks { get; set; } = new Dictionary<BenchmarkPerformanceType, int> {
{ BenchmarkPerformanceType.Quick, 1 },
{ BenchmarkPerformanceType.Standard, 3 },
{ BenchmarkPerformanceType.Precise, 9 },
};
[JsonProperty("max_ticks_per_algorithm")]
public Dictionary<BenchmarkPerformanceType, Dictionary<string, int>> PerAlgorithmTicks { get; set; } = new Dictionary<BenchmarkPerformanceType, Dictionary<string, int>> {
{ BenchmarkPerformanceType.Quick, new Dictionary<string, int>() },
{ BenchmarkPerformanceType.Standard, new Dictionary<string, int>() },
{ BenchmarkPerformanceType.Precise, new Dictionary<string, int>() },
};
public static int ParseBenchmarkTime(List<int> defaults, MinerBenchmarkTimeSettings timeSetting, IEnumerable<MiningPair> miningPairs, BenchmarkPerformanceType benchmarkType)
{
var dict = new Dictionary<BenchmarkPerformanceType, int> {
{BenchmarkPerformanceType.Quick, defaults[0] },
{BenchmarkPerformanceType.Standard, defaults[1] },
{BenchmarkPerformanceType.Precise, defaults[2] },
};
return ParseBenchmarkTime(dict, timeSetting, miningPairs, benchmarkType);
}
public static int ParseBenchmarkTime(Dictionary<BenchmarkPerformanceType, int> defaults, MinerBenchmarkTimeSettings timeSetting, IEnumerable<MiningPair> miningPairs, BenchmarkPerformanceType benchmarkType)
{
try
{
// TimePerAlgorithm has #1 priority
if (timeSetting.PerAlgorithm != null && timeSetting.PerAlgorithm.ContainsKey(benchmarkType))
{
var pairTypeTimeout = timeSetting.PerAlgorithm[benchmarkType];
var algorithmName = miningPairs.FirstOrDefault()?.Algorithm?.AlgorithmName ?? "";
if (pairTypeTimeout != null && !string.IsNullOrEmpty(algorithmName) && pairTypeTimeout.ContainsKey(algorithmName))
{
return pairTypeTimeout[algorithmName];
}
} // TimePerType has #2 priority
else if (timeSetting.General != null && timeSetting.General.ContainsKey(benchmarkType)) return timeSetting.General[benchmarkType];
}
catch (Exception e)
{
Logger.Error("ParseBenchmarkTime", $"ParseBenchmarkTime failed: {e.Message}");
}
return defaults[benchmarkType];
}
public static int ParseBenchmarkTicks(List<int> defaults, MinerBenchmarkTimeSettings timeSetting, IEnumerable<MiningPair> miningPairs, BenchmarkPerformanceType benchmarkType)
{
var dict = new Dictionary<BenchmarkPerformanceType, int> {
{BenchmarkPerformanceType.Quick, defaults[0] },
{BenchmarkPerformanceType.Standard, defaults[1] },
{BenchmarkPerformanceType.Precise, defaults[2] },
};
return ParseBenchmarkTicks(dict, timeSetting, miningPairs, benchmarkType);
}
public static int ParseBenchmarkTicks(Dictionary<BenchmarkPerformanceType, int> defaults, MinerBenchmarkTimeSettings timeSetting, IEnumerable<MiningPair> miningPairs, BenchmarkPerformanceType benchmarkType)
{
try
{
// TimePerAlgorithm has #1 priority
if (timeSetting.PerAlgorithmTicks != null && timeSetting.PerAlgorithmTicks.ContainsKey(benchmarkType))
{
var pairTypeTimeout = timeSetting.PerAlgorithmTicks[benchmarkType];
var algorithmName = miningPairs.FirstOrDefault()?.Algorithm?.AlgorithmName ?? "";
if (pairTypeTimeout != null && !string.IsNullOrEmpty(algorithmName) && pairTypeTimeout.ContainsKey(algorithmName))
{
return pairTypeTimeout[algorithmName];
}
} // TimePerType has #2 priority
else if (timeSetting.GeneralTicks != null && timeSetting.GeneralTicks.ContainsKey(benchmarkType)) return timeSetting.GeneralTicks[benchmarkType];
}
catch (Exception e)
{
Logger.Error("ParseBenchmarkTicks", $"ParseBenchmarkTicks failed: {e.Message}");
}
return defaults[benchmarkType];
}
}
}
| 50.444444
| 214
| 0.644358
|
da9933bfb4f5133ba86ee7e5fdde9d1f09111d9c
| 3,957
|
lua
|
Lua
|
lib/StyleGramMatrixLossModule.lua
|
sylvielee/style-swap-819
|
14e8727156c831d471b131058a56f1bbf1a916a5
|
[
"MIT"
] | 418
|
2016-12-14T02:47:48.000Z
|
2022-03-29T03:27:36.000Z
|
lib/StyleGramMatrixLossModule.lua
|
sylvielee/style-swap-819
|
14e8727156c831d471b131058a56f1bbf1a916a5
|
[
"MIT"
] | 40
|
2016-12-14T14:32:08.000Z
|
2018-03-21T00:45:57.000Z
|
lib/StyleGramMatrixLossModule.lua
|
sylvielee/style-swap-819
|
14e8727156c831d471b131058a56f1bbf1a916a5
|
[
"MIT"
] | 117
|
2016-12-14T02:56:34.000Z
|
2022-02-27T18:34:25.000Z
|
require 'nn'
autograd = require 'autograd'
local module, parent = torch.class('nn.StyleGramMatrixLossModule', 'nn.Module')
function module:__init(strength, normalize)
parent.__init(self)
self.normalize = normalize or false
self.strength = strength or 1
self.target = nil
self.loss = 0
self.fun = self.GramMatrixLoss
self.dfun = autograd(self.fun)
end
function module:clearState()
self.dfun = nil
return parent.clearState(self)
end
-- Input N x C x H x W
local gramMatrix = function(input)
local N,C,H,W = input:size(1), input:size(2), input:size(3), input:size(4)
local vecInput = input:view(N,C,H*W)
local gramMatrix = torch.bmm(vecInput, torch.transpose(vecInput, 2,3))
local output = gramMatrix / H / W
return output
end
local squareErr = function(input, target)
local buffer = input-target
return torch.sum( torch.cmul(buffer, buffer) )
end
local sqFrobnorm = function(x)
return torch.sum( torch.cmul(x,x) )
end
-- Input N x C x H x W
-- Target N x C x C
function module.GramMatrixLoss(input, target)
local gmInput = gramMatrix(input)
local sqErr = squareErr(gmInput, target)
local sqNorm = sqFrobnorm(gmInput)
local error = sqErr / sqNorm
if input:nDimension()==4 then error = error / input:size(1) end
return error
end
function module:setTarget(target_features)
if target_features:nDimension() == 3 then
local C,H,W = target_features:size(1), target_features:size(2), target_features:size(3)
local target = gramMatrix(target_features:view(1,C,H,W))
self.target = target:view(1,C,C)
elseif target_features:nDimension() == 4 then
local N,C,H,W = target_features:size(1), target_features:size(2), target_features:size(3), target_features:size(4)
local target = gramMatrix(target_features)
self.target = target:view(N,C,C)
else
error('Target must be 3D or 4D')
end
return self
end
function module:unsetTarget()
self.target = nil
return self
end
-- if # targets > 1 then assume # targets == # samples per batch
function module:updateOutput(input)
self.output = input
if self.target ~= nil then
if input:nDimension() == 3 then
local C,H,W = input:size(1), input:size(2), input:size(3)
input = input:view(1,C,H,W)
end
assert(input:nDimension()==4)
local N,C,H,W = input:size(1), input:size(2), input:size(3), input:size(4)
assert(input:size(2) == self.target:size(2))
if self.target:size(1) == 1 then
self.match = self.target:expand(N,C,C)
else
self.match = self.target
end
self.loss = self.fun(input, self.target)
self.loss = self.loss * self.strength
end
return self.output
end
function module:updateGradInput(input, gradOutput)
if self.target ~= nil then
local nInputDim = input:nDimension()
if input:nDimension() == 3 then
local C,H,W = input:size(1), input:size(2), input:size(3)
input = input:view(1,C,H,W)
end
assert(input:nDimension()==4)
local N,C,H,W = input:size(1), input:size(2), input:size(3), input:size(4)
assert(input:size(2) == self.target:size(2))
if self.target:size(1) == 1 then
self.match = self.target:expand(N,C,C)
else
self.match = self.target
end
if self.dfun == nil then
self.dfun = autograd(self.fun)
end
self.gradInput = self.dfun(input, self.target)
if self.normalize then
self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8)
end
if nInputDim == 3 then
self.gradInput = self.gradInput:view(C,H,W)
end
self.gradInput:mul(self.strength)
self.gradInput:add(gradOutput)
else
self.gradInput = gradOutput
end
return self.gradInput
end
| 29.095588
| 122
| 0.631539
|
67ac1f3128d019fc1322932c444bc64d4bf5fd5e
| 3,302
|
dart
|
Dart
|
lib/src/ignore_seed_value_observable.dart
|
toSkyrocket/flutter_bloc
|
48eb0ee3f1b50934ee6ef32693b16838a817537b
|
[
"MIT"
] | null | null | null |
lib/src/ignore_seed_value_observable.dart
|
toSkyrocket/flutter_bloc
|
48eb0ee3f1b50934ee6ef32693b16838a817537b
|
[
"MIT"
] | null | null | null |
lib/src/ignore_seed_value_observable.dart
|
toSkyrocket/flutter_bloc
|
48eb0ee3f1b50934ee6ef32693b16838a817537b
|
[
"MIT"
] | null | null | null |
import 'dart:async';
import 'package:rxdart/rxdart.dart';
///为了解决seedValue会触发监听的问题,但又想第一次能取到值
class IgnoreSeedValueObservable<T> extends ConnectableStream<T>
implements ValueStream<T> {
final Stream<T> _source;
final _IgnoreSeedBehaviorSubject<T> _subject;
IgnoreSeedValueObservable._(this._source, this._subject) : super(_subject);
///设置seedValue后不触发监听
factory IgnoreSeedValueObservable.seeded(
Stream<T> source,
T seedValue,
) =>
IgnoreSeedValueObservable<T>._(
source, _IgnoreSeedBehaviorSubject.seeded(seedValue));
@override
ValueStream<T> autoConnect({
void Function(StreamSubscription<T> subscription) connection,
}) {
_subject.onListen = () {
if (connection != null) {
connection(connect());
} else {
connect();
}
};
return _subject;
}
@override
StreamSubscription<T> connect() {
return ConnectableStreamSubscription<T>(
_source.listen(_subject.add, onError: _subject.addError),
_subject,
);
}
@override
ValueStream<T> refCount() {
ConnectableStreamSubscription<T> subscription;
_subject.onListen = () {
subscription = ConnectableStreamSubscription<T>(
_source.listen(_subject.add, onError: _subject.addError),
_subject,
);
};
_subject.onCancel = () {
subscription.cancel();
};
return _subject;
}
@override
T get value => _subject.value;
@override
bool get hasValue => _subject.hasValue;
}
class _IgnoreSeedBehaviorSubject<T> extends Subject<T>
implements ValueStream<T> {
_Wrapper<T> _wrapper;
_IgnoreSeedBehaviorSubject._(
StreamController<T> controller,
Stream<T> observable,
this._wrapper,
) : super(controller, observable);
factory _IgnoreSeedBehaviorSubject.seeded(
T seedValue, {
void onListen(),
void onCancel(),
bool sync = false,
}) {
// ignore: close_sinks
final controller = StreamController<T>.broadcast(
onListen: onListen,
onCancel: onCancel,
sync: sync,
);
final wrapper = _Wrapper<T>.seeded(seedValue);
return _IgnoreSeedBehaviorSubject<T>._(
controller, controller.stream, wrapper);
}
@override
void onAdd(T event) => _wrapper.setValue(event);
@override
void onAddError(Object error, [StackTrace stackTrace]) =>
_wrapper.setError(error, stackTrace);
@override
ValueStream<T> get stream => this;
@override
bool get hasValue => _wrapper.latestIsValue;
/// Get the latest value emitted by the Subject
@override
T get value => _wrapper.latestValue;
/// Set and emit the new value
set value(T newValue) => add(newValue);
}
class _Wrapper<T> {
T latestValue;
Object latestError;
StackTrace latestStackTrace;
bool latestIsValue = false, latestIsError = false;
/// Non-seeded constructor
_Wrapper();
_Wrapper.seeded(this.latestValue) : latestIsValue = true;
void setValue(T event) {
latestIsValue = true;
latestIsError = false;
latestValue = event;
latestError = null;
latestStackTrace = null;
}
void setError(Object error, [StackTrace stackTrace]) {
latestIsValue = false;
latestIsError = true;
latestValue = null;
latestError = error;
latestStackTrace = stackTrace;
}
}
| 22.013333
| 77
| 0.677771
|
d9d312eab1f57140fb9b24cac76b04f6d27282c5
| 3,238
|
kt
|
Kotlin
|
vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt
|
rottenstonks/SchildiChat-android
|
c1149858c4ebaae6017272bdfb6c49beb7ed2f07
|
[
"Apache-2.0"
] | null | null | null |
vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt
|
rottenstonks/SchildiChat-android
|
c1149858c4ebaae6017272bdfb6c49beb7ed2f07
|
[
"Apache-2.0"
] | null | null | null |
vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt
|
rottenstonks/SchildiChat-android
|
c1149858c4ebaae6017272bdfb6c49beb7ed2f07
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.app.features.home.room.detail.timeline.item
import android.content.Context
import android.view.View
import android.view.ViewStub
import android.widget.FrameLayout
import android.widget.RelativeLayout
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.core.view.updateLayoutParams
import com.airbnb.epoxy.EpoxyAttribute
import im.vector.app.R
import im.vector.app.core.epoxy.VectorEpoxyHolder
import im.vector.app.core.epoxy.VectorEpoxyModel
import im.vector.app.core.platform.CheckableView
import im.vector.app.core.ui.views.BubbleDependentView
import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout
/**
* Children must override getViewType()
*/
abstract class BaseEventItem<H : BaseEventItem.BaseHolder> : VectorEpoxyModel<H>(), ItemWithEvents, BubbleDependentView<H> {
// To use for instance when opening a permalink with an eventId
@EpoxyAttribute
var highlighted: Boolean = false
@EpoxyAttribute
open var leftGuideline: Int = 0
final override fun getViewType(): Int {
// This makes sure we have a unique integer for the combination of layout and ViewStubId.
val pairingResult = pairingFunction(layout.toLong(), getViewStubId().toLong())
return (pairingResult - Int.MAX_VALUE).toInt()
}
abstract fun getViewStubId(): Int
// Szudzik function
private fun pairingFunction(a: Long, b: Long): Long {
return if (a >= b) a * a + a + b else a + b * b
}
@CallSuper
override fun bind(holder: H) {
super.bind(holder)
holder.leftGuideline.updateLayoutParams<RelativeLayout.LayoutParams> {
if (ignoreMessageGuideline(holder.leftGuideline.context)) {
this.marginStart = 0
} else {
this.marginStart = leftGuideline
}
}
holder.checkableBackground.isChecked = highlighted
}
abstract class BaseHolder(@IdRes val stubId: Int) : VectorEpoxyHolder() {
val leftGuideline by bind<View>(R.id.messageStartGuideline)
val contentContainer by bind<View>(R.id.viewStubContainer)
val checkableBackground by bind<CheckableView>(R.id.messageSelectedBackground)
val viewStubContainer by bind<FrameLayout>(R.id.viewStubContainer)
override fun bindView(itemView: View) {
super.bindView(itemView)
inflateStub()
}
private fun inflateStub() {
view.findViewById<ViewStub>(stubId).inflate()
}
}
open fun ignoreMessageGuideline(context: Context): Boolean {
return false
}
}
| 35.195652
| 124
| 0.712477
|
7e6c3ec4fc1ec5cf592027459629f378b333d889
| 10,433
|
rb
|
Ruby
|
test/functional/ios/ios/device_test.rb
|
fruwe/ruby_lib_core
|
d757de4273b95aa27b12eb9b7b9be4ef65409b4c
|
[
"Apache-2.0"
] | null | null | null |
test/functional/ios/ios/device_test.rb
|
fruwe/ruby_lib_core
|
d757de4273b95aa27b12eb9b7b9be4ef65409b4c
|
[
"Apache-2.0"
] | null | null | null |
test/functional/ios/ios/device_test.rb
|
fruwe/ruby_lib_core
|
d757de4273b95aa27b12eb9b7b9be4ef65409b4c
|
[
"Apache-2.0"
] | null | null | null |
require 'test_helper'
require 'base64'
# $ rake test:func:ios TEST=test/functional/ios/ios/device_test.rb
# rubocop:disable Style/ClassVars
class AppiumLibCoreTest
module Ios
class DeviceTest < AppiumLibCoreTest::Function::TestCase
def setup
@@core ||= ::Appium::Core.for(Caps.ios)
@@driver ||= @@core.start_driver
end
def test_image_element
skip 'Requres `npm install -g appium opencv4nodejs`' unless `npm list -g opencv4nodejs`.include? 'opencv4nodejs'
@@driver.update_settings({ fixImageFindScreenshotDims: false,
fixImageTemplateSize: true,
autoUpdateImageElementPosition: true })
e = @@driver.find_element_by_image AppiumLibCoreTest.path_of('test/functional/data/test_button_image_ios.png')
assert e.inspect
assert e.hash
assert e.ref =~ /\Aappium-image-element-[a-z0-9\-]+/
assert e.location.x
assert e.location.y
assert e.size.width
assert e.size.height
assert e.rect.x
assert e.rect.y
assert e.rect.width
assert e.rect.height
assert e.displayed?
end
def test_image_elements
skip 'Requres `npm install -g appium opencv4nodejs`' unless `npm list -g opencv4nodejs`.include? 'opencv4nodejs'
@@driver.update_settings({ fixImageTemplateSize: true,
autoUpdateImageElementPosition: true })
e = @@driver.find_elements_by_image AppiumLibCoreTest.path_of('test/functional/data/test_arrow_multiple_ios.png')
assert e[0].inspect
assert e[0].hash
assert e[0].ref =~ /\Aappium-image-element-[a-z0-9\-]+/
assert e[0].location
assert e[0].size
assert e[0].rect
assert e[0].displayed?
end
def teardown
save_reports(@@driver)
end
def test_window_size
size = @@driver.window_size
assert size.width
assert size.height
end
def test_window_rect
size = @@driver.window_rect
assert size.width
assert size.height
assert size.x
assert size.y
end
def test_shake
skip 'NotImplemented' if @@core.automation_name == :xcuitest
assert @@driver.shake
end
def test_close_and_launch_app
@@driver.close_app
assert_equal ['NATIVE_APP'], @@driver.available_contexts
@@driver.launch_app
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextView' }
assert_equal 'TextView', e.name
end
def test_lock_unlock
@@driver.lock
@@core.wait { assert @@driver.device_locked? }
@@driver.unlock
@@core.wait { assert !@@driver.device_locked? }
end
def test_background_reset
@@driver.background_app 5
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextView' }
assert_equal 'TextView', e.name
@@driver.background_app(-1)
error = assert_raises ::Selenium::WebDriver::Error::WebDriverError do
@@driver.find_element :accessibility_id, 'TextView'
end
assert 'An element could not be located on the page using the given search parameters.', error.message
@@driver.reset
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextView' }
assert_equal 'TextView', e.name
end
def test_device_time
require 'date'
assert Date.parse(@@driver.device_time).is_a?(Date)
end
def test_context_related
e = @@core.wait { @@driver.find_element :accessibility_id, 'Web' }
e.click
contexts = @@driver.available_contexts
assert_equal ['NATIVE_APP'], contexts
assert_equal 'NATIVE_APP', @@driver.current_context
@@driver.context = contexts.last
assert_match 'NATIVE_APP', @@driver.current_context
@@driver.switch_to_default_context
assert_equal 'NATIVE_APP', @@driver.current_context
@@driver.back # go to top
end
def test_app_string
assert_equal 'Use of UISearchBar', @@driver.app_strings['SearchBarExplain']
end
def test_re_install
skip 'NotImplemented' if @@core.automation_name == :xcuitest
assert @@driver.app_installed?('com.example.apple-samplecode.UICatalog')
@@driver.remove_app 'com.example.apple-samplecode.UICatalog'
assert !@@driver.app_installed?('com.example.apple-samplecode.UICatalog')
@@driver.install_app Caps.ios[:caps][:app]
assert @@driver.app_installed?('com.example.apple-samplecode.UICatalog')
end
def test_app_management
assert @@driver.app_state('com.example.apple-samplecode.UICatalog') == :running_in_foreground
assert @@driver.terminate_app('com.example.apple-samplecode.UICatalog')
assert @@driver.app_state('com.example.apple-samplecode.UICatalog') == :not_running
assert @@driver.activate_app('com.example.apple-samplecode.UICatalog') == {}
assert @@driver.app_state('com.example.apple-samplecode.UICatalog') == :running_in_foreground
end
def test_pull_file
# Only pulling files from application containers is supported for iOS Simulator.
# Provide the remote path in format @<bundle_id>/<path_to_the_file_in_its_container>
read_file = @@driver.pull_file 'Library/AddressBook/AddressBook.sqlitedb'
assert read_file.start_with?('SQLite format')
end
def test_push_file
skip
# @driver.push_file path, filedata
end
def test_pull_folder
data = @@driver.pull_folder 'Library/AddressBook'
assert data.length > 1
end
def test_settings
assert_equal(false, @@driver.get_settings['nativeWebTap'])
@@driver.update_settings('nativeWebTap' => true)
assert_equal(true, @@driver.get_settings['nativeWebTap'])
@@driver.update_settings('nativeWebTap' => false)
end
def test_touch_actions
if @@core.automation_name == :xcuitest
element = @@core.wait { @@driver.find_element :accessibility_id, 'TextView' }
@@driver.execute_script('mobile: tap', x: 0, y: 0, element: element.ref)
else
Appium::Core::TouchAction.new(@@driver)
.press(element: @@driver.find_element(:accessibility_id, 'TextView'))
.perform
end
@@core.wait { @@driver.find_element :accessibility_id, 'Back' }
@@driver.back
end
def test_swipe
@@core.wait { @@driver.find_element :accessibility_id, 'Buttons' }.click
el = @@core.wait { @@driver.find_element :accessibility_id, 'Gray' }
rect = el.rect
Appium::Core::TouchAction
.new(@@driver)
.swipe(start_x: 75, start_y: 500, end_x: 75, end_y: 500, duration: 500)
.perform
assert rect.x == el.rect.x
assert rect.y == el.rect.y
touch_action = Appium::Core::TouchAction
.new(@@driver)
.swipe(start_x: 75, start_y: 500, end_x: 75, end_y: 300, duration: 500)
assert_equal :press, touch_action.actions[0][:action]
assert_equal({ x: 75, y: 500 }, touch_action.actions[0][:options])
assert_equal :wait, touch_action.actions[1][:action]
assert_equal({ ms: 500 }, touch_action.actions[1][:options])
assert_equal :moveTo, touch_action.actions[2][:action]
assert_equal({ x: 75, y: 300 }, touch_action.actions[2][:options])
assert_equal :release, touch_action.actions[3][:action]
touch_action.perform
assert_equal [], touch_action.actions
assert !el.displayed? # gone
assert rect.y > el.rect.y
@@driver.back
end
def test_touch_id
assert_nil @@driver.toggle_touch_id_enrollment
assert_nil @@driver.toggle_touch_id_enrollment(true)
assert_nil @@driver.toggle_touch_id_enrollment(false)
end
def test_hidekeyboard
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextFields' }
e.click
text = @@core.wait { @@driver.find_element :name, '<enter text>' }
text.click
assert @@driver.find_element(:class, 'XCUIElementTypeKeyboard').displayed?
@@core.wait do
@@driver.hide_keyboard
sleep 1 # wait animation
end
m = assert_raises ::Selenium::WebDriver::Error::WebDriverError do
@@driver.find_element(:class, 'XCUIElementTypeKeyboard')
end
assert 'An element could not be located on the page using the given search parameters.', m.message
@@driver.back
end
def test_within_context
result = @@driver.within_context('NATIVE_APP') do
@@core.wait { @@driver.find_element :accessibility_id, 'Buttons' }
end
assert_equal 'Buttons', result.name
end
def test_viewport_screenshot
file = @@driver.save_viewport_screenshot AppiumLibCoreTest.path_of('ios_viewport_screenshot_test.png')
assert File.exist?(file.path)
File.delete file.path
assert !File.exist?(file.path)
end
# Requires --relaxed-security server flag
def test_start_performance_record_and_stop
file_path = AppiumLibCoreTest.path_of('test_start_performance_record_and_stop.zip')
File.delete file_path if File.exist? file_path
@@driver.start_performance_record(timeout: 300_000, profile_name: 'Time Profiler')
@@driver.find_element(:accessibility_id, 'Buttons').click
sleep 2
@@driver.back
sleep 1
# Get .zip file
file = @@driver.get_performance_record(
save_file_path: AppiumLibCoreTest.path_of('test_start_performance_record_and_stop'),
profile_name: 'Time Profiler'
)
assert File.exist?(file.path)
end
def test_clipbord
input = 'happy testing'
@@driver.set_clipboard(content: input)
assert_equal input, @@driver.get_clipboard
end
def test_battery_info
result = @@driver.battery_info
assert !result[:state].nil?
assert !result[:level].nil?
end
end
end
end
# rubocop:enable Style/ClassVars
| 32.400621
| 121
| 0.633567
|
b8d704ae241c27d31d7e47fc4f4a4804590c8f04
| 1,186
|
h
|
C
|
vendor/chromium/base/trace_event/memory_infra_background_whitelist.h
|
thorium-cfx/fivem
|
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
|
[
"MIT"
] | 5,411
|
2017-04-14T08:57:56.000Z
|
2022-03-30T19:35:15.000Z
|
src/base/trace_event/memory_infra_background_whitelist.h
|
18901233704/libquic
|
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
|
[
"BSD-3-Clause"
] | 802
|
2017-04-21T14:18:36.000Z
|
2022-03-31T21:20:48.000Z
|
src/base/trace_event/memory_infra_background_whitelist.h
|
18901233704/libquic
|
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
|
[
"BSD-3-Clause"
] | 2,011
|
2017-04-14T09:44:15.000Z
|
2022-03-31T15:40:39.000Z
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_TRACE_EVENT_MEMORY_INFRA_BACKGROUND_WHITELIST_H_
#define BASE_TRACE_EVENT_MEMORY_INFRA_BACKGROUND_WHITELIST_H_
// This file contains the whitelists for background mode to limit the tracing
// overhead and remove sensitive information from traces.
#include <string>
#include "base/base_export.h"
namespace base {
namespace trace_event {
// Checks if the given |mdp_name| is in the whitelist.
bool BASE_EXPORT IsMemoryDumpProviderWhitelisted(const char* mdp_name);
// Checks if the given |name| matches any of the whitelisted patterns.
bool BASE_EXPORT IsMemoryAllocatorDumpNameWhitelisted(const std::string& name);
// The whitelist is replaced with the given list for tests. The last element of
// the list must be nullptr.
void BASE_EXPORT SetDumpProviderWhitelistForTesting(const char* const* list);
void BASE_EXPORT
SetAllocatorDumpNameWhitelistForTesting(const char* const* list);
} // namespace trace_event
} // namespace base
#endif // BASE_TRACE_EVENT_MEMORY_INFRA_BACKGROUND_WHITELIST_H_
| 34.882353
| 79
| 0.809444
|
4d9d24764054cde10fdd4419e4bce56718925d20
| 4,192
|
cs
|
C#
|
projectCS/physical components/LockerComponents.cs
|
titimar16/KitBox
|
6c102b593fb3f12297925c2cda627b137e26ebc2
|
[
"MIT"
] | 5
|
2020-03-01T16:25:31.000Z
|
2020-04-09T19:41:33.000Z
|
projectCS/physical components/LockerComponents.cs
|
titimar16/KitBox
|
6c102b593fb3f12297925c2cda627b137e26ebc2
|
[
"MIT"
] | 1
|
2020-03-02T10:49:06.000Z
|
2020-03-02T10:49:06.000Z
|
projectCS/physical components/LockerComponents.cs
|
titimar16/KitBox
|
6c102b593fb3f12297925c2cda627b137e26ebc2
|
[
"MIT"
] | 4
|
2020-02-06T12:32:18.000Z
|
2020-03-18T15:59:35.000Z
|
using projectCS.Tools_class;
namespace projectCS
{
public class CrossBar : CatalogueComponents
{
private CrossBarType _type;
public CrossBarType type
{
get => _type;
set => _type = value;
}
public CrossBar() : this(0, "null", "0000", new ComponentSize(0, 0, 0), false, CrossBarType.LR)
{
}
public CrossBar(double price,
string reference,
string code,
ComponentSize size,
bool inStock,
CrossBarType type) : base(price, reference, code, size, inStock)
{
this._type = type;
}
}
public class Panels : CatalogueComponents
{
private ComponentColor _color;
public ComponentColor color
{
get => _color;
set
{
if (value == ComponentColor.glass)
{
ErrorWindow window = new ErrorWindow(ErrorMessages.invalidColorMsg, ErrorMessages.invalidColorTitle);
window.displayWindow();
}
else
_color = value;
}
}
private PanelsType _type;
public PanelsType type
{
get => _type;
set => _type = value;
}
public Panels() : this(0, "null", "0000", new ComponentSize(0, 0, 0), false, ComponentColor.black, PanelsType.LR)
{
}
public Panels(double price,
string reference,
string code,
ComponentSize size,
bool inStock,
ComponentColor color,
PanelsType type) : base(price, reference, code, size, inStock)
{
this.color = color;
this._type = type;
}
}
public class Door : CatalogueComponents
{
private ComponentColor _color;
public ComponentColor color
{
get => _color;
set => _color = value;
}
private bool _cup;
public bool cup
{
get => _cup;
set => _cup = value;
}
public override double price
{
get
{
double tempPrice = _price;
if (_cup)
tempPrice += 0.005;
return tempPrice;
}
}
public Door() : this(0, "null", "0000", new ComponentSize(0, 0, 0), false, ComponentColor.black)
{
}
public Door(double price,
string reference,
string code,
ComponentSize size,
bool inStock,
ComponentColor color) : this(price, reference, code, size, inStock, color, false)
{
}
public Door(double price,
string reference,
string code,
ComponentSize size,
bool inStock,
ComponentColor color,
bool cup) : base(price, reference, code, size, inStock)
{
this.color = color;
this._cup = cup;
}
}
public class Cleat : CatalogueComponents
{
public Cleat() : this(0, "null", "0000", new ComponentSize(0, 0, 0), false)
{
}
public Cleat(double price,
string reference,
string code,
ComponentSize size,
bool inStock) : base(price, reference, code, size, inStock)
{
}
}
/// <summary>
/// regroup all color available in catalog
/// </summary>
public enum ComponentColor
{
white,
brown,
galvanised,
black,
glass
}
public enum PanelsType
{
HL,
B,
LR
}
public enum CrossBarType
{
F,
B,
LR
}
}
| 25.406061
| 121
| 0.442748
|
0aa0c8eeaf49aff2ab21e11ba36aa0675c7711bb
| 2,630
|
cs
|
C#
|
SanjeeviCLI/Program.cs
|
VaduganathanP/Sanjeevi
|
386c3a171b4edd79ee22e35877f3197d2cd76ad9
|
[
"MIT"
] | null | null | null |
SanjeeviCLI/Program.cs
|
VaduganathanP/Sanjeevi
|
386c3a171b4edd79ee22e35877f3197d2cd76ad9
|
[
"MIT"
] | null | null | null |
SanjeeviCLI/Program.cs
|
VaduganathanP/Sanjeevi
|
386c3a171b4edd79ee22e35877f3197d2cd76ad9
|
[
"MIT"
] | null | null | null |
using Sanjeevi;
using System;
using System.Collections.Generic;
namespace SanjeeviCLI
{
class Program
{
static void Main()
{
const string minerAddress = "miner1";
const string user1Address = "A";
const string user2Address = "B";
BlockChain blockChain = new BlockChain(proofOfWorkDifficulty: 2, miningReward: 10);
blockChain.CreateTransaction(new Transaction(user1Address, user2Address, 200));
blockChain.CreateTransaction(new Transaction(user2Address, user1Address, 10));
Console.WriteLine("Is valid: {0}", blockChain.IsValidChain());
Console.WriteLine();
Console.WriteLine("--------- Start mining ---------");
blockChain.MineBlock(minerAddress);
Console.WriteLine("BALANCE of the miner: {0}", blockChain.GetBalance(minerAddress));
blockChain.CreateTransaction(new Transaction(user1Address, user2Address, 5));
Console.WriteLine();
Console.WriteLine("--------- Start mining ---------");
blockChain.MineBlock(minerAddress);
Console.WriteLine("BALANCE of the miner: {0}", blockChain.GetBalance(minerAddress));
Console.WriteLine();
PrintChain(blockChain);
Console.WriteLine();
Console.WriteLine("Hacking the blockchain...");
blockChain.Chain[1].Transactions = new List<Transaction> { new Transaction(user1Address, minerAddress, 150) };
Console.WriteLine("Is valid: {0}", blockChain.IsValidChain());
Console.ReadKey();
}
private static void PrintChain(BlockChain blockChain)
{
Console.WriteLine("----------------- Start Blockchain -----------------");
foreach (Block block in blockChain.Chain)
{
Console.WriteLine();
Console.WriteLine("------ Start Block ------");
Console.WriteLine("Hash: {0}", block.Hash);
Console.WriteLine("Previous Hash: {0}", block.PreviousHash);
Console.WriteLine("--- Start Transactions ---");
foreach (Transaction transaction in block.Transactions)
{
Console.WriteLine("From: {0} To {1} Amount {2}", transaction.From, transaction.To, transaction.Amount);
}
Console.WriteLine("--- End Transactions ---");
Console.WriteLine("------ End Block ------");
}
Console.WriteLine("----------------- End Blockchain -----------------");
}
}
}
| 46.964286
| 123
| 0.561977
|
c672dd728f416fa4a40e6abe079d13fba6e2c6ee
| 5,105
|
py
|
Python
|
exordium/migrations/0001_initial.py
|
apocalyptech/exordium
|
a582380e34d247dd07a9fd5161febe8087760054
|
[
"MIT",
"BSD-3-Clause"
] | 3
|
2017-04-22T11:09:12.000Z
|
2020-01-28T12:14:27.000Z
|
exordium/migrations/0001_initial.py
|
apocalyptech/exordium
|
a582380e34d247dd07a9fd5161febe8087760054
|
[
"MIT",
"BSD-3-Clause"
] | 5
|
2021-03-04T20:52:32.000Z
|
2022-03-15T19:27:35.000Z
|
exordium/migrations/0001_initial.py
|
apocalyptech/exordium
|
a582380e34d247dd07a9fd5161febe8087760054
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2017-11-11T08:06:51.000Z
|
2017-11-11T08:06:51.000Z
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-30 18:47
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Album',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('normname', models.CharField(max_length=255)),
('year', models.IntegerField(default=0)),
('miscellaneous', models.BooleanField(default=False)),
('live', models.BooleanField(default=False)),
('time_added', models.DateTimeField(default=django.utils.timezone.now)),
('art_filename', models.CharField(default=None, max_length=4096, null=True)),
('art_mtime', models.IntegerField(default=0, null=True)),
('art_ext', models.CharField(default=None, max_length=4, null=True)),
('art_mime', models.CharField(default=None, max_length=64, null=True)),
],
),
migrations.CreateModel(
name='AlbumArt',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('size', models.CharField(choices=[('album', 'Album Listing'), ('list', 'Inside Lists')], max_length=5)),
('resolution', models.PositiveSmallIntegerField(default=0)),
('from_mtime', models.IntegerField(default=0)),
('image', models.BinaryField()),
('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exordium.Album')),
],
),
migrations.CreateModel(
name='Artist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
('normname', models.CharField(max_length=255, unique=True)),
('prefix', models.CharField(max_length=32)),
('various', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='Song',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('filename', models.CharField(max_length=4096)),
('title', models.CharField(max_length=255)),
('normtitle', models.CharField(max_length=255)),
('year', models.IntegerField()),
('tracknum', models.SmallIntegerField(verbose_name='#')),
('raw_artist', models.CharField(max_length=255)),
('raw_group', models.CharField(default='', max_length=255)),
('raw_composer', models.CharField(default='', max_length=255)),
('raw_conductor', models.CharField(default='', max_length=255)),
('filetype', models.CharField(choices=[('mp3', 'mp3'), ('ogg', 'ogg')], max_length=3)),
('bitrate', models.IntegerField()),
('mode', models.CharField(choices=[('ABR', 'ABR'), ('CBR', 'CBR'), ('VBR', 'VBR')], max_length=3)),
('size', models.IntegerField()),
('length', models.IntegerField()),
('time_added', models.DateTimeField(default=django.utils.timezone.now)),
('time_updated', models.IntegerField(default=0)),
('sha256sum', models.CharField(max_length=64)),
('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exordium.Album')),
('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exordium.Artist')),
('composer', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='composer_set', to='exordium.Artist')),
('conductor', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='conductor_set', to='exordium.Artist')),
('group', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='group_set', to='exordium.Artist')),
],
),
migrations.AddField(
model_name='album',
name='artist',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='exordium.Artist'),
),
migrations.AlterUniqueTogether(
name='albumart',
unique_together=set([('album', 'size')]),
),
migrations.AlterUniqueTogether(
name='album',
unique_together=set([('artist', 'name')]),
),
]
| 52.628866
| 183
| 0.584133
|
46eb35163042466342f8d24b852fdc7e180d305c
| 651
|
py
|
Python
|
args_parser/hyeonhoseo.py
|
SanghunOh/share_5GUAV_2021
|
bdcc272da4bce5e3e56ff7842bff7fb0c802f083
|
[
"Apache-2.0"
] | null | null | null |
args_parser/hyeonhoseo.py
|
SanghunOh/share_5GUAV_2021
|
bdcc272da4bce5e3e56ff7842bff7fb0c802f083
|
[
"Apache-2.0"
] | null | null | null |
args_parser/hyeonhoseo.py
|
SanghunOh/share_5GUAV_2021
|
bdcc272da4bce5e3e56ff7842bff7fb0c802f083
|
[
"Apache-2.0"
] | 3
|
2021-11-30T07:49:08.000Z
|
2021-12-01T08:57:48.000Z
|
import argparse
from itertools import permutations
args = argparse.ArgumentParser()
args.add_argument('-first', '--xVal', required=True)
args.add_argument('-second', '--yVal', required=True)
args.add_argument('-third', '--zVal', required=True)
argvar = vars(args.parse_args())
def mul_div(argvar):
x,y,z = argvar.values()
arg_list = [x,y,z]
combilist = list(permutations(arg_list, 2))
for x,y in combilist:
mul = x*y
try:
div = x/y
return print(f'{x}x{y}={mul} , {x}/{y}={div}')
except:
return print(f'{x}/{y}={div} : ZeroDivisionError')
pass
mul_div(argvar)
| 23.25
| 62
| 0.602151
|
a3d840d9017e6deb733b55025d6be88264b1344e
| 1,813
|
java
|
Java
|
app/src/main/java/com/xeniac/harrypotterstorybooks/database/chaptersDataBase/ChaptersTable.java
|
XeniacDev/HarryPotterStoryBooks
|
dfa6ab759554c9a23f6c8942c819883d870964de
|
[
"MIT"
] | 1
|
2021-06-18T14:30:36.000Z
|
2021-06-18T14:30:36.000Z
|
app/src/main/java/com/xeniac/harrypotterstorybooks/database/chaptersDataBase/ChaptersTable.java
|
XeniacDev/HarryPotterStoryBooks
|
dfa6ab759554c9a23f6c8942c819883d870964de
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/xeniac/harrypotterstorybooks/database/chaptersDataBase/ChaptersTable.java
|
XeniacDev/HarryPotterStoryBooks
|
dfa6ab759554c9a23f6c8942c819883d870964de
|
[
"MIT"
] | null | null | null |
package com.xeniac.harrypotterstorybooks.database.chaptersDataBase;
import com.xeniac.harrypotterstorybooks.database.booksDataBase.BooksTable;
public class ChaptersTable {
static final String TABLE_CHAPTERS = "chapters";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NUMBER = "number";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_PAGES = "pages";
public static final String COLUMN_TOTAL_SCROLL = "totalScroll";
public static final String COLUMN_READ_SCROLL = "readScroll";
public static final String COLUMN_BOOK_ID = "bookId";
public static final String COLUMN_COVER = "cover";
public static final String COLUMN_FAVORITE = "favorite";
public static final String COLUMN_RELEASED = "released";
static final String[] ALL_IDS = {COLUMN_ID};
static final String[] ALL_COLUMNS = {COLUMN_ID, COLUMN_NUMBER, COLUMN_TITLE,
COLUMN_PAGES, COLUMN_TOTAL_SCROLL, COLUMN_READ_SCROLL, COLUMN_BOOK_ID,
COLUMN_COVER, COLUMN_FAVORITE, COLUMN_RELEASED};
public static final String SQL_CREATE =
"CREATE TABLE " + TABLE_CHAPTERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NUMBER + " INTEGER," +
COLUMN_TITLE + " INTEGER," +
COLUMN_PAGES + " INTEGER," +
COLUMN_TOTAL_SCROLL + " INTEGER," +
COLUMN_READ_SCROLL + " INTEGER," +
COLUMN_BOOK_ID + " INTEGER," +
COLUMN_COVER + " TEXT," +
COLUMN_FAVORITE + " INTEGER," +
COLUMN_RELEASED + " INTEGER," +
"FOREIGN KEY (" + COLUMN_BOOK_ID + ") REFERENCES books(" + BooksTable.COLUMN_ID + "));";
}
| 50.361111
| 108
| 0.63872
|
cfdcab3fd7cd96b56ce2fb0fe52e89d7f8aeb84b
| 1,325
|
sh
|
Shell
|
tup/test/t3064-group-circular6.sh
|
dat-boi-lux/Langevin-MCMC-Modern
|
bcb0dbf9c93d024484709362066bd423e81067b5
|
[
"MIT"
] | 73
|
2020-05-07T04:23:33.000Z
|
2022-01-21T05:57:18.000Z
|
tup/test/t3064-group-circular6.sh
|
dat-boi-lux/Langevin-MCMC-Modern
|
bcb0dbf9c93d024484709362066bd423e81067b5
|
[
"MIT"
] | 2
|
2020-05-15T15:21:36.000Z
|
2021-06-23T18:48:05.000Z
|
tup/test/t3064-group-circular6.sh
|
dat-boi-lux/Langevin-MCMC-Modern
|
bcb0dbf9c93d024484709362066bd423e81067b5
|
[
"MIT"
] | 11
|
2020-05-13T12:18:16.000Z
|
2022-01-10T23:30:55.000Z
|
#! /bin/sh -e
# tup - A file-based build system
#
# Copyright (C) 2013-2018 Mike Shal <marfey@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Make sure group links are cleaned up when necessary. This is tricky since
# there is no guaranteed order between which of sub1 and sub2 will be parsed
# first, so we have to defer circular dependency checking among groups until
# after all files are parsed and old commands are deleted.
. ./tup.sh
tmkdir sub1
tmkdir sub2
cat > sub1/Tupfile << HERE
: <foo> |> echo blah > %o |> output.txt | <bar>
HERE
update
cat > sub1/Tupfile << HERE
HERE
cat > sub2/Tupfile << HERE
: <bar> |> echo blah > %o |> output.txt | <foo>
HERE
tup touch sub1/Tupfile sub2/Tupfile
update
eotup
| 31.547619
| 76
| 0.740377
|
0aa4659e272e35832b839fa57a10ffea139988f9
| 171
|
cs
|
C#
|
FINT.Model.Resource.Arkiv/Kodeverk/DokumentTypeResources.cs
|
FINTmodels/FINT.Information.Model
|
1d9ebc79a8377f432c6121d76a9fae7a8e0d7cdd
|
[
"MIT"
] | null | null | null |
FINT.Model.Resource.Arkiv/Kodeverk/DokumentTypeResources.cs
|
FINTmodels/FINT.Information.Model
|
1d9ebc79a8377f432c6121d76a9fae7a8e0d7cdd
|
[
"MIT"
] | 2
|
2020-10-07T10:47:39.000Z
|
2020-10-07T10:56:09.000Z
|
FINT.Model.Resource.Arkiv/Kodeverk/DokumentTypeResources.cs
|
FINTmodels/FINT.Information.Model
|
1d9ebc79a8377f432c6121d76a9fae7a8e0d7cdd
|
[
"MIT"
] | null | null | null |
using FINT.Model.Resource;
namespace FINT.Model.Arkiv.Kodeverk
{
public class DokumentTypeResources : AbstractCollectionResources<DokumentTypeResource>
{
}
}
| 19
| 90
| 0.77193
|