hexsha
stringlengths 40
40
| size
int64 140
1.03M
| ext
stringclasses 94
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
663
| max_stars_repo_name
stringlengths 4
120
| 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
663
| max_issues_repo_name
stringlengths 4
120
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
116k
⌀ | 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
663
| 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 140
1.03M
| avg_line_length
float64 2.32
23.1k
| max_line_length
int64 11
938k
| alphanum_fraction
float64 0.01
1
| score
float32 3
4.25
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0c7c8dce6c70d8ff2dee0d4d341ee24189b8fc0
| 1,339 |
rs
|
Rust
|
benchmarking/benches/my_benchmark.rs
|
RenWild/FabChess
|
f86e9e23663e923144d04da962bc8edbc43e5e76
|
[
"BSD-3-Clause"
] | 29 |
2019-08-06T15:08:28.000Z
|
2022-01-29T19:42:40.000Z
|
benchmarking/benches/my_benchmark.rs
|
RenWild/FabChess
|
f86e9e23663e923144d04da962bc8edbc43e5e76
|
[
"BSD-3-Clause"
] | 11 |
2019-07-26T12:16:03.000Z
|
2020-08-04T09:18:19.000Z
|
benchmarking/benches/my_benchmark.rs
|
RenWild/FabChess
|
f86e9e23663e923144d04da962bc8edbc43e5e76
|
[
"BSD-3-Clause"
] | 4 |
2020-03-28T17:38:37.000Z
|
2020-09-26T19:04:50.000Z
|
use benchmarking::*;
use core_sdk::evaluation::eval_game_state;
use core_sdk::move_generation::makemove::make_move;
use core_sdk::move_generation::movegen::{self, MoveList};
use criterion::{criterion_group, criterion_main, Criterion};
pub fn evaluation_bench(c: &mut Criterion) {
let states = load_benchmarking_positions();
c.bench_function("evaluation", |b| {
b.iter(|| {
let mut sum = 0;
for i in 0..BENCHMARKING_POSITIONS_AMOUNT {
sum += eval_game_state(&states[i]).final_eval as isize;
}
sum
})
});
}
pub fn generate_moves_bench(c: &mut Criterion) {
let states = load_benchmarking_positions();
let mut movelist = MoveList::default();
c.bench_function("movegen", |b| {
b.iter(|| {
let mut sum = 0;
for i in 0..BENCHMARKING_POSITIONS_AMOUNT {
movegen::generate_moves(&states[i], false, &mut movelist);
sum += movelist.move_list.len();
for mv in movelist.move_list.iter() {
let g = make_move(&states[i], mv.0);
sum += (g.get_hash() & 0xFF) as usize;
}
}
sum
})
});
}
criterion_group!(benches, evaluation_bench, generate_moves_bench);
criterion_main!(benches);
| 33.475 | 74 | 0.583271 | 3 |
53ae3d723c75d0781ac84df992e37a7cc926aeb3
| 3,186 |
java
|
Java
|
DataMining/src/salp/Individual.java
|
HadiAwad/TestCasePrioritization
|
b00fe953c57087c896f24c15531685e0063ea96d
|
[
"Apache-2.0"
] | null | null | null |
DataMining/src/salp/Individual.java
|
HadiAwad/TestCasePrioritization
|
b00fe953c57087c896f24c15531685e0063ea96d
|
[
"Apache-2.0"
] | null | null | null |
DataMining/src/salp/Individual.java
|
HadiAwad/TestCasePrioritization
|
b00fe953c57087c896f24c15531685e0063ea96d
|
[
"Apache-2.0"
] | null | null | null |
package salp;
import Catalano.Core.IntRange;
import utils.IObjectiveFunction;
import java.util.*;
/**
* Represents individual in the population.
* @author Diego Catalano
*/
public class Individual implements Comparable<Individual>, Cloneable {
private int[] location;
private double fitness;
public static int generateRandom(int min, int max){
return new Random().nextInt(max-min+1) +min;
}
public static int[] UniformRandom(List<IntRange> ranges){
Random rand = new Random();
int[] r = new int[ranges.size()];
Set<Integer> uniqueNumbers = new HashSet<>();
for (int i = 0; i < r.length; i++) {
IntRange range = ranges.get(i);
int generatedNumber = -1;
do{
generatedNumber = generateRandom(range.getMin(),range.getMax());
}while (uniqueNumbers.contains(generatedNumber));
r[i] = generatedNumber;
uniqueNumbers.add(generatedNumber);
}
return r;
}
public static List<Individual> CreatePopulation(int populationSize, List<IntRange> boundConstraints, IObjectiveFunction function){
List<Individual> population = new ArrayList<>(populationSize);
for (int i = 0; i < populationSize; i++) {
int[] location = UniformRandom(boundConstraints);
double fitness = function.Compute(location);
population.add(new Individual(location, fitness));
}
return population;
}
/**
* Get location in the space.
* @return Location.
*/
public int[] getLocation() {
return location;
}
/**
* Get location in the space.
* @param index Index.
* @return Value.
*/
public double getLocation(int index){
return location[index];
}
/**
* Set location in the space.
* @param location Location.
*/
public void setLocation(int[] location) {
this.location = location;
}
/**
* Set location in the space.
* @param index Index.
* @param location Location.
*/
public void setLocation(int index, int location){
this.location[index] = location;
}
/**
* Get fitness.
* @return Fitness.
*/
public double getFitness() {
return fitness;
}
/**
* Set fitness.
* @param fitness Fitness.
*/
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Initialize a new instance of the Individual class.
* @param location Location.
*/
public Individual(int[] location){
this(location, Double.NaN);
}
/**
* Initialize a new instance of the Individual class.
* @param location Location.
* @param fitness Fitness.
*/
public Individual(int[] location, double fitness) {
this.location = location;
this.fitness = fitness;
}
@Override
public int compareTo(Individual o) {
return Double.compare(fitness, o.getFitness());
}
public Individual getClone(){
return new Individual(Arrays.copyOf(location, location.length), fitness);
}
}
| 24.697674 | 134 | 0.596359 | 3.234375 |
e75593e53b4c6077f8214bf85889bd132d94752b
| 1,336 |
js
|
JavaScript
|
server.js
|
devtsp/crud-clubs-API
|
fe5417eadfcc9f78a6e0e496b8788778f9f90222
|
[
"MIT"
] | null | null | null |
server.js
|
devtsp/crud-clubs-API
|
fe5417eadfcc9f78a6e0e496b8788778f9f90222
|
[
"MIT"
] | null | null | null |
server.js
|
devtsp/crud-clubs-API
|
fe5417eadfcc9f78a6e0e496b8788778f9f90222
|
[
"MIT"
] | null | null | null |
const {
createClub,
deleteClub,
getAllClubs,
getClub,
editClub,
} = require('./club_controller.js');
const fs = require('fs');
const cors = require('cors');
const express = require('express');
const PORT = 8080;
const app = express();
const multer = require('multer');
const upload = multer({ dest: 'public/uploads/img' });
app.use(cors());
app.use(express.static('public'));
app.get('/index', (req, res) => {
const clubs = getAllClubs();
const namesAndIds = [...clubs].map(club => {
return {
id: club.id,
name: club.name,
crest: club.crest,
colors: club.colors,
};
});
res.status(200).json(namesAndIds);
});
app.post('/', upload.single('crest'), (req, res) => {
const posted = createClub(req);
res.status(200).json(posted);
});
app.get('/:id', (req, res) => {
const gotten = getClub(req);
res.status(200).json(gotten);
});
app.delete('/:id', (req, res) => {
const deleted = deleteClub(req);
res.status(200).json(deleted);
});
app.post('/edit/:id', upload.single('crest'), (req, res) => {
console.log(req.method, req.url);
const edited = editClub(req);
console.log(edited);
res.json(edited);
});
app.get('*', (req, res) => {
res.status(404).json({ message: 'The resource does not exists.' });
});
app.listen(process.env.PORT || PORT);
console.log(`Listening on http://localhost:${PORT}`);
| 21.206349 | 68 | 0.631737 | 3 |
5c3879984695b3dc1d069ad6c00021e30de44eee
| 1,344 |
h
|
C
|
Source/Utility/utility.h
|
nanhasa/Blocker
|
e34ce35ea02468a0bf6bb65900c9209b2fe54df0
|
[
"MIT"
] | null | null | null |
Source/Utility/utility.h
|
nanhasa/Blocker
|
e34ce35ea02468a0bf6bb65900c9209b2fe54df0
|
[
"MIT"
] | null | null | null |
Source/Utility/utility.h
|
nanhasa/Blocker
|
e34ce35ea02468a0bf6bb65900c9209b2fe54df0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <sstream>
#include <string>
namespace utility {
/**
* \brief timeSinceEpoch
* \return
*/
long timeSinceEpoch();
/**
* \brief Used to get timestamp in milliseconds, thread safe
* \return Current time in milliseconds
*/
int timestampMs();
/**
* \brief deltaTimeSec
* \param timestamp
* \return Elapsed seconds since the parameter value
*/
float deltaTimeSec(int timestamp);
/**
* \brief deltaTimeMs
* \param timestamp
* \return Elapsed milliseconds since the parameter value
*/
int deltaTimeMs(int timestamp);
// Utility function to return hex format of a number
template<typename T>
std::string toHex(T&& num)
{
std::stringstream ss;
ss << "0x" << std::hex << std::forward<T>(num);
return ss.str();
}
// Utility function to return dec format of a number
template<typename T>
std::string toDec(T&& num)
{
std::stringstream ss;
ss << std::dec << std::forward<T>(num);
return ss.str();
}
// Utility function to turn number to string
// Returns empty string if parameter is not integral or floating point
template<typename T>
std::string toStr(T num)
{
#pragma warning(suppress: 4127)
if (!std::is_integral<T>::value && !std::is_floating_point<T>::value)
return std::string();
return std::to_string(std::forward<T>(num));
}
} // namespace utility
| 21.333333 | 71 | 0.677083 | 3.171875 |
01068bb8b711c2abe138200e335c20cad0063c7f
| 2,496 |
lua
|
Lua
|
prods/wtf-atabimp/heightmap.lua
|
GitoriousLispBackup/praxis
|
a5c1a806c00c6589a3603a29cc9773a704821ebd
|
[
"MIT"
] | 103 |
2015-01-08T14:04:30.000Z
|
2022-02-04T02:57:14.000Z
|
prods/wtf-atabimp/heightmap.lua
|
GitoriousLispBackup/praxis
|
a5c1a806c00c6589a3603a29cc9773a704821ebd
|
[
"MIT"
] | 6 |
2015-03-01T13:42:32.000Z
|
2020-06-28T18:39:41.000Z
|
prods/wtf-atabimp/heightmap.lua
|
GitoriousLispBackup/praxis
|
a5c1a806c00c6589a3603a29cc9773a704821ebd
|
[
"MIT"
] | 10 |
2015-03-03T00:09:55.000Z
|
2021-08-31T19:10:01.000Z
|
-- Name: heightmap.lua
--heit = {}
t = 0
t_spd = 0.02
heightmap = {}
cellsize = 10
camCellPosI = 5
camCellPosJ = 5
camAngle = 0
camAngleSpeed = 4
camOrbitCenter = { x = 5 * cellsize, y = 5 * cellsize }
camOrbitRadius = 50
camOrbitHeight = 10
-- make a guy that runs and jumps over these platforms
function heit.init()
camAngle = 0
camAngleSpeed = 4
camOrbitCenter = { x = 5 * cellsize, y = 5 * cellsize }
camOrbitRadius = 50
camOrbitHeight = 10
end
function heit.update()
t = t + t_spd
for i=1,10 do
for j=1,10 do
heightmap[i][j] = 20*math.sin(t * i * 0.1) + 20*math.sin(t * j * 0.1)
end
end
camAngle = camAngle + camAngleSpeed * math.pi / 180
camPos = { x = camOrbitCenter.x + camOrbitRadius * math.cos(camAngle), y = camOrbitCenter.y + camOrbitRadius * math.sin(camAngle) }
ahead = { x = camPos.x + -10 * math.sin(camAngle), y = camPos.y + 10 * math.cos(camAngle) }
camOrbitRadius = math.sin(camAngle * 0.25) * 15 + 20
setCamPos(camPos.x, camOrbitHeight, camPos.y)
lookAt(ahead.x, camOrbitHeight, ahead.y)
--setCamPos(getcellposition(camCellPosI,camCellPosJ))
--setCamPos(i * cellsize, heightmap[i][j]+10, j * cellsize)
-- shiftcellcam()
end
function heit.render()
beginTriGL()
renderheightmap()
endGL()
end
function createheightmap()
heightmap = {}
for i=1,10 do
heightmap[i] = {}
for j=1,10 do
heightmap[i][j] = 20
end
end
end
function rendercell(i,j)
colorGL(20 * i, 20 * j, 0, 255)
vectorGL(i * cellsize, heightmap[i][j], j * cellsize)
vectorGL((i+1) * cellsize, heightmap[i][j], j * cellsize)
vectorGL(i * cellsize, heightmap[i][j], (j+1) * cellsize)
vectorGL((i+1) * cellsize, heightmap[i][j], j * cellsize)
vectorGL((i+1) * cellsize, heightmap[i][j], (j+1) * cellsize)
vectorGL(i * cellsize, heightmap[i][j], (j+1) * cellsize)
end
function renderheightmap()
for i = 1,10 do
for j = 1,10 do
rendercell(i,j)
end
end
end
function getcellposition(i,j)
return i * cellsize + (cellsize * 0.5), heightmap[i][j]+10, j * cellsize + (cellsize * 0.5)
end
function shiftcellcam()
camCellPosI = camCellPosI + 1
if camCellPosI > 10 then
camCellPosI = 1
camCellPosJ = camCellPosJ + 1
if camCellPosJ > 10 then
camCellPosJ = 1
end
end
end
createheightmap()
| 23.327103 | 135 | 0.598157 | 3.203125 |
5fa8591bcd4e78196ec292c82b37247aa09e7ce1
| 2,536 |
c
|
C
|
Plugins/Nektar/Veclib/math/xvrand.c
|
mathstuf/ParaView
|
e867e280545ada10c4ed137f6a966d9d2f3db4cb
|
[
"Apache-2.0"
] | 1 |
2020-05-21T20:20:59.000Z
|
2020-05-21T20:20:59.000Z
|
Plugins/Nektar/Veclib/math/xvrand.c
|
mathstuf/ParaView
|
e867e280545ada10c4ed137f6a966d9d2f3db4cb
|
[
"Apache-2.0"
] | null | null | null |
Plugins/Nektar/Veclib/math/xvrand.c
|
mathstuf/ParaView
|
e867e280545ada10c4ed137f6a966d9d2f3db4cb
|
[
"Apache-2.0"
] | 5 |
2016-04-14T13:42:37.000Z
|
2021-05-22T04:59:42.000Z
|
/*
* Random number generation
*/
#include <stdio.h>
#include <math.h>
#include <assert.h>
#ifndef NULL
#define NULL (0L)
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static int iseed;
/* Prototypes */
void InitializeRandom (int);
double Random (double, double);
double GetGaussian (double);
double GetLorentz (double);
void Get2Gaussians (double*, double*, double);
double ran1 (int*);
/* ---------------------------------------------------------------------- */
void dvrand (int n, double *x, const int incx)
{
while (n--) {
*x = Random (0.,1.);
x += incx;
}
return;
}
double drand(void) { return Random (0.,1.); }
/* ---------------------------------------------------------------------- */
double Random(double low, double high)
{
double d_r = ran1(&iseed);
d_r = d_r * (high-low) + low;
assert(d_r>=low );
assert(d_r<=high);
return d_r;
}
double GetGaussian(double sigma)
{
double theta = Random(0.0,2*M_PI);
double x = Random(0.0,1.0);
double r = sqrt( -2.0*sigma*sigma*log(x) );
return r * cos(theta);
}
double GetLorentz(double width)
{
double x = Random(-M_PI/2,M_PI/2);
return width * tan(x);
}
void Get2Gaussians(double *g1, double *g2, double sigma)
{
double theta = Random(0.0,2*M_PI);
double x = Random(0.0,1.0);
double r = sqrt( -2.0*sigma*sigma*log(x));
assert(g1!=NULL);
assert(g2!=NULL);
*g1 = r*cos(theta);
*g2 = r*sin(theta);
}
void InitializeRandom(int flag)
{
if ( flag < 0 )
iseed = time(NULL);
else
iseed = flag;
(void) ran1(&iseed);
}
#define M1 259200
#define IA1 7141
#define IC1 54773
#define RM1 (1.0/M1)
#define M2 134456
#define IA2 8121
#define IC2 28411
#define RM2 (1.0/M2)
#define M3 243000
#define IA3 4561
#define IC3 51349
double ran1(int *idum)
{
static long ix1,ix2,ix3;
static double r[98];
double temp;
static int iff=0;
int j;
if (*idum < 0 || iff == 0) {
iff=1;
ix1=(IC1-(*idum)) % M1;
ix1=(IA1*ix1+IC1) % M1;
ix2=ix1 % M2;
ix1=(IA1*ix1+IC1) % M1;
ix3=ix1 % M3;
for (j=1;j<=97;j++) {
ix1=(IA1*ix1+IC1) % M1;
ix2=(IA2*ix2+IC2) % M2;
r[j]=(ix1+ix2*RM2)*RM1;
}
*idum=1;
}
ix1=(IA1*ix1+IC1) % M1;
ix2=(IA2*ix2+IC2) % M2;
ix3=(IA3*ix3+IC3) % M3;
j =1 + ((97*ix3)/M3);
temp=r[j];
r[j]=(ix1+ix2*RM2)*RM1;
return temp;
}
#undef M1
#undef IA1
#undef IC1
#undef RM1
#undef M2
#undef IA2
#undef IC2
#undef RM2
#undef M3
#undef IA3
#undef IC3
| 17.489655 | 76 | 0.556782 | 3.359375 |
38b03905216996ea22ad40561dc1b68493b52a31
| 2,009 |
c
|
C
|
atividades/at02/mini-calculadora.c
|
studTon/inf029-evertondasilva
|
901b90fb9c52b9659a05bd399aa219cf3869b333
|
[
"MIT"
] | 1 |
2021-02-24T23:54:06.000Z
|
2021-02-24T23:54:06.000Z
|
atividades/at02/mini-calculadora.c
|
studTon/INF029-EvertondaSilva
|
901b90fb9c52b9659a05bd399aa219cf3869b333
|
[
"MIT"
] | 16 |
2021-04-15T14:05:17.000Z
|
2021-07-02T19:17:35.000Z
|
atividades/at02/mini-calculadora.c
|
studTon/inf029-evertondasilva
|
901b90fb9c52b9659a05bd399aa219cf3869b333
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
//Funções para as operações da calculadora
float somar(float numA, float numB)
{
return numA + numB;
}
float subtrair(float numA, float numB)
{
return numA - numB;
}
float multiplicar(float numA, float numB)
{
return numA * numB;
}
float dividir(float numA, float numB)
{
return numA / numB;
}
//Corpo principal do programa
int main()
{
int escolha = 1;
float numeroA, numeroB, resultado;
while(escolha >= 1 && escolha <= 4)
{
printf("Digite o primeiro numero: ");
scanf("%f", &numeroA);
printf("Digite o segundo numero: ");
scanf("%f", &numeroB);
printf("\nEscolha uma das operacoes:");
printf("\n0 - Sair\n1 - Somar\n2 - Subtrair\n3 - Multiplicar\n4 - Dividir\n");
printf("Sua escolha: ");
scanf("%d", &escolha);
if(escolha == 0)
{
printf("\nSair\n");
break;
}
switch(escolha)
{
case 0: printf("\nSair\n"); break;
case 1: {
resultado = somar(numeroA, numeroB);
printf("\nResultado: %.3f", resultado);
}break;
case 2: {
resultado = subtrair(numeroA, numeroB);
printf("\nResultado: %.3f", resultado);
}break;
case 3: {
resultado = multiplicar(numeroA, numeroB);
printf("\nResultado: %.3f", resultado);
}break;
case 4: {
if(numeroB != 0)
{
resultado = dividir(numeroA, numeroB);
printf("\nResultado: %.3f", resultado);
}
else
{
printf("\nNao pode dividir por zero!");
}
}break;
default: {
printf("Digite uma das 5 alternativas");
}break;
}
printf("\n\n");
}
return 0;
}
| 23.360465 | 86 | 0.467894 | 3.21875 |
50fe3fdc5b3b6c9c6750ef53f2b8e18bb7e2e47b
| 3,652 |
go
|
Go
|
ws/broker.go
|
aurawing/auramq-ws
|
071a6e872d30fc4998f8f934a5fdec294543833d
|
[
"Apache-2.0"
] | null | null | null |
ws/broker.go
|
aurawing/auramq-ws
|
071a6e872d30fc4998f8f934a5fdec294543833d
|
[
"Apache-2.0"
] | null | null | null |
ws/broker.go
|
aurawing/auramq-ws
|
071a6e872d30fc4998f8f934a5fdec294543833d
|
[
"Apache-2.0"
] | null | null | null |
package ws
import (
"log"
"net/http"
"github.com/aurawing/auramq"
"github.com/aurawing/auramq/msg"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
)
//Broker websocket broker
type Broker struct {
server *http.Server
router *auramq.Router
addr string
auth bool
authFunc func([]byte) bool
readBufferSize int
writeBufferSize int
subscriberBufferSize int
pingWait int
readWait int
writeWait int
}
//NewBroker create new websocket broker
func NewBroker(router *auramq.Router, addr string, auth bool, authFunc func([]byte) bool, subscriberBufferSize, readBufferSize, writeBufferSize, pingWait, readWait, writeWait int) auramq.Broker {
if subscriberBufferSize == 0 {
subscriberBufferSize = 1024
}
if readBufferSize == 0 {
readBufferSize = 4096
}
if writeBufferSize == 0 {
writeBufferSize = 4096
}
if pingWait == 0 {
pingWait = 30
}
if readWait == 0 {
readWait = 60
}
if writeWait == 0 {
writeWait = 10
}
return &Broker{
router: router,
addr: addr,
auth: auth,
authFunc: authFunc,
readBufferSize: readBufferSize,
writeBufferSize: writeBufferSize,
subscriberBufferSize: subscriberBufferSize,
pingWait: pingWait,
readWait: readWait,
writeWait: writeWait,
}
}
//Run start websocket broker
func (broker *Broker) Run() {
var upgrader = websocket.Upgrader{
ReadBufferSize: broker.readBufferSize,
WriteBufferSize: broker.writeBufferSize,
EnableCompression: true,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
srv := &http.Server{Addr: broker.addr}
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("subscribe error:", err)
return
}
if broker.NeedAuth() {
_, b, err := conn.ReadMessage()
if err != nil {
log.Println("read auth message failed:", err)
// conn.WriteMessage(websocket.CloseMessage, []byte{})
conn.Close()
return
}
// if msgType != websocket.BinaryMessage {
// log.Println("auth message should be binary format")
// return
// }
if !broker.Auth(b) {
log.Println("auth failed")
// conn.WriteMessage(websocket.CloseMessage, []byte{})
conn.Close()
return
}
}
_, b, err := conn.ReadMessage()
if err != nil {
log.Printf("error when read topics for subscribing: %s\n", err)
// conn.WriteMessage(websocket.CloseMessage, []byte{})
conn.Close()
return
}
subscribeMsg := new(msg.SubscribeMsg)
err = proto.Unmarshal(b, subscribeMsg)
if err != nil {
log.Printf("error when decode topics for subscribing: %s\n", err)
conn.Close()
return
}
subscriber := NewWsSubscriber(broker.router, conn, broker.subscriberBufferSize, broker.pingWait, broker.readWait, broker.writeWait)
subscriber.Run()
broker.router.Register(subscriber, subscribeMsg.Topics)
})
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Printf("httpserver: ListenAndServe() error: %s", err)
}
}()
broker.server = srv
}
//NeedAuth if need auth when subscribe
func (broker *Broker) NeedAuth() bool {
return broker.auth
}
//Auth authencate when subscribing
func (broker *Broker) Auth(authMsg []byte) bool {
return broker.authFunc(authMsg)
}
//Close close http server
func (broker *Broker) Close() {
if err := broker.server.Shutdown(nil); err != nil {
log.Printf("httpserver: Shutdown() error: %s", err)
}
broker.router.Close()
}
| 25.538462 | 195 | 0.650329 | 3 |
c267bccd3a5bb25f9459721aefc4b4d576cebb0f
| 2,467 |
kt
|
Kotlin
|
common/src/main/java/co/railgun/common/StringUtil.kt
|
ProjectRailgun/Spica
|
394f3303fc261289a82e7a39dd77a9e413ca27ed
|
[
"MIT"
] | null | null | null |
common/src/main/java/co/railgun/common/StringUtil.kt
|
ProjectRailgun/Spica
|
394f3303fc261289a82e7a39dd77a9e413ca27ed
|
[
"MIT"
] | null | null | null |
common/src/main/java/co/railgun/common/StringUtil.kt
|
ProjectRailgun/Spica
|
394f3303fc261289a82e7a39dd77a9e413ca27ed
|
[
"MIT"
] | null | null | null |
package co.railgun.common
import co.railgun.common.model.Bangumi
import co.railgun.common.model.Episode
import co.railgun.common.model.EpisodeDetail
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Created by roya on 2017/7/20.
*/
object StringUtil {
private var dayFormatter = SimpleDateFormat("EEEE", Locale.getDefault())
private const val oneDay = 86400000
fun dayOfWeek(day: Int): String {
return dayFormatter.format(day * oneDay + 3 * oneDay)
}
private fun addPadding(string: String): String {
return (if (string.length < 2) "0" else "") + string
}
fun microsecondFormat(ms: Long): String =
addPadding("" + TimeUnit.MILLISECONDS.toMinutes(ms)) +
":" +
addPadding(
"" + (TimeUnit.MILLISECONDS.toSeconds(ms) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)))
)
fun getName(bangumi: Bangumi): String = when {
isDisplayLanguageChinese -> when {
bangumi.name_cn.isNotEmpty() -> bangumi.name_cn
else -> bangumi.name
}
else -> when {
bangumi.name.isNotEmpty() -> bangumi.name
else -> bangumi.name_cn
}
}
fun getName(episode: Episode): String = when {
isDisplayLanguageChinese -> when {
episode.name_cn.isEmpty() -> episode.name
else -> episode.name_cn
}
else -> when {
episode.name.isEmpty() -> episode.name_cn
else -> episode.name
}
}
fun getName(episodeDetail: EpisodeDetail): String = when {
isDisplayLanguageChinese -> when {
episodeDetail.name_cn.isEmpty() -> episodeDetail.name
else -> episodeDetail.name_cn
}
else -> when {
episodeDetail.name.isEmpty() -> episodeDetail.name_cn
else -> episodeDetail.name
}
}
fun subTitle(bangumi: Bangumi): String = when {
isDisplayLanguageChinese -> when {
bangumi.name.isNotEmpty() -> bangumi.name
else -> bangumi.name_cn
}
else -> when {
bangumi.name_cn.isNotEmpty() -> bangumi.name_cn
else -> bangumi.name
}
}
private val isDisplayLanguageChinese: Boolean
get() = Locale.getDefault().displayLanguage == Locale.CHINESE.displayLanguage
}
| 30.45679 | 92 | 0.593028 | 3.09375 |
98d6db5bf4892ee9c331f32ec11193a7eccd6b74
| 2,898 |
lua
|
Lua
|
scripts/screenhelper.lua
|
58115310/isaac-mod-config-menu
|
612071c448e29095917a3902f73031a4a5722feb
|
[
"MIT"
] | 2 |
2021-12-27T23:01:49.000Z
|
2022-03-20T22:55:39.000Z
|
scripts/screenhelper.lua
|
58115310/isaac-mod-config-menu
|
612071c448e29095917a3902f73031a4a5722feb
|
[
"MIT"
] | 5 |
2021-12-14T15:43:26.000Z
|
2022-01-29T04:49:05.000Z
|
scripts/screenhelper.lua
|
58115310/isaac-mod-config-menu
|
612071c448e29095917a3902f73031a4a5722feb
|
[
"MIT"
] | 4 |
2021-12-14T15:39:45.000Z
|
2022-01-29T04:12:11.000Z
|
------------------------------------------------------------------------------
-- IMPORTANT: DO NOT EDIT THIS FILE!!! --
------------------------------------------------------------------------------
-- This file relies on other versions of itself being the same. --
-- If you need something in this file changed, please let the creator know! --
------------------------------------------------------------------------------
-- CODE STARTS BELOW --
-------------
-- version --
-------------
local fileVersion = 1
--prevent older/same version versions of this script from loading
if ScreenHelper and ScreenHelper.Version >= fileVersion then
return ScreenHelper
end
if not ScreenHelper then
ScreenHelper = {}
ScreenHelper.Version = fileVersion
elseif ScreenHelper.Version < fileVersion then
local oldVersion = ScreenHelper.Version
-- handle old versions
ScreenHelper.Version = fileVersion
end
---------------------
--hud offset helper--
---------------------
ScreenHelper.CurrentScreenOffset = ScreenHelper.CurrentScreenOffset or 0
function ScreenHelper.SetOffset(num)
num = math.min(math.max(math.floor(num),0),10)
ScreenHelper.CurrentScreenOffset = num
return num
end
function ScreenHelper.GetOffset()
return ScreenHelper.CurrentScreenOffset
end
------------------------------------
--screen size and corner functions--
------------------------------------
local vecZero = Vector(0,0)
function ScreenHelper.GetScreenSize() --based off of code from kilburn
local game = Game()
local room = game:GetRoom()
local pos = room:WorldToScreenPosition(vecZero) - room:GetRenderScrollOffset() - game.ScreenShakeOffset
local rx = pos.X + 60 * 26 / 40
local ry = pos.Y + 140 * (26 / 40)
return Vector(rx*2 + 13*26, ry*2 + 7*26)
end
function ScreenHelper.GetScreenCenter()
return ScreenHelper.GetScreenSize() / 2
end
function ScreenHelper.GetScreenBottomRight(offset)
offset = offset or ScreenHelper.GetOffset()
local pos = ScreenHelper.GetScreenSize()
local hudOffset = Vector(-offset * 2.2, -offset * 1.6)
pos = pos + hudOffset
return pos
end
function ScreenHelper.GetScreenBottomLeft(offset)
offset = offset or ScreenHelper.GetOffset()
local pos = Vector(0, ScreenHelper.GetScreenBottomRight(0).Y)
local hudOffset = Vector(offset * 2.2, -offset * 1.6)
pos = pos + hudOffset
return pos
end
function ScreenHelper.GetScreenTopRight(offset)
offset = offset or ScreenHelper.GetOffset()
local pos = Vector(ScreenHelper.GetScreenBottomRight(0).X, 0)
local hudOffset = Vector(-offset * 2.2, offset * 1.2)
pos = pos + hudOffset
return pos
end
function ScreenHelper.GetScreenTopLeft(offset)
offset = offset or ScreenHelper.GetOffset()
local pos = vecZero
local hudOffset = Vector(offset * 2, offset * 1.2)
pos = pos + hudOffset
return pos
end
return ScreenHelper
| 21.466667 | 104 | 0.632505 | 3.234375 |
dd0d7c6dd7f0fcea8f87ebeb9896f9f54792b3fd
| 985 |
go
|
Go
|
leetcode/combination-sum-ii/solution.go
|
rtxu/cp
|
16b8d6337e202f19ce75db644d4c54f4ef7baa32
|
[
"MIT"
] | null | null | null |
leetcode/combination-sum-ii/solution.go
|
rtxu/cp
|
16b8d6337e202f19ce75db644d4c54f4ef7baa32
|
[
"MIT"
] | null | null | null |
leetcode/combination-sum-ii/solution.go
|
rtxu/cp
|
16b8d6337e202f19ce75db644d4c54f4ef7baa32
|
[
"MIT"
] | null | null | null |
func backtrack(i int, current []int, nums, counts []int, target int, result *[][]int) {
if target == 0 {
currentCopy := make([]int, len(current))
copy(currentCopy, current)
*result = append(*result, currentCopy)
return
}
if i == len(nums) {
return
}
var j int
for j = 0; j <= counts[i] && target - nums[i]*j >= 0; j++ {
backtrack(i+1, current, nums, counts, target - nums[i]*j, result)
current = append(current, nums[i])
}
current = current[0:len(current)-j]
}
func combinationSum2(candidates []int, target int) [][]int {
M := make(map[int]int)
for i := 0; i < len(candidates); i++ {
M[candidates[i]]++
}
nums, counts := make([]int, len(M)), make([]int, len(M))
var i int
for num, count := range M {
nums[i], counts[i] = num, count
i++
}
var result [][]int
backtrack(0, []int{}, nums, counts, target, &result)
return result
}
| 28.142857 | 87 | 0.532995 | 3.1875 |
2602eca239ac1507dd53509d59e31b0029d97128
| 3,056 |
java
|
Java
|
src/test/java/com/alexrnl/commons/translation/TranslatorTest.java
|
AlexRNL/Commons
|
e65e42f3649d6381a6f644beb03304c2ae4ad524
|
[
"BSD-3-Clause"
] | 1 |
2015-04-03T00:25:56.000Z
|
2015-04-03T00:25:56.000Z
|
src/test/java/com/alexrnl/commons/translation/TranslatorTest.java
|
AlexRNL/Commons
|
e65e42f3649d6381a6f644beb03304c2ae4ad524
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/java/com/alexrnl/commons/translation/TranslatorTest.java
|
AlexRNL/Commons
|
e65e42f3649d6381a6f644beb03304c2ae4ad524
|
[
"BSD-3-Clause"
] | 2 |
2015-04-03T00:25:58.000Z
|
2019-04-23T03:47:15.000Z
|
package com.alexrnl.commons.translation;
import static org.junit.Assert.assertEquals;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
/**
* Test suite for the {@link Translator} class.
* @author Alex
*/
public class TranslatorTest {
/** The translator to test */
private Translator translator;
/**
* Set up attributes.
* @throws URISyntaxException
* if the path to the test translation file is not valid.
*/
@Before
public void setUp () throws URISyntaxException {
translator = new Translator(Paths.get(getClass().getResource("/locale.xml").toURI()));
}
/**
* Test method for {@link Translator#get(String)}.
*/
@Test
public void testGetString () {
assertEquals("aba.ldr", translator.get("aba.ldr"));
assertEquals("The Name", translator.get("commons.test.name"));
assertEquals("Hey, this has The Name, isn't that cool?", translator.get("commons.test.include"));
assertEquals("Hey, this has The Name", translator.get("commons.test.includeEnd"));
assertEquals("commons.test.missing", translator.get("commons.test.missing"));
assertEquals("Hey, this has commons.test.missing", translator.get("commons.test.includeFake"));
}
/**
* Test that verify that a self inclusion throwing an {@link IllegalArgumentException} instead
* of provoking a {@link StackOverflowError}.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetSelfIncludedTranslation () {
translator.get("commons.test.includeSelf");
}
/**
* Test method for {@link Translator#get(java.lang.String, Collection)}.
*/
@Test
public void testGetStringCollection () {
assertEquals("aba.ldr", translator.get("aba.ldr", Collections.emptyList()));
assertEquals("The Name", translator.get("commons.test.name", Collections.emptyList()));
assertEquals("The Name", translator.get("commons.test.name", (Collection<Object>) null));
assertEquals("My parameter LDR", translator.get("commons.test.parameter", "LDR"));
assertEquals("This LDR is really ABA!", translator.get("commons.test.parameters", "LDR", "ABA"));
assertEquals("This LDR is really ABA!", translator.get("commons.test.parameters", "LDR", "ABA", "XXX"));
}
/**
* Test method for {@link Translator#get(ParametrableTranslation)}.
*/
@Test
public void testGetParametrableTranslation () {
assertEquals("This LDR is really ABA!", translator.get(new ParametrableTranslation() {
@Override
public String getTranslationKey () {
return "commons.test.parameters";
}
@Override
public Collection<Object> getParameters () {
return Arrays.<Object>asList("LDR", "ABA", "XXX");
}
}));
}
/**
* Test method for {@link Translator#get(Translatable)}.
*/
@Test
public void testGetTranslatable () {
assertEquals("The Name", translator.get(new Translatable() {
@Override
public String getTranslationKey () {
return "commons.test.name";
}
}));
}
}
| 30.868687 | 106 | 0.705825 | 3 |
00cb361df99516a812d2ab1c40c5864bcc67f2bf
| 1,632 |
kt
|
Kotlin
|
Room/app/src/main/java/com/ko/room/AddActivity.kt
|
terracotta-ko/Android_Treasure_House
|
098d5844fb68cac5ed22fa79370de91e93551227
|
[
"MIT"
] | 3 |
2017-07-08T08:48:31.000Z
|
2022-03-09T07:22:48.000Z
|
Room/app/src/main/java/com/ko/room/AddActivity.kt
|
terracotta-ko/Android_Treasure_House
|
098d5844fb68cac5ed22fa79370de91e93551227
|
[
"MIT"
] | null | null | null |
Room/app/src/main/java/com/ko/room/AddActivity.kt
|
terracotta-ko/Android_Treasure_House
|
098d5844fb68cac5ed22fa79370de91e93551227
|
[
"MIT"
] | null | null | null |
package com.ko.room
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ko.room.data.UserDao
import com.ko.room.data.UserDatabaseProvider
import com.ko.room.data.UserEntity
import kotlinx.android.synthetic.main.activity_add.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.random.Random
class AddActivity : AppCompatActivity(), CoroutineScope {
private lateinit var userDao: UserDao
private lateinit var dispatcher: CoroutineDispatcher
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
job = Job()
userDao = UserDatabaseProvider.getInstance(this).userDao()
dispatcher = CoroutineDispatcherDefault()
confirmButton.setOnClickListener {
launch(dispatcher.IODispatcher) {
userDao.addUser(
UserEntity(
userIdInput.editText?.text.toString().toLong(),
userNameInput.editText?.text.toString(),
Random.nextBoolean()
)
)
launch(dispatcher.UIDispatcher) {
finish()
}
}
}
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
}
| 30.222222 | 71 | 0.653186 | 3.015625 |
506b70feaa54e921daf93f0b68fb4897f971c395
| 2,469 |
go
|
Go
|
http-utils.go
|
CzarSimon/go-util
|
5db483fbbe25cfa8196eaa43f05f36e857165d8b
|
[
"MIT"
] | null | null | null |
http-utils.go
|
CzarSimon/go-util
|
5db483fbbe25cfa8196eaa43f05f36e857165d8b
|
[
"MIT"
] | null | null | null |
http-utils.go
|
CzarSimon/go-util
|
5db483fbbe25cfa8196eaa43f05f36e857165d8b
|
[
"MIT"
] | null | null | null |
package util
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
// StatusOK The status 200 return message
const StatusOK string = "200 - OK"
// StatusUnauthorized The status 401 return message
const StatusUnauthorized string = "401 - Unauthorized"
//SendPlainTextRes sends a plain text message given as an input
func SendPlainTextRes(res http.ResponseWriter, msg string) {
res.Header().Set("Content-Type", "text/plain")
res.Header().Set("Access-Control-Allow-Origin", "*")
res.WriteHeader(http.StatusOK)
res.Write([]byte(msg))
}
//JSONRes contains a response
type JSONRes struct {
Response string
}
//SendJSONStringRes serializes a given message sting to JSON and sends to the requestor
func SendJSONStringRes(res http.ResponseWriter, msg string) {
jsonResponse := JSONRes{msg}
js, err := json.Marshal(jsonResponse)
if err != nil {
SendErrRes(res, err)
return
}
SendJSONRes(res, js)
}
//SendJSONRes send a given JSON respons to the requestor
func SendJSONRes(res http.ResponseWriter, js []byte) {
res.Header().Set("Content-Type", "application/json")
res.Header().Set("Access-Control-Allow-Origin", "*")
res.WriteHeader(http.StatusOK)
res.Write(js)
}
//SendErrRes sends a given error to the requestor
func SendErrRes(res http.ResponseWriter, err error) {
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
}
}
// SendErrStatus Sends an error and a given status code to the requestor
func SendErrStatus(res http.ResponseWriter, err error, statusCode int) {
if err != nil {
http.Error(res, err.Error(), statusCode)
}
}
//SendOK sends status code 200 to the requestor
func SendOK(res http.ResponseWriter) {
res.WriteHeader(http.StatusOK)
res.Write([]byte(StatusOK))
}
// Ping sends a 200 response if the server is running
func Ping(res http.ResponseWriter, req *http.Request) {
fmt.Println("Ping recieved")
SendOK(res)
}
// SendUnauthorized Sends an unauthorized status to the requestor
func SendUnauthorized(res http.ResponseWriter) {
http.Error(res, StatusUnauthorized, http.StatusUnauthorized)
}
//PlaceholderHandler is a dummy handler to ease development
func PlaceholderHandler(res http.ResponseWriter, req *http.Request) {
SendOK(res)
}
// ParseValueFromQuery Parses a query value from request
func ParseValueFromQuery(req *http.Request, key, errorMsg string) (string, error) {
value := req.URL.Query().Get(key)
if value == "" {
return "", errors.New(errorMsg)
}
return value, nil
}
| 26.836957 | 87 | 0.745241 | 3.359375 |
e8eedc51b24c6143d7853efa95a31479c5ffbbd9
| 2,645 |
py
|
Python
|
tests/commands/test_generate.py
|
pedrovelho/camp
|
98105c9054b8db3377cb6a06e7b5451b97c6c285
|
[
"MIT"
] | null | null | null |
tests/commands/test_generate.py
|
pedrovelho/camp
|
98105c9054b8db3377cb6a06e7b5451b97c6c285
|
[
"MIT"
] | null | null | null |
tests/commands/test_generate.py
|
pedrovelho/camp
|
98105c9054b8db3377cb6a06e7b5451b97c6c285
|
[
"MIT"
] | 1 |
2019-02-05T08:49:41.000Z
|
2019-02-05T08:49:41.000Z
|
#
# CAMP
#
# Copyright (C) 2017, 2018 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
from unittest import TestCase
from camp.commands import Command, Generate
class DefaultValuesAreCorrect(TestCase):
def test_given_no_working_directory(self):
command_line = "generate --all"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertEqual(command.working_directory,
Generate.DEFAULT_WORKING_DIRECTORY)
def test_given_no_working_directory(self):
command_line = "generate -d my/directory"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertEqual(command.only_coverage,
Generate.DEFAULT_COVERAGE)
class ShortOptionsAreAccepted(TestCase):
def test_given_working_directory(self):
command_line = "generate --d my/test/directory"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertEqual(command.working_directory,
"my/test/directory")
def test_given_only_coverage(self):
command_line = "generate --c"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertTrue(command.only_coverage)
def test_given_all_configurations(self):
command_line = "generate --a"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertFalse(command.only_coverage)
class LongOptionsAreAccepted(TestCase):
def test_given_working_directory(self):
command_line = "generate --directory my/test/directory"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertEqual(command.working_directory,
"my/test/directory")
def test_given_only_coverage(self):
command_line = "generate --coverage"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertTrue(command.only_coverage)
def test_given_all_configurations(self):
command_line = "generate --all"
command = Command.extract_from(command_line.split())
self.assertIsInstance(command, Generate)
self.assertFalse(command.only_coverage)
| 25.190476 | 63 | 0.689981 | 3.203125 |
56babdf2f8d08e5c265ca8c7ae7b04565d0b0d1c
| 1,394 |
ts
|
TypeScript
|
src/Common.ts
|
huang2002/3h-math
|
af401ed89238d8b0bceabc94719b10569dd3be84
|
[
"MIT"
] | null | null | null |
src/Common.ts
|
huang2002/3h-math
|
af401ed89238d8b0bceabc94719b10569dd3be84
|
[
"MIT"
] | null | null | null |
src/Common.ts
|
huang2002/3h-math
|
af401ed89238d8b0bceabc94719b10569dd3be84
|
[
"MIT"
] | null | null | null |
/**
* Common utilities.
*/
export namespace Common {
/** dts2md break */
/**
* Whether to check input data.
* (Validation can be disabled to improve performance
* at the cost of potential errors.)
* @default true
*/
export let checkInput = true;
/** dts2md break */
/**
* Type of array initializers.
*/
export type ArrayInitializer<T> = (_: void, index: number) => T;
/** dts2md break */
/**
* Create an array of the given length and
* initialize each element using provided initializer.
*/
export const createArray = <T>(
length: number,
initializer: ArrayInitializer<T>,
): T[] => (
Array.from({ length }, initializer)
);
/** dts2md break */
/**
* Assert that the given two dimensions are equal.
*/
export const assertSameDimension = (d1: number, d2: number) => {
if (d1 !== d2) {
throw new RangeError(
`dimensions don't match (${d1} !== ${d2})`
);
}
};
/** dts2md break */
/**
* Asserts that the given dimension is valid.
*/
export const validateDimension = (dimension: number) => {
if ((dimension <= 0) || !Number.isInteger(dimension)) {
throw new RangeError(
`invalid dimension (${dimension})`
);
}
};
}
| 26.301887 | 68 | 0.530846 | 3.203125 |
a7e001f8b61785f0cc5088a8d95a19f45656ad58
| 2,278 |
lua
|
Lua
|
concord/utils.lua
|
LaughingLeader/Concord
|
ea1aa0d799317cc7d82469ef304e37ce5eb8899c
|
[
"MIT"
] | null | null | null |
concord/utils.lua
|
LaughingLeader/Concord
|
ea1aa0d799317cc7d82469ef304e37ce5eb8899c
|
[
"MIT"
] | null | null | null |
concord/utils.lua
|
LaughingLeader/Concord
|
ea1aa0d799317cc7d82469ef304e37ce5eb8899c
|
[
"MIT"
] | null | null | null |
--- Helper module for misc operations
---@class Utils:table
local Utils = {}
--- Does a shallow copy of a table and appends it to a target table.
---@param orig Table to copy
---@param target Table to append to
function Utils.shallowCopy(orig, target)
for key, value in pairs(orig) do
target[key] = value
end
return target
end
--- Requires files and puts them in a table.
--- Accepts a table of paths to Lua files: {"path/to/file_1", "path/to/another/file_2", "etc"}
--- Accepts a path to a directory with Lua files: "my_files/here"
---@param pathOrFiles The table of paths or a path to a directory.
---@param namespace A table that will hold the required files
---@return table The namespace table
function Utils.loadNamespace(pathOrFiles, namespace)
if (type(pathOrFiles) ~= "string" and type(pathOrFiles) ~= "table") then
error("bad argument #1 to 'loadNamespace' (string/table of strings expected, got "..type(pathOrFiles)..")", 2)
end
if (type(pathOrFiles) == "string") then
local info = love.filesystem.getInfo(pathOrFiles) --- luacheck: ignore
if (info == nil or info.type ~= "directory") then
error("bad argument #1 to 'loadNamespace' (path '"..pathOrFiles.."' not found)", 2)
end
local files = love.filesystem.getDirectoryItems(pathOrFiles)
for _, file in ipairs(files) do
local name = file:sub(1, #file - 4)
local path = pathOrFiles.."."..name
local value = require(path)
if namespace then namespace[name] = value end
end
elseif (type(pathOrFiles == "table")) then
for _, path in ipairs(pathOrFiles) do
if (type(path) ~= "string") then
error("bad argument #2 to 'loadNamespace' (string/table of strings expected, got table containing "..type(path)..")", 2) --- luacheck: ignore
end
local name = path
local dotIndex, slashIndex = path:match("^.*()%."), path:match("^.*()%/")
if (dotIndex or slashIndex) then
name = path:sub((dotIndex or slashIndex) + 1)
end
local value = require(path)
if namespace then namespace[name] = value end
end
end
return namespace
end
return Utils
| 36.15873 | 157 | 0.628622 | 3.484375 |
5846bb493394ac0f77bde2212570cdeb33d4193a
| 2,722 |
kt
|
Kotlin
|
src/test/kotlin/org/jetbrains/kotlin/jupyter/test/ikotlinTests.kt
|
jjkavalam/kotlin-jupyter
|
1476fc94b0cfe10727c8bc57900310680f051470
|
[
"Apache-2.0"
] | 1 |
2018-06-27T06:52:38.000Z
|
2018-06-27T06:52:38.000Z
|
src/test/kotlin/org/jetbrains/kotlin/jupyter/test/ikotlinTests.kt
|
jjkavalam/kotlin-jupyter
|
1476fc94b0cfe10727c8bc57900310680f051470
|
[
"Apache-2.0"
] | null | null | null |
src/test/kotlin/org/jetbrains/kotlin/jupyter/test/ikotlinTests.kt
|
jjkavalam/kotlin-jupyter
|
1476fc94b0cfe10727c8bc57900310680f051470
|
[
"Apache-2.0"
] | null | null | null |
package org.jetbrains.kotlin.jupyter.test
import org.jetbrains.kotlin.jupyter.*
import org.junit.*
import org.zeromq.ZMQ
import java.io.IOException
import java.net.ServerSocket
import java.util.*
import kotlin.concurrent.thread
class KernelServerTest {
private val config = KernelConfig(
ports = JupyterSockets.values().map { randomPort() }.toTypedArray(),
transport = "tcp",
signatureScheme = "hmac1-sha256",
signatureKey = "")
private val hmac = HMAC(config.signatureScheme, config.signatureKey)
private var server: Thread? = null
@Before
fun setupServer() {
server = thread { kernelServer(config) }
}
@After
fun teardownServer() {
Thread.sleep(100)
server?.interrupt()
}
@Test
fun testHeartbeat() {
val context = ZMQ.context(1)
with (context.socket(ZMQ.REQ)) {
try {
connect("${config.transport}://*:${config.ports[JupyterSockets.hb.ordinal]}")
send("abc")
val msg = recvStr()
Assert.assertEquals("abc", msg)
} finally {
close()
context.term()
}
}
}
@Test
fun testStdin() {
val context = ZMQ.context(1)
with (context.socket(ZMQ.REQ)) {
try {
connect("${config.transport}://*:${config.ports[JupyterSockets.stdin.ordinal]}")
sendMore("abc")
sendMore("def")
send("ok")
} finally {
close()
context.term()
}
}
}
@Test
fun testShell() {
val context = ZMQ.context(1)
with (context.socket(ZMQ.REQ)) {
try {
connect("${config.transport}://*:${config.ports[JupyterSockets.control.ordinal]}")
sendMessage(Message(header = makeHeader("kernel_info_request")), hmac)
val msg = receiveMessage(recv(), hmac)
Assert.assertEquals("kernel_info_reply", msg!!.header!!["msg_type"])
} finally {
close()
context.term()
}
}
}
companion object {
private val rng = Random()
private val portRangeStart = 32768
private val portRangeEnd = 65536
fun randomPort(): Int =
generateSequence { portRangeStart + rng.nextInt(portRangeEnd - portRangeStart) }.find {
try {
ServerSocket(it).close()
true
}
catch (e: IOException) {
false
}
}!!
}
}
| 27.494949 | 99 | 0.511756 | 3.0625 |
365569eae6b87c0f624a559da753374adef6f3fa
| 1,298 |
kt
|
Kotlin
|
src/commonMain/kotlin/KWS/OpCode/OpCodeUtils.kt
|
SeekDaSky/KWS
|
2ade7661b622b5782a5c75b8203b41b45c80002a
|
[
"MIT"
] | 1 |
2020-04-14T01:36:21.000Z
|
2020-04-14T01:36:21.000Z
|
src/commonMain/kotlin/KWS/OpCode/OpCodeUtils.kt
|
SeekDaSky/KWS
|
2ade7661b622b5782a5c75b8203b41b45c80002a
|
[
"MIT"
] | null | null | null |
src/commonMain/kotlin/KWS/OpCode/OpCodeUtils.kt
|
SeekDaSky/KWS
|
2ade7661b622b5782a5c75b8203b41b45c80002a
|
[
"MIT"
] | null | null | null |
package KWS.OpCode
import KWS.Message.*
import kotlin.experimental.and
/**
* Returns the OpCode having the corresponding binary code
*
* @param Byte Byte to analyse
* @return OpCode
*/
internal fun getOpcode(raw : Byte) : OpCode{
return when((raw and 0b00001111).toInt()){
0 -> OpCode.FRAGMENT
1 -> OpCode.TEXT
2 -> OpCode.BINARY
8 -> OpCode.CONNECTION_CLOSED
9 -> OpCode.PING
10-> OpCode.PONG
else -> OpCode.RESERVED
}
}
/**
* Return the OpCode of a Sendable object
*
* @param obj Sendable to evaluate
* @return OpCode of this object
*/
internal fun getOpcode(obj : Sendable) : OpCode{
return when(obj){
is FragmentMessage -> OpCode.FRAGMENT
is StringMessage -> OpCode.TEXT
is BinaryMessage -> OpCode.BINARY
is CloseMessage -> OpCode.CONNECTION_CLOSED
is PingMessage -> OpCode.PING
is PongMessage-> OpCode.PONG
else -> throw Exception("Unknown object given")
}
}
/**
* Returns the binary representation of the OpCode
*
* @param OpCode OpCode to convert
* @return Byte
*/
internal fun getBinaryOpCode(op : OpCode) : Byte {
return when(op){
OpCode.FRAGMENT -> 0
OpCode.TEXT -> 1
OpCode.BINARY -> 2
OpCode.CONNECTION_CLOSED -> 8
OpCode.PING -> 9
OpCode.PONG -> 10
else -> throw Exception("Unknown operation code");
}
}
| 21.278689 | 57 | 0.688752 | 3.21875 |
577280c1d2b2e76b1a7fd41bf5a71255ea6bcf5c
| 2,681 |
h
|
C
|
llist.h
|
PotatoMaster101/linked_list
|
4cbe19077d062bbdeb91eff27f137d82053b3a90
|
[
"MIT"
] | null | null | null |
llist.h
|
PotatoMaster101/linked_list
|
4cbe19077d062bbdeb91eff27f137d82053b3a90
|
[
"MIT"
] | null | null | null |
llist.h
|
PotatoMaster101/linked_list
|
4cbe19077d062bbdeb91eff27f137d82053b3a90
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// llist.h
// Linked list implementation in C99.
//
// Author: PotatoMaster101
// Date: 12/04/2019
///////////////////////////////////////////////////////////////////////////////
#ifndef LLIST_H
#define LLIST_H
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define LLIST_OK 0
#define LLIST_NULL_ERR 1
#define LLIST_ALLOC_ERR 2
// The linked list node type.
typedef struct linked_list_node_t {
void *data; // internal data
struct linked_list_node_t *prev; // pointer to previous
struct linked_list_node_t *next; // pointer to next
} lnode_t;
// The linked list type.
typedef struct linked_list_t {
lnode_t *head; // list head
lnode_t *tail; // list tail
size_t len; // list size
} llist_t;
// Initialises the specified linked list.
//
// PARAMS:
// l - the linked list to initialise
//
// RET:
// Zero on success, non-zero on error.
int llist_init(llist_t *l);
// Returns the element at the given index in the specified linked list. If the
// index is out of range, then the last element will be returned.
//
// PARAMS:
// l - the linked list to retrieve the element
// i - the index of the element
//
// RET:
// The element at the given index, or NULL if any error occurred.
void *llist_get(const llist_t *l, size_t i);
// Add a new element into the given linked list. The element will be stored as
// a copy.
//
// PARAMS:
// l - the linked list to have the element added
// d - the element to add
// n - the size of the element
//
// RET:
// Zero on success, non-zero on error.
int llist_add(llist_t *l, const void *d, size_t n);
// Inserts a new element into the given linked list. The element will be
// stored as a copy.
//
// PARAMS:
// l - the linked list to have the element inserted
// d - the element to insert
// n - the size of the element
// i - the index in the linked list to insert to
//
// RET:
// Zero on success, non-zero on error.
int llist_ins(llist_t *l, const void *d, size_t n, size_t i);
// Deletes the element at the given index in the specified linked list. If the
// given index is out of range, then the last element will be deleted.
//
// PARAMS:
// l - the linked list to have the element deleted
// i - the index of the element
//
// RET:
// The element that just got removed.
void *llist_del(llist_t *l, size_t i);
// Clears the given linked list, removing and freeing every element.
//
// PARAMS:
// l - the linked list to free
void llist_clear(llist_t *l);
#endif
| 27.639175 | 79 | 0.615815 | 3.078125 |
75fcdba2f5d6b549d8eed501b10e9c4889018017
| 2,681 |
php
|
PHP
|
app/Http/Controllers/FilmsController.php
|
salmakl/FilmReview
|
b6495339fd7704a3ee886789f93962bd880538a9
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/FilmsController.php
|
salmakl/FilmReview
|
b6495339fd7704a3ee886789f93962bd880538a9
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/FilmsController.php
|
salmakl/FilmReview
|
b6495339fd7704a3ee886789f93962bd880538a9
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use App\Film;
use App\Comment;
use Illuminate\Http\Request;
class FilmsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$films = Film::all();
return view('films',['films'=>$films]);
}
public function afficher()
{
$films = Film::all();
return view('gallery',['films'=>$films]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$film=new Film();
$file = $request->img;
$ext = $file->getClientOriginalExtension();
$filename = time() . "." . $ext;
$file->move('images/', $filename);
$film->title=$request->title;
$film->description=$request->description;
$film->img=$filename;
$film->save();
return redirect('/films');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Film $id)
{
// echo $id;
$comments= Comment::where('movie_id',$id->id)->get();
return view('single')->with('single', $id)->with('comments',$comments);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$film=Film::find($id);
return view('edit',["film"=>$film]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$film=Film::find($id);
$film->title=$request->title;
$film->description=$request->description;
$film->update();
return redirect(route("films"));
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$film = Film::findOrFail($id);
$film->delete();
return redirect()->back();
// Post::where('id', $id)->delete();
}
}
| 21.277778 | 79 | 0.531145 | 3.078125 |
92f453985288730c9c6d4c2078fe0f58e5886811
| 2,467 |
h
|
C
|
SphereToTriangle/SphereToTriangle/EDCommon.h
|
Cabrra/Advanced-Algorithms
|
062c469e575ef18ce22dc5320be3188dbe3b409d
|
[
"MIT"
] | null | null | null |
SphereToTriangle/SphereToTriangle/EDCommon.h
|
Cabrra/Advanced-Algorithms
|
062c469e575ef18ce22dc5320be3188dbe3b409d
|
[
"MIT"
] | null | null | null |
SphereToTriangle/SphereToTriangle/EDCommon.h
|
Cabrra/Advanced-Algorithms
|
062c469e575ef18ce22dc5320be3188dbe3b409d
|
[
"MIT"
] | null | null | null |
#ifndef _EDCOMMON_H_
#define _EDCOMMON_H_
#include <windows.h>
#include <queue>
using namespace std;
#include "matrix4.h"
static vec3f worldX( 1.0f, 0.0f, 0.0f );
static vec3f worldY( 0.0f, 1.0f, 0.0f );
static vec3f worldZ( 0.0f, 0.0f, 1.0f );
// OrthoNormalInverse
//
// Fast inverse calculation of a 4x4 matrix that is orthogonal with normalized axes (orthonormal)
//
// See: Orthonormal Matrix Inverse.doc
//
// In:
// const matrix4f &MatrixA - The orthonormal matrix to find the inverse of
// Out:
// matrix4f &MatrixO - Where to store the result of the inverse
void OrthoNormalInverse( matrix4f &MatrixO, const matrix4f &MatrixA );
// MouseLook
//
// Implementation of the Mouse Look Algorithm
//
// See: Matrix Behaviors.doc
//
// In:
// matrix4f &mat - The matrix to rotate
// float fTime - The time elapsed since the last frame
//
// Out:
// matrix4f &mat - The rotated matrix
void MouseLook( matrix4f &mat, float fTime );
// LookAt
//
// Implementation of the Look At Algorithm
//
// See: Matrix Behaviors.doc
//
// In:
// matrix4f &mat - The matrix to transform
// const vec3f& target - The position to look at
//
// Out:
// matrix4f &mat - The transformed matrix
void LookAt( matrix4f &mat, const vec3f &target );
// TurnTo
//
// Implementation of the Turn To Algorithm
//
// See: Matrix Behaviors.doc
//
// In:
// matrix4f &mat - The matrix to transform
// const vec3f &target - The position to turn to
// float fTime - The time elapsed since the last frame
//
// Out:
// matrix4f &mat - The transformed matrix
void TurnTo( matrix4f &mat, const vec3f &target, float fTime );
// HardAttach
//
// Implementation of the Hard Attach Algorithm
//
// See: Matrix Bevahiors.doc
//
// In:
// matrix4f &AttachMat - The matrix to attach
// const matrix4f &AttachToMat - The matrix to attach to
// const vec3f &offset - The object/local space (relative) vector to offset by
//
// Out:
//
// matrix4f &AttachMat - The attached matrix
void HardAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, const vec3f &offset );
// SoftAttach
//
// Implementation of the Soft Attach Algorithm
//
// See: Matrix Behaviors.doc
//
// In:
// matrix4f &AttachMat - The matrix to attach
// const matrix4f& AttachToMat - The matrix to enqueue
// queue< matrix4f > &Buffer - The filled queue of matrices to attach to from
void SoftAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, queue< matrix4f > &Buffer, const vec3f &offset );
#endif
| 25.173469 | 117 | 0.703283 | 3.15625 |
a172e1c97975ec3d3e5d293ccb00024278a91c42
| 1,199 |
c
|
C
|
arr.c
|
DeyvidAdzhemiev/C-Programming
|
7b53149759d8b0af20001d7a7a2e6cab39022ed8
|
[
"MIT"
] | null | null | null |
arr.c
|
DeyvidAdzhemiev/C-Programming
|
7b53149759d8b0af20001d7a7a2e6cab39022ed8
|
[
"MIT"
] | null | null | null |
arr.c
|
DeyvidAdzhemiev/C-Programming
|
7b53149759d8b0af20001d7a7a2e6cab39022ed8
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
int **alloc_array(int rows, int cols) {
int **rp = NULL;
int j, k;
rp = (int **)malloc(rows * sizeof (int *));
if (!rp) goto bad0;
for (j = 0; j < rows; j++) {
rp[j] = (int *)malloc(cols * sizeof (int));
if (!rp[j]) goto bad1;
}
return rp;
bad1:
for (k = 0; k < j; k++)
free(rp[k]);
free(rp);
bad0:
return NULL;
}
void dealloc_array(int **rp, int rows) {
int j;
for (j = 0; j < rows; j++)
free(rp[j]);
free(rp);
return;
}
int main(void) {
int a[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
int i, j;
int **dynarr;
int ***t = &dynarr;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", a[i][j]);
printf("\n");
}
dynarr = alloc_array(3, 3);
if (!dynarr) goto error;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++) {
dynarr[i][j] = a[i][j];
/*
*(*(dynarr + i) + j) = a[i][j];
*/
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", dynarr[i][j]);
printf("\n");
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d ", *(*((*t) + i) + j));
printf("\n");
}
dealloc_array(dynarr, 3);
return 0;
error:
return -1;
}
| 14.27381 | 45 | 0.442869 | 3.125 |
e4391e4563f2223d3ebd0ed3702fb1822c7549c0
| 829 |
swift
|
Swift
|
Algorithm/Algorithm/Sort/BinarySearch.swift
|
hulinSun/al
|
06f47309780aa72a184f2173bb2efad980bd9165
|
[
"Apache-2.0"
] | null | null | null |
Algorithm/Algorithm/Sort/BinarySearch.swift
|
hulinSun/al
|
06f47309780aa72a184f2173bb2efad980bd9165
|
[
"Apache-2.0"
] | null | null | null |
Algorithm/Algorithm/Sort/BinarySearch.swift
|
hulinSun/al
|
06f47309780aa72a184f2173bb2efad980bd9165
|
[
"Apache-2.0"
] | null | null | null |
//
// BinarySearch.swift
// Algorithm
//
// Created by 孙虎林 on 2020/12/4.
//
import Foundation
/// 二分查找
class BinarySearch {
/// 二分查找
/// - Parameters:
/// - value: 查找的值
/// - array: 数组
/// - Returns: 索引,查不到返回 -1
public class func indexOf(value: Int, array:[Int]) -> Int {
var begin = 0
var end = array.count
while begin != end {
let mid = begin + (end - begin) / 2 // 减少溢出
if value < array[mid] {
end = mid
} else if value > array[mid] {
begin = mid
} else {
return mid
}
}
return -1
}
public class func test() {
let array = [1,2,3,4,5,6,7,8,9]
let idx = indexOf(value: 9, array: array)
print(idx)
}
}
| 20.725 | 63 | 0.44994 | 3.265625 |
d5c7dbbd6a2ef853ed8fb62813c6eaac40d33692
| 2,932 |
kt
|
Kotlin
|
plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt
|
duhd/ubin-corda
|
ee7914059638ca12375bf51375c3d19b767d2c1f
|
[
"Apache-2.0"
] | 108 |
2017-11-14T03:10:47.000Z
|
2020-08-26T03:49:37.000Z
|
plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt
|
duhd/ubin-corda
|
ee7914059638ca12375bf51375c3d19b767d2c1f
|
[
"Apache-2.0"
] | 3 |
2018-03-12T07:51:49.000Z
|
2018-11-12T14:28:49.000Z
|
plan/src/main/kotlin/com/r3/demos/ubin2a/plan/graph/StronglyConnectedComponentDetection.kt
|
duhd/ubin-corda
|
ee7914059638ca12375bf51375c3d19b767d2c1f
|
[
"Apache-2.0"
] | 53 |
2017-11-14T02:58:15.000Z
|
2021-08-13T04:24:04.000Z
|
package com.r3.demos.ubin2a.plan.graph
import java.util.*
/**
* Use Tarjan's strongly connected components algorithm to find all strongly connected components in a graph.
*/
fun <T> detectStronglyConnectedComponents(graph: DirectedGraph<T>): List<StronglyConnectedComponent<T>> {
return StronglyConnectedComponentDetection(graph).components
}
private class StronglyConnectedComponentDetection<T>(val graph: DirectedGraph<T>) {
private val componentsList = mutableListOf<StronglyConnectedComponent<T>>()
private val exploredEdges = mutableSetOf<Pair<GraphNode<T>, GraphNode<T>>>()
private val stack = Stack<GraphNode<T>>()
private var index = 0
/**
* For each node in the directed graph, find strongly connected components.
*/
val components: List<StronglyConnectedComponent<T>> by lazy {
graph.undefinedNodes().forEach { connect(it) }
componentsList
}
/**
* Recursively find strongly connected component.
*/
private fun connect(node: GraphNode<T>) {
node.index = index
node.lowLink = index
index += 1
stack.push(node)
var processedEdges = false
for (connectedNode in graph.edgesForNode(node.id)) {
// Instead of relying on traversing the nodes in a specific order,
// keep track of what edges have been visited
exploreEdge(node, connectedNode) {
processedEdges = true
if (connectedNode.hasUndefinedIndex()) {
connect(connectedNode)
node.lowLink = minOf(node.lowLink, connectedNode.lowLink)
} else if (stack.contains(connectedNode)) {
// On the stack -> in the current strongly connected component
node.lowLink = minOf(node.lowLink, connectedNode.index)
}
}
}
if (node.lowLink == node.index) {
// At the root node, so add strongly connected component to result
val component = StronglyConnectedComponent(graph, stackNodes(node))
if (component.hasNodes && processedEdges) {
componentsList.add(component)
}
}
}
/**
* Get nodes on stack belonging to the current strongly connected component.
*/
private fun stackNodes(node: GraphNode<T>): List<GraphNode<T>> {
val nodes = mutableListOf<GraphNode<T>>()
do {
val stackNode = stack.pop()
nodes.add(stackNode)
} while (stackNode != node)
return nodes
}
/**
* Execute action if and only if the provided edge has not yet been explored.
*/
private fun exploreEdge(from: GraphNode<T>, to: GraphNode<T>, action: () -> Unit) {
val edge = Pair(from, to)
if (!exploredEdges.contains(edge)) {
exploredEdges.add(edge)
action()
}
}
}
| 35.325301 | 109 | 0.61528 | 3.171875 |
92be131dea620ab605d533c11c3a10fb948ab74e
| 2,942 |
kt
|
Kotlin
|
plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt
|
IKrukov-HORIS/lets-plot
|
b772e4abcc4c715ef3c3a2e3db55abd4044f863f
|
[
"MIT"
] | 768 |
2019-11-28T14:09:46.000Z
|
2022-03-30T18:19:28.000Z
|
plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt
|
IKrukov-HORIS/lets-plot
|
b772e4abcc4c715ef3c3a2e3db55abd4044f863f
|
[
"MIT"
] | 240 |
2019-12-04T20:15:03.000Z
|
2022-03-30T17:12:23.000Z
|
plot-common-portable/src/jvmTest/kotlin/plot/common/data/SeriesUtilFilterFiniteTest.kt
|
IKrukov-HORIS/lets-plot
|
b772e4abcc4c715ef3c3a2e3db55abd4044f863f
|
[
"MIT"
] | 43 |
2019-12-05T13:45:32.000Z
|
2022-03-31T21:27:00.000Z
|
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.common.data
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
@RunWith(Parameterized::class)
class SeriesUtilFilterFiniteTest(
private val list0: List<Double?>,
private val list1: List<Double?>,
private val expected: List<List<Double>>, // Two output lists
) {
@Test
fun filterFinite() {
val filtered = SeriesUtil.filterFinite(list0, list1)
assertEquals(expected[0], filtered[0])
assertEquals(expected[1], filtered[1])
if (list0.size == filtered[0].size) {
assertSame(list0, filtered[0])
assertSame(list1, filtered[1])
}
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun params(): Collection<Array<Any?>> {
return listOf<Array<Any?>>(
arrayOf(
emptyList<Double?>(),
emptyList<Double?>(),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, Double.NEGATIVE_INFINITY, Double.NaN),
listOf<Double?>(1.0, 1.0, 1.0),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(1.0, 1.0, 1.0),
listOf<Double?>(null, Double.NEGATIVE_INFINITY, Double.NaN),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, 1.0, Double.NaN),
listOf<Double?>(1.0, Double.NEGATIVE_INFINITY, 1.0),
listOf(emptyList<Double>(), emptyList<Double>())
),
arrayOf(
listOf<Double?>(null, 1.0, Double.NaN),
listOf<Double?>(1.0, 2.0, Double.NEGATIVE_INFINITY),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
arrayOf(
listOf<Double?>(1.0, 2.0),
listOf<Double?>(3.0, 4.0),
listOf(listOf<Double>(1.0, 2.0), listOf<Double>(3.0, 4.0))
),
arrayOf(
listOf<Double?>(1.0, null),
listOf<Double?>(2.0, Double.NEGATIVE_INFINITY),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
arrayOf(
listOf<Double?>(Double.NaN, 1.0),
listOf<Double?>(null, 2.0),
listOf(listOf<Double>(1.0), listOf<Double>(2.0))
),
)
}
}
}
| 35.02381 | 96 | 0.50136 | 3.0625 |
f71fe6e979a3a854d998ff73ff148210cd6fc3be
| 1,019 |
h
|
C
|
teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h
|
atp42/jks-ros-pkg
|
367fc00f2a9699f33d05c7957d319a80337f1ed4
|
[
"FTL"
] | 3 |
2017-02-02T13:27:45.000Z
|
2018-06-17T11:52:13.000Z
|
teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h
|
salisbury-robotics/jks-ros-pkg
|
367fc00f2a9699f33d05c7957d319a80337f1ed4
|
[
"FTL"
] | null | null | null |
teleop_and_haptics/haptic_display_tools/include/haptic_display_tools/Graphics/SphericalCamera.h
|
salisbury-robotics/jks-ros-pkg
|
367fc00f2a9699f33d05c7957d319a80337f1ed4
|
[
"FTL"
] | null | null | null |
#ifndef SPHERICALCAMERA_H
#define SPHERICALCAMERA_H
#include "Camera.h"
class SphericalCamera : public OrbitingCamera
{
protected:
float m_azimuth, m_altitude;
float m_altitudeLimit;
int m_cardinalUp; // 0 for x, 1 for y, 2 for z
public:
SphericalCamera(cml::vector3f origin = cml::vector3f(0,0,0),
float radius = 2.f, int cardinalUp = 1);
void setAzimuth(float theta) { m_azimuth = theta; }
void setAltitude(float phi) { m_altitude = phi; }
// mutators for setting camera parameters
void setAltitudeLimit(float limit) { m_altitudeLimit = limit; }
void setCardinalUp(int up) { m_cardinalUp = up; }
// helper function to compute the view matrix from spherical parameters
virtual void computeViewMatrix();
// call these functions when mouse input is captured
virtual void mouseMove(int x, int y);
};
#endif // SPHERICALCAMERA_H
| 31.84375 | 80 | 0.62316 | 3.109375 |
7a54be51516aa7c2f4db7682d73ab8f41897fd3d
| 2,083 |
sql
|
SQL
|
Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql
|
osu-cass/usda-plant-breeding
|
4163aaeb87f7e3934aca80298582639c60b458c2
|
[
"MIT"
] | 2 |
2020-01-07T07:39:59.000Z
|
2020-02-19T19:41:11.000Z
|
Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql
|
osu-cass/usda-plant-breeding
|
4163aaeb87f7e3934aca80298582639c60b458c2
|
[
"MIT"
] | 12 |
2019-08-15T16:33:32.000Z
|
2022-03-02T05:09:46.000Z
|
Usda.PlantBreeding.Database/dbo/Stored Procedures/GetPhenotypeEntry.sql
|
osu-cass/usda-plant-breeding
|
4163aaeb87f7e3934aca80298582639c60b458c2
|
[
"MIT"
] | 1 |
2019-08-09T18:03:24.000Z
|
2019-08-09T18:03:24.000Z
|
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetPhenotypeEntry]
@Year varchar(5),
@MapId int,
@GenotypeId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select mcy.Id [MapCompYearId], mc.GenotypeId, a.Text, q.Label, mc.Row, mc.PlantNum, a.Id [answerId], q.[Order], Maps.PicklistPrefix, mc.PickingNumber PickingNumber, mc.ExternalId, mc.PlantsInRep, mc.Rep
,ISNULL(NULLIF(femaleGenotype.GivenName, ' '), femaleGenotype.OriginalName) as [FemaleGenotypeName], ISNULL(NULLIF(maleGenotype.GivenName, ' '), maleGenotype.OriginalName) as [MaleGenotypeName]
, ISNULL(NULLIF(g.GivenName, ' '), g.OriginalName) as [GenotypeName]
, mcy.Comments
, fct.Name [CrossTypeName]
, Maps.Name [MapName]
, Years.[Year] [YearName]
, STUFF((
Select ', ' + Fates.Label
From MapComponentYearsFate
Inner Join Fates
on Fates.Id = MapComponentYearsFate.Fates_Id
where MapComponentYearsFate.MapComponentYears_Id = mcy.Id
order by 1
for xml path('')
), 1, 1, '' ) AS [Fates]
from Maps
Inner Join MapQuestion mq
on mq.Maps_Id = Maps.Id
Inner Join Questions q
on q.Id = mq.Questions_Id
Inner Join MapComponents mc
on mc.MapId = Maps.Id
Inner Join MapComponentYears mcy
on mcy.MapComponentId = mc.Id
Inner Join Years
on Years.Id = mcy.YearsId
Left Join Answers a
on a.MapComponentYearsId = mcy.Id
and a.QuestionId = q.Id
Left Join Genotypes g
on mc.GenotypeId = g.Id
Left Join Families f
on g.FamilyId = f.Id
Left Join CrossTypes fct
on fct.Id = f.CrossTypeId
Left Join Genotypes femaleGenotype
on f.FemaleParent = femaleGenotype.Id
Left Join Genotypes maleGenotype
on f.MaleParent = maleGenotype.Id
where
ISNULL(@GenotypeId, g.Id) = g.Id
and ISNULL(@MapId, mc.MapId) = mc.MapId
and ISNULL(@Year, Years.[Year]) = Years.[Year]
and mc.isSeedling = 0
Order By Years.[Year] Desc, mc.GenotypeId, Row, PlantNum, q.Label
END
| 27.051948 | 203 | 0.704273 | 3.015625 |
8b28a41849148096a6ffac4bb8e559a93375d4c0
| 2,013 |
asm
|
Assembly
|
HW_Example/h701.asm
|
smallru8/smallMasmLib
|
5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74
|
[
"BSD-3-Clause"
] | null | null | null |
HW_Example/h701.asm
|
smallru8/smallMasmLib
|
5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74
|
[
"BSD-3-Clause"
] | null | null | null |
HW_Example/h701.asm
|
smallru8/smallMasmLib
|
5c6e525a9867ecf82fa0db98d0a46c8b00c1ec74
|
[
"BSD-3-Clause"
] | null | null | null |
TITLE (.asm)
INCLUDE Irvine32.inc
INCLUDE Macros.inc
.data
MAX = 100
string1 BYTE MAX+1 DUP(0)
string2 BYTE MAX+1 DUP(0)
.code
main PROC
LOCAL ediLen:DWORD
mWrite "Destination string : "
mov edx,OFFSET string1
mov ecx,MAX
call ReadString
mov edi,OFFSET string1
mov esi,edi
call strlen
mov ediLen,eax
mWrite "Search string : "
mov edx,OFFSET string2
mov ecx,MAX
call ReadString
mov esi,OFFSET string2
call strstr
mWrite "Search result : "
.IF eax > ediLen
mWrite "NO found."
.ELSE
mWrite "OK."
.ENDIF
call crlf
mWrite "Append string : "
mov edx,OFFSET string2
mov ecx,MAX
call ReadString
mov edi,OFFSET string1
mov esi,OFFSET string2
call strcat
mov edx,edi
mWrite "After appending : "
call WriteString
call crlf
exit
main ENDP
;====================
;在字串1中搜尋字串2
;輸入 edi : 字串1
;輸入 esi : 字串2
;輸出 eax : 在字串1的位置
;====================
strstr PROC USES ecx
LOCAL esiPtr:DWORD
LOCAL ediPtr:DWORD
LOCAL esiLen:DWORD
LOCAL ediLen:DWORD
mov esiPtr,esi
mov ediPtr,edi
call strlen
inc eax;加上null byte
mov esiLen,eax
xchg esi,edi
call strlen
inc eax;加上null byte
mov ediLen,eax
xchg esi,edi
mov eax,0
L1:
cmp eax,ediLen
jg Return
cld
mov ecx,esiLen
repe cmpsb
cmp ecx,0
je Return
inc eax
mov edi,ediPtr
mov esi,esiPtr
add edi,eax
jmp L1
Return:
mov edi,ediPtr
mov esi,esiPtr
ret
strstr ENDP
;====================
;取得字串長度
;輸入 esi : 字串
;輸出 eax : 字串長度
;====================
strlen PROC USES edi
mov edi,esi
mov eax,0
L1:
cmp BYTE PTR [edi],0
je Return
inc edi
inc eax
jmp L1
Return:
ret
strlen ENDP
;====================
;將字串2接在字串1後面
;輸入 edi : 字串1
;輸入 esi : 字串2
;====================
strcat PROC USES eax ecx
push edi
push esi
xchg esi,edi
call strlen
xchg esi,edi
add edi,eax
call strlen
mov ecx,eax
inc ecx;加上null byte
cld
rep movsb
pop esi
pop edi
ret
strcat ENDP
END main
| 15.022388 | 32 | 0.61997 | 3.203125 |
d421c42349849498ab3e1d29c139d8c831424d0b
| 3,210 |
rs
|
Rust
|
rust/day01/depths_window/src/main.rs
|
kyclark/advent2021
|
b7961ffb7eca3a64b826424ceb9f6c628d7b046c
|
[
"MIT"
] | 1 |
2021-12-01T21:32:19.000Z
|
2021-12-01T21:32:19.000Z
|
rust/day01/depths_window/src/main.rs
|
kyclark/advent2021
|
b7961ffb7eca3a64b826424ceb9f6c628d7b046c
|
[
"MIT"
] | null | null | null |
rust/day01/depths_window/src/main.rs
|
kyclark/advent2021
|
b7961ffb7eca3a64b826424ceb9f6c628d7b046c
|
[
"MIT"
] | null | null | null |
use clap::{App, Arg};
use std::{
error::Error,
fs::File,
io::{self, BufRead, BufReader},
};
type MyResult<T> = Result<T, Box<dyn Error>>;
#[derive(Debug)]
pub struct Config {
filename: String,
window: usize,
}
// --------------------------------------------------
pub fn get_args() -> MyResult<Config> {
let matches = App::new("depths")
.version("0.1.0")
.author("Ken Youens-Clark <[email protected]>")
.about("Detect depths increasing/decreasing")
.arg(
Arg::with_name("filename")
.value_name("FILE")
.help("Input data file")
.default_value("-"),
)
.arg(
Arg::with_name("window")
.short("w")
.long("window")
.value_name("WINDOW")
.help("Window size")
.default_value("3"),
)
.get_matches();
let window = matches
.value_of("window")
.map(parse_positive_int)
.transpose()
.map_err(|e| format!("Invalid window \"{}\"", e))?;
Ok(Config {
filename: matches.value_of("filename").unwrap().to_string(),
window: window.unwrap(),
})
}
// --------------------------------------------------
fn parse_positive_int(val: &str) -> MyResult<usize> {
match val.parse() {
Ok(n) if n > 0 => Ok(n),
_ => Err(From::from(val)),
}
}
// --------------------------------------------------
#[test]
fn test_parse_positive_int() {
// 3 is an OK integer
let res = parse_positive_int("3");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 3);
// Any string is an error
let res = parse_positive_int("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "foo".to_string());
// A zero is an error
let res = parse_positive_int("0");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "0".to_string());
}
// --------------------------------------------------
fn main() -> MyResult<()> {
let args = get_args()?;
match open(&args.filename) {
Err(err) => eprintln!("{}: {}", args.filename, err),
Ok(file) => {
let mut num_increased = 0;
let mut prev = vec![];
for line in file.lines() {
let line = line?;
if let Ok(num) = line.parse::<usize>() {
if prev.len() == args.window {
let prev_sum: usize = prev.iter().sum();
prev.remove(0);
prev.push(num);
let this_sum: usize = prev.iter().sum();
if prev_sum < this_sum {
num_increased += 1;
}
} else {
prev.push(num);
}
}
}
println!("{} increased", num_increased);
}
}
Ok(())
}
fn open(filename: &str) -> MyResult<Box<dyn BufRead>> {
match filename {
"-" => Ok(Box::new(BufReader::new(io::stdin()))),
_ => Ok(Box::new(BufReader::new(File::open(filename)?))),
}
}
| 28.157895 | 68 | 0.443614 | 3.140625 |
e3ff145676e6e12a8193d5bc5a9d9172afeef331
| 1,495 |
go
|
Go
|
pkg/util/conv.go
|
RickyC0626/loki
|
3d941ccccbcc6109224dce1845f7aaead30d5ddf
|
[
"Apache-2.0"
] | null | null | null |
pkg/util/conv.go
|
RickyC0626/loki
|
3d941ccccbcc6109224dce1845f7aaead30d5ddf
|
[
"Apache-2.0"
] | null | null | null |
pkg/util/conv.go
|
RickyC0626/loki
|
3d941ccccbcc6109224dce1845f7aaead30d5ddf
|
[
"Apache-2.0"
] | null | null | null |
package util
import (
"time"
"unsafe"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
)
// ModelLabelSetToMap convert a model.LabelSet to a map[string]string
func ModelLabelSetToMap(m model.LabelSet) map[string]string {
if len(m) == 0 {
return map[string]string{}
}
return *(*map[string]string)(unsafe.Pointer(&m))
}
// MapToModelLabelSet converts a map into a model.LabelSet
func MapToModelLabelSet(m map[string]string) model.LabelSet {
if len(m) == 0 {
return model.LabelSet{}
}
return *(*map[model.LabelName]model.LabelValue)(unsafe.Pointer(&m))
}
// RoundToMilliseconds returns milliseconds precision time from nanoseconds.
// from will be rounded down to the nearest milliseconds while through is rounded up.
func RoundToMilliseconds(from, through time.Time) (model.Time, model.Time) {
fromMs := from.UnixNano() / int64(time.Millisecond)
throughMs := through.UnixNano() / int64(time.Millisecond)
// add a millisecond to the through time if the nanosecond offset within the second is not a multiple of milliseconds
if int64(through.Nanosecond())%int64(time.Millisecond) != 0 {
throughMs++
}
return model.Time(fromMs), model.Time(throughMs)
}
// LabelsToMetric converts a Labels to Metric
// Don't do this on any performance sensitive paths.
func LabelsToMetric(ls labels.Labels) model.Metric {
m := make(model.Metric, len(ls))
for _, l := range ls {
m[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
return m
}
| 29.9 | 118 | 0.742475 | 3.125 |
85b1af5aefd5017782d607c2078d8a01f5616a0c
| 5,976 |
js
|
JavaScript
|
Helpers/FileUploader/fileuploader.js
|
alexidr9116/bib-123
|
2cbdae10307610f6df1bc62d43e1dcb01de55846
|
[
"MIT"
] | null | null | null |
Helpers/FileUploader/fileuploader.js
|
alexidr9116/bib-123
|
2cbdae10307610f6df1bc62d43e1dcb01de55846
|
[
"MIT"
] | null | null | null |
Helpers/FileUploader/fileuploader.js
|
alexidr9116/bib-123
|
2cbdae10307610f6df1bc62d43e1dcb01de55846
|
[
"MIT"
] | null | null | null |
const multer = require("multer");
const formidable = require("formidable");
const fs = require("fs");
const path = require("path");
const Global = require("../Global");
const Response = require("../Response");
const imageStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/images",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
const videoStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/videos",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
const pdfStorage = multer.diskStorage({
// Destination to store image
destination: "./uploads/files",
filename: (req, file, cb) => {
cb(
null,
file.fieldname +
"x" +
Global.randomNumber(6) +
"c" +
Date.now() +
path.extname(file.originalname)
);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
},
});
var imageUpload = multer({
storage: imageStorage,
limits: {
fileSize: 1000000, // 1000000 Bytes = 1 MB
},
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(png|jpg)$/)) {
// upload only png and jpg format
return cb(new Error("Please upload a Image"));
}
cb(null, true);
},
});
const videoUpload = multer({
storage: videoStorage,
limits: {
fileSize: 10000000, // 10000000 Bytes = 10 MB
},
fileFilter(req, file, cb) {
// upload only mp4 and mkv format
if (!file.originalname.match(/\.(mp4|MPEG-4|mkv)$/)) {
return cb(new Error("Please upload a video"));
}
cb(null, true);
},
});
// const pdfFilter = (req, file, cb) => {
// if (file.mimetype.split("/")[1] === "pdf") {
// cb(null, true);
// } else {
// cb(new Error("Not a PDF File!!"), false);
// }
// };
const pdfUpload = multer({
storage: pdfStorage,
limits: {
fileSize: 10000000, // 10000000 Bytes = 10 MB
},
fileFilter(req, file, cb) {
// upload only mp4 and mkv format
if (!file.originalname.match(/\.(pdf)$/)) {
return cb(new Error("Please upload a pdf file."));
}
cb(null, true);
},
});
// --------------------------------------
const _uploadDir_image = "uploads/images/";
const _uploadDir_videos = "uploads/videos/";
const _uploadDir_files = "uploads/files/";
const checkAndUploadImage = (req, res, next, fieldInfo, fieldsToCheck = []) => {
console.log(req.body)
const form = new formidable.IncomingForm({ multiples: true });
form.parse(req, function (err, fields, files) {
console.log("Files : ", files[fieldInfo.name].length);
var _next = true;
if (fieldsToCheck.length > 0) {
fieldsToCheck.forEach((element) => {
let _minLength = element.minLength ? element.minLength : 3;
// check validations
if (!fields[element.name] || fields[element.name] === "") {
_next = false;
return Response.error(res, element.name + " is required");
}
if (fields[element.name] && fields[element.name].length < _minLength) {
console.log(fields[element.name].length);
_next = false;
return Response.error(
res,
element.name +
" minimum length should be " +
_minLength +
" character long."
);
}
// end of check validations
});
}
if (_next) {
if (files[fieldInfo.name].length > 0) {
let _uploadedPaths = [];
let uploadDone = false;
files[fieldInfo.name].forEach((fileElement, index) => {
if (index < fieldInfo.maxCount) {
if (isFileValid(fileElement)) {
var oldPath = fileElement.filepath;
var newPath = _uploadDir_image + getFileName(fileElement);
fs.readFile(oldPath, (err, data) => {
if (err) return Response.error(res, err);
fs.writeFile(newPath, data, function (err) {
if (err) return Response.error(res, err);
_uploadedPaths.push(newPath);
if (
index === fieldInfo.maxCount - 1 ||
index === files[fieldInfo.name].length - 1
) {
uploadDone = true;
}
if (uploadDone && _uploadedPaths.length > 0) {
if (fieldInfo.maxCount === 1) {
req.body = fields;
req.uploadedPath = _uploadedPaths[0];
} else {
req.body = fields;
req.uploadedPath = _uploadedPaths;
}
next();
return true;
} else {
next();
return true;
}
});
});
}else{
Response.error(res, "Please upload image file.");
}
} else {
}
});
}
}
});
};
const isFileValid = (file) => {
if (!file.originalFilename.match(/\.(png|jpg|jpeg)$/)) {
return false;
}
return true;
};
const getFileName = (file) => {
return (
"image_" +
Global.randomNumber(6) +
Date.now() +
path.extname(file.originalFilename)
);
};
// --------------------------------------
module.exports = {
imageUpload,
videoUpload,
pdfUpload,
checkAndUploadImage,
};
| 27.666667 | 80 | 0.525435 | 3.234375 |
b51b8c180a527f860f003b278dac22b749fe86d5
| 6,399 |
swift
|
Swift
|
Sources/TCP/Socket/TCPServer.swift
|
captainOfM/sockets
|
734f148087a3bd649cf07afe224f7273d3da3438
|
[
"MIT"
] | 125 |
2017-03-24T12:15:09.000Z
|
2018-03-16T10:59:17.000Z
|
Sources/TCP/Socket/TCPServer.swift
|
captainOfM/sockets
|
734f148087a3bd649cf07afe224f7273d3da3438
|
[
"MIT"
] | 43 |
2016-09-09T16:04:58.000Z
|
2017-03-17T09:29:01.000Z
|
Sources/TCP/Socket/TCPServer.swift
|
captainOfM/sockets
|
734f148087a3bd649cf07afe224f7273d3da3438
|
[
"MIT"
] | 25 |
2016-09-09T13:23:48.000Z
|
2017-03-17T16:02:44.000Z
|
import Async
import Bits
import Debugging
import Dispatch
import COperatingSystem
/// Accepts client connections to a socket.
///
/// Uses Async.OutputStream API to deliver accepted clients
/// with back pressure support. If overwhelmed, input streams
/// can cause the TCP server to suspend accepting new connections.
///
/// [Learn More →](https://docs.vapor.codes/3.0/sockets/tcp-server/)
public struct TCPServer {
/// A closure that can dictate if a client will be accepted
///
/// `true` for accepted, `false` for not accepted
public typealias WillAccept = (TCPClient) -> (Bool)
/// Controls whether or not to accept a client
///
/// Useful for security purposes
public var willAccept: WillAccept?
/// This server's TCP socket.
public let socket: TCPSocket
/// Creates a TCPServer from an existing TCPSocket.
public init(socket: TCPSocket) throws {
self.socket = socket
}
/// Starts listening for peers asynchronously
public func start(hostname: String = "0.0.0.0", port: UInt16, backlog: Int32 = 128) throws {
/// bind the socket and start listening
try socket.bind(hostname: hostname, port: port)
try socket.listen(backlog: backlog)
}
/// Accepts a client and outputs to the output stream
/// important: the socket _must_ be ready to accept a client
/// as indicated by a read source.
public mutating func accept() throws -> TCPClient? {
guard let accepted = try socket.accept() else {
return nil
}
/// init a tcp client with the socket and assign it an event loop
let client = try TCPClient(socket: accepted)
/// check the will accept closure to approve this connection
if let shouldAccept = willAccept, !shouldAccept(client) {
client.close()
return nil
}
/// output the client
return client
}
/// Stops the server
public func stop() {
socket.close()
}
}
extension TCPServer {
/// Create a stream for this TCP server.
/// - parameter on: the event loop to accept clients on
/// - parameter assigning: the event loops to assign to incoming clients
public func stream(on eventLoop: EventLoop) -> TCPClientStream {
return .init(server: self, on: eventLoop)
}
}
extension TCPSocket {
/// bind - bind a name to a socket
/// http://man7.org/linux/man-pages/man2/bind.2.html
fileprivate func bind(hostname: String = "0.0.0.0", port: UInt16) throws {
var hints = addrinfo()
// Support both IPv4 and IPv6
hints.ai_family = AF_INET
// Specify that this is a TCP Stream
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
// If the AI_PASSIVE flag is specified in hints.ai_flags, and node is
// NULL, then the returned socket addresses will be suitable for
// bind(2)ing a socket that will accept(2) connections.
hints.ai_flags = AI_PASSIVE
// Look ip the sockeaddr for the hostname
var result: UnsafeMutablePointer<addrinfo>?
var res = getaddrinfo(hostname, port.description, &hints, &result)
guard res == 0 else {
throw TCPError.gaierrno(
res,
identifier: "getAddressInfo",
possibleCauses: [
"The address that binding was attempted on (\"\(hostname)\":\(port)) does not refer to your machine."
],
suggestedFixes: [
"Bind to `0.0.0.0` or to your machine's IP address"
],
source: .capture()
)
}
defer {
freeaddrinfo(result)
}
guard let info = result else {
throw TCPError(identifier: "unwrapAddress", reason: "Could not unwrap address info.", source: .capture())
}
res = COperatingSystem.bind(descriptor, info.pointee.ai_addr, info.pointee.ai_addrlen)
guard res == 0 else {
throw TCPError.posix(errno, identifier: "bind", source: .capture())
}
}
/// listen - listen for connections on a socket
/// http://man7.org/linux/man-pages/man2/listen.2.html
fileprivate func listen(backlog: Int32 = 4096) throws {
let res = COperatingSystem.listen(descriptor, backlog)
guard res == 0 else {
throw TCPError.posix(errno, identifier: "listen", source: .capture())
}
}
/// accept, accept4 - accept a connection on a socket
/// http://man7.org/linux/man-pages/man2/accept.2.html
fileprivate func accept() throws -> TCPSocket? {
let (clientfd, address) = try TCPAddress.withSockaddrPointer { address -> Int32? in
var size = socklen_t(MemoryLayout<sockaddr>.size)
let descriptor = COperatingSystem.accept(self.descriptor, address, &size)
guard descriptor > 0 else {
switch errno {
case EAGAIN: return nil // FIXME: enum return
default: throw TCPError.posix(errno, identifier: "accept", source: .capture())
}
}
return descriptor
}
guard let c = clientfd else {
return nil
}
let socket = TCPSocket(
established: c,
isNonBlocking: isNonBlocking,
shouldReuseAddress: shouldReuseAddress,
address: address
)
return socket
}
}
extension TCPError {
static func gaierrno(
_ gaires: Int32,
identifier: String,
possibleCauses: [String] = [],
suggestedFixes: [String] = [],
source: SourceLocation
) -> TCPError {
guard gaires != EAI_SYSTEM else {
return .posix(
errno,
identifier: identifier,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
source: source
)
}
let message = COperatingSystem.gai_strerror(gaires)
let string = String(cString: message!, encoding: .utf8) ?? "unknown"
return TCPError(
identifier: identifier,
reason: string,
possibleCauses: possibleCauses,
suggestedFixes: suggestedFixes,
source: source
)
}
}
| 32.318182 | 121 | 0.597437 | 3.046875 |
16d4ac8e5bf2a579c73c9e8099a2d161a96e3333
| 18,277 |
lua
|
Lua
|
CollectionAgent.lrdevplugin/Framework/System/Updater.lua
|
Greven-of-Norway/RC_CollectionAgent
|
ad3872263aad8ccc5a12eb17ae07e98cdae6d51d
|
[
"Artistic-2.0"
] | 5 |
2017-07-02T22:58:14.000Z
|
2022-01-08T15:44:38.000Z
|
FileRenamer.lrplugin/Framework/System/Updater.lua
|
DaveBurns/rc_FileRenamer
|
1c346969db84172339df6254554b49268513f68b
|
[
"Artistic-2.0"
] | null | null | null |
FileRenamer.lrplugin/Framework/System/Updater.lua
|
DaveBurns/rc_FileRenamer
|
1c346969db84172339df6254554b49268513f68b
|
[
"Artistic-2.0"
] | 3 |
2017-10-04T22:26:20.000Z
|
2018-09-23T03:10:44.000Z
|
--[[
Updater.lua
Note: this could encapsulate check-for-update and uninstall too, but doesn't, yet.
Initial motivation is so plugin can customize updating without extending app object.
--]]
local Updater, dbg, dbgf = Object:newClass{ className= 'Updater', register=true }
--- Constructor for extending class.
--
-- @param t initial table - optional.
--
function Updater:newClass( t )
return Object.newClass( self, t )
end
--- Constructor for new instance object.
--
-- @param t initial table - optional.
--
-- @usage Construct new updater with the default of no copy exclusions, and excluding preferences from being seen as extraneous and purging.
--
function Updater:new( t )
local o = Object.new( self, t )
o.copyExcl = o.copyExcl or {} -- no default copy protection.
if o.purgeExcl then
-- explicit purge exclusions
else
o.purgeExcl = { "^Preferences[\\/]", "^Settings[\\/]" } -- don't purge preferences or settings.
end
return o
end
--- Migrate special plugin files.
--
-- @usage In case some files require special handling instead of just copying.<br>
-- Prime examples are auto-generated metadata module files.<br>
-- Excludes preferences which are handled more specifically (see migrate-prefs method).
--
function Updater:migrateSpecials()
local errs = 0
-- self.service.scope:setCaption( "Copying files" )
return errs
end
--- Migrate plugin preferences.
--
-- @usage Default implementation simply transfers plugin preference backing files.<br>
-- Override in extended class to translate legacy preferences (backed or reglar) to new, if desired.
--
-- @return number of errors encountered.
--
function Updater:migratePrefsAndSets( subdir )
if self.me == self.target then
app:log( "Not migrating prefs/sets since I'm the target." )
return 0
end
app:log( "Considering migration of '^1'", subdir )
local mePrefDir = LrPathUtils.child( self.me, subdir )
local destPrefDir = LrPathUtils.child( self.target, subdir ) -- dest is synoymous with target.
local errs = 0
if fso:existsAsDir( mePrefDir ) then
if fso:existsAsDir( destPrefDir ) then -- updating plugin supports pref backing too
local count = 0
for filePath in LrFileUtils.recursiveFiles( mePrefDir ) do
self.service.scope:setCaption( "Copying files" ) -- this needs to be there to "goose" the delayed progress indicator, but I'm not trying to give too much info.
local leaf = LrPathUtils.leafName( filePath )
local name = LrPathUtils.removeExtension( leaf )
local destPath = LrPathUtils.child( destPrefDir, leaf )
if name ~= 'Default' then
count = count + 1
local overwrite
if fso:existsAsFile( destPath ) then
app:log( "Overwriting named pref/sets file: " .. destPath )
overwrite = true
else
overwrite = false
end
local s, m = fso:copyFile( filePath, destPath, false, overwrite ) -- pref directory pre-verified.
Debug.logn( filePath, destPath )
if s then
app:log( "Migrated pref/sets backing file from ^1 to ^2", filePath, destPath )
else
app:logError( "Unable to migrate pref support file: " .. m )
errs = errs + 1
end
else
app:log( "Not migrated default pref/sets backing file ^1 to ^2", filePath, destPath )
end
end
if count == 0 then
app:log( "No named pref/sets found to migrate." )
end
else
app:log( "Updated plugin does not support pref/sets backing, ignoring source pref/sets backing files - please visit plugin manager to update configuration." )
end
else
app:log( "No source pref/sets to migrate" )
end
return errs
end
--- Determine if a particular sub-path is to be excluded from copying from source of update to target.
--
-- @param f sub-path relative to lrplugin dir
--
function Updater:isCopyExcluded( f )
for i, v in ipairs( self.copyExcl ) do
if f:find( v ) then
return true
end
end
return false
end
--- Determine if a particular sub-path is to be excluded from purging from updated target.
--
-- @param f sub-path relative to lrplugin dir
--
function Updater:isPurgeExcluded( f )
for i, v in ipairs( self.purgeExcl ) do
if f:find( v ) then
return true
end
end
return false
end
--- Sync source tree to target tree.
--
function Updater:syncTree()
local errs = 0
for src in LrFileUtils.recursiveFiles( self.src ) do
self.service.scope:setCaption( "Copying files" )
local subPath = LrPathUtils.makeRelative( src, self.src )
local dest = LrPathUtils.child( self.target, subPath )
if not self:isCopyExcluded( subPath ) then
local s, m = fso:copyFile( src, dest, true, true )
if s then
app:log( "Copied ^1 to ^2", src, dest )
else
errs = errs + 1
app:log( "Unable to copied plugin file, error message: ^1", m )
end
else
app:log( "Excluded from copy: " .. subPath )
end
end
local extras = {}
for dest in LrFileUtils.recursiveFiles( self.target ) do
self.service.scope:setCaption( "Copying files" ) -- not exactly correct, but...
local subPath = LrPathUtils.makeRelative( dest, self.target )
local src = LrPathUtils.child( self.src, subPath )
if not self:isPurgeExcluded( subPath ) then
if not fso:existsAsFile( src ) then
extras[#extras + 1] = dest
app:log( "Extraneous: " .. dest )
end
else
app:log( "Excluded from purge: " .. subPath )
end
end
if #extras > 0 then
app:log( "^1 in ^2", str:plural( #extras, "extraneous file" ), self.target )
local answer
repeat
if app:logVerbose() or app:isAdvDbgEna() or ( app:getUserName() == '_RobCole_' ) then
answer = app:show{ confirm="Extraneous files have been found in ^1, ok to delete?\n \nSee log file for details.",
buttons={ dia:btn( "Yes - OK to delete", 'ok' ), dia:btn( "Show Log File", 'showLogs' ), dia:btn( "No - Keep them", 'cancel' ) }, subs=self.target }
else
answer = 'ok'
end
if answer == 'ok' then
for i, v in ipairs( extras ) do
local s, m = fso:moveToTrash( v )
if s then
app:log( "Moved to trash or deleted ^1", v )
else
errs = errs + 1
app:logErr( "Unable to move extraneous plugin file to trash, error message: ^1", m )
end
end
break
elseif answer == 'showLogs' then
app:showLogFile()
elseif answer == 'cancel' then
break
else
error( "bad answer: " .. answer )
end
until false
else
app:log( "No extraneous files in ^1 to move to trash.", self.target )
end
return errs
end
--- Updates plugin to new version (must be already downloaded/available).
--
function Updater:updatePlugin()
app:call( Service:new{ name = 'Update Plugin', async=true, guard=App.guardVocal, main=function( service )
-- Its legal to have two copies of the same plugin installed, but only one can be enabled.
-- so make sure its the enabled one that's being updated.
self.service = service
if app:isPluginEnabled() then
-- good
else
app:show{ warning="Plugin must be enabled to be updated." }
service:cancel()
return
end
if gbl:getValue( 'background' ) then -- global background object, as distinguished from background-enable pref of same name.
local button = app:show{ confirm="To proceed with update, background processing must be shutdown, and you may need to reload plugin afterward - proceed?" }
if button == 'ok' then
service:setMandatoryMessage( "*** Plugin may need to be reloaded." )
app:log( "*** Plugin may need to be reloaded." )
elseif button == 'cancel' then
service:cancel()
return
else
error( "bad button" )
end
app:showBezel( { dur=3, holdoff=1 }, "Stopping background processing - please wait (up to 30 seconds, but probably much less)..." ) -- note: bezel won't work if shutting down.
background.done = true -- shutdown would be more effective, but that causes pause to return prematurely. Long running background tasks, like FTP sync, should check this flag along with others.
local s, m = background:pause( 30 ) -- Might be better to stop instead of pausing, but @25/Jan/2014 17:27, stopping is not as robust as pausing is - pause just as good for all practical purposes though, I think.
-- note: @25/Jan/2014 19:15, background has auto-retry until succeed or user quit's trying (by choosing "No", not "Cancel").
background.done = false
if s then
app:showBezel( { dur=1, holdoff=2 }, "Background processing is paused for sake of plugin update." ) -- hold-off longer than duration, so message is cleared before OS chooser is displayed.
-- for some reason, a holdoff of 1.5 is not cutting it - hmm...
else
app:logErr( "Unable to pause background processing for sake of update, error message: ^1\n \nDisable background processing, re-load plugin, then try upating plugin again.", m )
service:abort( "Unable to pause background processing" ) -- may be something useful in log file.
return
end
end
local id = app:getPluginId()
local dir
if app:getUserName() == '_RobCole_' then
if app:isAdvDbgEna() then
dir = "X:\\Dev\\LightroomPlugins\\RC_ExifMeta\\ReleasePackageContents\\ExifMeta.lrplugin"
else
dir = "X:\\Dev\\LightroomPlugins"
end
else
dir = "/"
end
--self.src = dia:selectFolder { -- source of the update ###2 - test on Mac (Paula P. said stuff was disabled, as did another Mac user - hmm... - probably should be "file" not folder)
self.src = dia:selectPackage { -- changed 1/Jun/2014 18:15 - select-file on Mac, select folder in Windows.
title = "Choose newly downloaded (and unzipped) plugin folder (name must end with .lrplugin)",
-- 'prompt' ignored by (OS) folder chooser.
initialDirectory = dir,
fileTypes = { "lrplugin", "lrdevplugin" }, -- ignored by OS chooser, but respected by select-folder method.
}
if self.src then
local appData = LrPathUtils.getStandardFilePath( 'appData' ) -- ###2 get-preset-dir?
assert( fso:existsAsDir( appData ), "Where's Lr app-data?" )
local modulesPath = LrPathUtils.child( appData, "Modules" ) -- may or may not already exist.
if fso:existsAsDir( modulesPath ) then
app:log( "Updating in existing modules directory: " .. modulesPath )
else
local s, m = fso:assureAllDirectories( modulesPath )
if s then
app:log( "Updating into freshly created modules directory: " .. modulesPath )
else
error( "Unable to directory for updated plugin: " .. str:to( m ) )
end
end
self.name = LrPathUtils.leafName( self.src ) -- name of the update
self.base = LrPathUtils.removeExtension( self.name ) -- base-name of the update
self.me = _PLUGIN.path -- identity of the plugin doing the updating.
self.target = LrPathUtils.child( modulesPath, self.name )
if self.src == self.me then
local parent = LrPathUtils.parent( self.src )
if parent ~= modulesPath then
if dia:isOk( "Are you sure you want to update the same plugin?\n \nthus effectively moving it to " .. modulesPath ) then
app:log( "Moving plugin to lr-modules dir: " .. self.target )
else
service:cancel()
return
end
else
app:show{ warning="Source plugin selected (^1) is this one, and is already running from Lightroom modules directory - can't update it: maybe try selecting a different one.", self.src }
service:cancel()
return
end
end
if self.src == self.target then
app:logError( "Source plugin must not already reside in target directory." )
return
end
if self.base ~= str:getBaseName( _PLUGIN.path ) then
if not dia:isOk( "Source plugin has different filename - are you sure its the same plugin?" ) then
service:cancel()
return
end
end
if fso:existsAsDir( self.target ) then
local answer
if self.me == self.target then
app:log( "Plugin updating itself: " .. self.target )
else
app:log( "Plugin updating a foreign instance: " .. self.target )
answer = app:show{ confirm="OK to overwrite ^1?", subs=self.target, buttons={ dia:btn( "OK", 'ok' ) } }
if answer == 'ok' then
-- just proceed to update.
elseif answer == 'cancel' then
service:cancel()
return
else
error( "bad answer" )
end
end
else
app:log( "Updating ^1 for first time to ^2", app:getPluginName(), self.target )
end
assert( self.src, "no src" )
assert( self.target, "no target" )
service.scope = DelayedProgressScope:new {
title = "Updating plugin",
functionContext = service.context,
modal = true,
}
local s, m = self:syncTree() -- copy/overwrite files, except for exclusions, then delete the rest.
if s then
local errs = 0
errs = errs + self:migratePrefsAndSets( 'Preferences' )
errs = errs + self:migratePrefsAndSets( 'Settings' )
errs = errs + self:migrateSpecials()
if errs > 0 then
error( "Errors occurred, update not successful: see log file for details." )
end
if self.me ~= self.target then -- running plugin is not in modules folder, so it was updated from somewhere else.
local notMe = self.me .. "." .. app:getVersionString()
local s, m = fso:moveFolderOrFile( self.me, notMe ) -- can cause strange errors under unusual circumstances.
service.scope:setCaption( "Done" )
service.scope:done()
LrTasks.yield()
if not s then
app:log( "Unable to rename previous plugin, error message: ", m )
app:show{ error="Unable to rename original plugin from ^1 to ^2.\n \nAlthough its not necessary for the updated plugin to work, you will have two versions of plugin installed - take care which is enabled.", self.me, notMe }
else
app:log( "Previous plugin was renamed: " .. notMe )
end
app:log( "Update was successful - after restarting, revisit plugin manager (status section) and make sure ^1 is enabled (click 'Enable' button if need be).", app:getPluginName() )
app:show{ info="Update was successful - You must restart Lightroom now, then revisit plugin manager and make sure ^1 is enabled (click 'Enable' button if need be).", app:getPluginName() }
service:cancel("") -- kill normal service ending message if update was successful (to avoid extraneous error messages)
else -- running plugin is in modules folder, so was updated in place.
service.scope:setCaption( "Done" )
service.scope:done()
LrTasks.yield()
if WIN_ENV then
app:show{ info="^1 update successful - either reload plugin (see plugin author section), or restart Lightroom now.", app:getPluginName() }
else
app:show{ info="^1 update successful - restart Lightroom now.", app:getPluginName() }
end
service:cancel("") -- haven't seen extraneous error messages in this case, but rather not take a chance...
end
else
error( m )
end
else -- user did not select a plugin for updating.
if gbl:getValue( 'background' ) then
app:show{ warning="You probably need to reload the plugin now - see \"Plugin Author Tools\" section here in plugin manager." }
end
service:cancel()
end
end } )
end
return Updater
| 46.037783 | 247 | 0.561142 | 3.140625 |
541dc3f6fe7bf5abd9c6ea7f9629edb0f96ed3b7
| 1,624 |
go
|
Go
|
pkg/utils/aes.go
|
cxz66666/xms-go
|
125b11734cb8b2d58bae08be8513825bb8f60bde
|
[
"MIT"
] | null | null | null |
pkg/utils/aes.go
|
cxz66666/xms-go
|
125b11734cb8b2d58bae08be8513825bb8f60bde
|
[
"MIT"
] | null | null | null |
pkg/utils/aes.go
|
cxz66666/xms-go
|
125b11734cb8b2d58bae08be8513825bb8f60bde
|
[
"MIT"
] | null | null | null |
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
//PKCS7Padding use PKCS7 to padding
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext) % blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
//PKCS7UnPadding use PkCS7 to unpadding
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// AesCBCEncrypt use aes-cbc,pkcs7 padding to encrypt, support AES-128, AES-192, or AES-256.
func AesCBCEncrypt(origData []byte, key []byte, iv []byte) ([]byte, error) {
newKey:=make([]byte,16)
newIv:=make([]byte,16)
copy(newKey,key)
copy(newIv,iv)
block, err := aes.NewCipher(newKey)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
//使用cbc
blocMode := cipher.NewCBCEncrypter(block, newIv)
encrypted := make([]byte, len(origData))
blocMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
// AesCBCDecrypt use decrypt the content, like its name
func AesCBCDecrypt(cypted []byte, key []byte, iv []byte) ([]byte, error) {
newKey:=make([]byte,16)
newIv:=make([]byte,16)
copy(newKey,key)
copy(newIv,iv)
block, err := aes.NewCipher(newKey)
if err != nil {
return nil, err
}
//使用key充当偏移量
blockMode := cipher.NewCBCDecrypter(block, newIv)
origData := make([]byte, len(cypted))
blockMode.CryptBlocks(origData, cypted)
origData = PKCS7UnPadding(origData)
if err != nil {
return nil, err
}
return origData, err
}
| 23.2 | 92 | 0.704433 | 3.171875 |
2a6006e21d06ae966cd56a02f3c596cee0ae00ed
| 876 |
java
|
Java
|
474/D.java
|
I-See-You/Programming-Solutions
|
e69d94586b1718256a6ff4d2e67f91bc98c64815
|
[
"MIT"
] | null | null | null |
474/D.java
|
I-See-You/Programming-Solutions
|
e69d94586b1718256a6ff4d2e67f91bc98c64815
|
[
"MIT"
] | null | null | null |
474/D.java
|
I-See-You/Programming-Solutions
|
e69d94586b1718256a6ff4d2e67f91bc98c64815
|
[
"MIT"
] | null | null | null |
import java.util.Scanner;
import java.util.Arrays;
public class Test1 {
public static void main(String[] args)
{
Scanner cin = new Scanner (System.in);
int t,k;
final int mod = 1000000007;
int[] dp = new int[100005];
t = cin.nextInt();
k = cin.nextInt();
dp[0] = 1;
for(int i=1;i<=100000;i++){
dp[i] = (dp[i] + dp[i-1]) % mod;
if(i >= k) dp[i] = (dp[i] + dp[i-k]) % mod;
}
dp[0] = 0;
for(int i=1;i<=100000;i++) dp[i] = (dp[i] + dp[i-1]) % mod;
while(t-- > 0){
int x,y;
x = cin.nextInt();
y = cin.nextInt();
int ans = dp[y] - dp[x-1];
ans = ans % mod;
if(ans < 0) ans += mod;
System.out.println(ans);
}
}
}
| 27.375 | 68 | 0.399543 | 3.0625 |
01429bf8d1becf7115262ab82d51ed3e5e849674
| 3,768 |
sql
|
SQL
|
dashboards/sql-page-timeframe/DateConversions.sql
|
admariner/samples-1
|
475bcb333ff2f7b486314827142d32d40b934fb5
|
[
"Apache-2.0"
] | 13 |
2021-06-16T20:49:16.000Z
|
2022-01-28T22:25:50.000Z
|
dashboards/sql-page-timeframe/DateConversions.sql
|
squaredup/samples
|
475bcb333ff2f7b486314827142d32d40b934fb5
|
[
"Apache-2.0"
] | 14 |
2021-06-16T20:01:09.000Z
|
2021-10-18T13:47:07.000Z
|
dashboards/sql-page-timeframe/DateConversions.sql
|
admariner/samples-1
|
475bcb333ff2f7b486314827142d32d40b934fb5
|
[
"Apache-2.0"
] | 12 |
2021-06-25T15:49:48.000Z
|
2022-01-28T02:13:43.000Z
|
IF OBJECT_ID(N'tempdb..#Native') IS NOT NULL DROP TABLE #Native;
--Create a temporary table to hold our display values
CREATE TABLE #Native ([Description] nvarchar(255)
, [strFormatted] nvarchar(255)
, [asDateTime] datetime
, [timeAgo] datetime
, [timeAgoDt] datetime
, [timeAgoHowLong] datetime )
--Insert some differnt types of date conversions using native SQL
--Current Date and Time
INSERT INTO #Native SELECT 'Current Date and Time', FORMAT (GETDATE(), 'yyyy-MM-dd hh:mm:ss tt'), GETDATE(), GETDATE(), GETDATE(), GETDATE()
--1 hour
INSERT INTO #Native SELECT 'StartDate -1 hour', FORMAT (DATEADD(HOUR, -1, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(HOUR, -1, GETDATE()), DATEADD(HOUR, -1, GETDATE()), DATEADD(HOUR, -1, GETDATE()), DATEADD(HOUR, -1, GETDATE())
--12 hours
INSERT INTO #Native SELECT 'StartDate -12 hour', FORMAT (DATEADD(HOUR, -12, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(HOUR, -12, GETDATE()), DATEADD(HOUR, -12, GETDATE()), DATEADD(HOUR, -12, GETDATE()), DATEADD(HOUR, -12, GETDATE())
--1 day
INSERT INTO #Native SELECT 'StartDate -24 hour', FORMAT (DATEADD(HOUR, -24, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(HOUR, -24, GETDATE()), DATEADD(HOUR, -24, GETDATE()), DATEADD(HOUR, -24, GETDATE()), DATEADD(HOUR, -24, GETDATE())
--7 days
INSERT INTO #Native SELECT 'StartDate -7 days', FORMAT (DATEADD(d, -7, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(d, -7, GETDATE()), DATEADD(d, -7, GETDATE()), DATEADD(d, -7, GETDATE()), DATEADD(d, -7, GETDATE())
--30 days
INSERT INTO #Native SELECT 'StartDate -30 days', FORMAT (DATEADD(d, -30, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(d, -30, GETDATE()), DATEADD(d, -30, GETDATE()), DATEADD(d, -30, GETDATE()), DATEADD(d, -30, GETDATE())
INSERT INTO #Native SELECT 'StartDate -1 months', FORMAT (DATEADD(MM, -1, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(MM, -1, GETDATE()), DATEADD(MM, -1, GETDATE()), DATEADD(MM, -1, GETDATE()), DATEADD(MM, -1, GETDATE())
--3 months (90 days)
INSERT INTO #Native SELECT 'StartDate -90 days', FORMAT (DATEADD(d, -90, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(d, -90, GETDATE()), DATEADD(d, -90, GETDATE()), DATEADD(d, -90, GETDATE()), DATEADD(d, -90, GETDATE())
INSERT INTO #Native SELECT 'StartDate -3 months', FORMAT (DATEADD(MM, -3, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(MM, -3, GETDATE()), DATEADD(MM, -3, GETDATE()), DATEADD(MM, -3, GETDATE()), DATEADD(MM, -3, GETDATE())
--6 months (180 days)
INSERT INTO #Native SELECT 'StartDate -6 months', FORMAT (DATEADD(MM, -6, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(MM, -6, GETDATE()), DATEADD(MM, -6, GETDATE()), DATEADD(MM, -6, GETDATE()), DATEADD(MM, -6, GETDATE())
--12 months (240 days)
INSERT INTO #Native SELECT 'StartDate -12 months', FORMAT (DATEADD(MM, -12, GETDATE()), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(MM, -12, GETDATE()), DATEADD(MM, -12, GETDATE()), DATEADD(MM, -12, GETDATE()), DATEADD(MM, -12, GETDATE())
--all data
INSERT INTO #Native SELECT 'StartDate All Days', FORMAT (convert(datetime,0), 'yyyy-MM-dd hh:mm:ss tt'), convert(datetime,0), convert(datetime,0),convert(datetime,0), convert(datetime,0)
--End Date
INSERT INTO #Native SELECT 'End Date', FORMAT (GETDATE(), 'yyyy-MM-dd hh:mm:ss tt'), GETDATE(), GETDATE(),GETDATE(), GETDATE()
--Midnight
INSERT INTO #Native SELECT 'Midnight', FORMAT (DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate())), 'yyyy-MM-dd hh:mm:ss tt'), DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate())),DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate())),DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate())),DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate()))
--Dump out the table for SquaredUp to display on the dashboard
SELECT * FROM #Native
| 72.461538 | 299 | 0.653397 | 3.1875 |
1a2be726f0342cdc0c637c8e4d3c28d0ef470c69
| 3,520 |
rs
|
Rust
|
src/cpu.rs
|
liushiqi/riscv-simulator
|
d05f060b2544da61a7ce39ebc9c7035bc3bfbd93
|
[
"MIT"
] | null | null | null |
src/cpu.rs
|
liushiqi/riscv-simulator
|
d05f060b2544da61a7ce39ebc9c7035bc3bfbd93
|
[
"MIT"
] | null | null | null |
src/cpu.rs
|
liushiqi/riscv-simulator
|
d05f060b2544da61a7ce39ebc9c7035bc3bfbd93
|
[
"MIT"
] | null | null | null |
use std::{
io::{stderr, Write},
ops::Range,
path::PathBuf,
};
use crate::{
device::{Bus, ReqType},
inst::decode_instruction,
isa::{Extension, Isa, XLen},
reg_file::{RegFile, RegIndex},
SimulateResult,
};
pub(crate) enum PcLength {
Four,
#[allow(unused)]
Two,
}
pub struct Cpu {
regs: RegFile<u64, false>,
pc: u64,
pc_len: PcLength,
isa: Isa,
bus: Bus,
debug: bool,
}
impl Cpu {
pub fn new(entry_point: u64, isa: Isa, bus: Bus, debug: bool) -> Self {
Self {
regs: RegFile::default(),
pc: entry_point,
pc_len: PcLength::Four,
isa,
bus,
debug,
}
}
pub fn execute(&mut self) {
loop {
let stderr = stderr();
let prev_pc = self.pc;
let instruction = self.read_addr(self.pc, ReqType::Word(0));
if let Ok(ReqType::Word(instruction)) = instruction {
let (inst, r#type) = decode_instruction(instruction, self);
self.pc_len = r#type;
if self.debug {
write!(
stderr.lock(),
"0x{:016x} (0x{:08x}) {}\n",
if self.get_xlen() == XLen::Bit32 { self.pc as u32 as u64 } else { self.pc },
instruction,
inst
)
.unwrap()
}
inst.exec(self);
if self.pc == prev_pc {
break
}
} else {
panic!("Instruction load failed.")
};
}
}
}
impl Cpu {
pub(crate) fn get_xlen(&self) -> XLen { self.isa.get_xlen() }
pub(crate) fn get_xlen_num(&self) -> u64 {
match self.isa.get_xlen() {
XLen::Bit32 => 32,
XLen::Bit64 => 64,
}
}
pub(crate) fn have_ext(&self, ext: Extension) -> bool { self.isa.have_ext(ext) }
pub(crate) fn get_pc(&self) -> u64 { self.pc }
pub(crate) fn get_next_pc(&self) -> u64 {
self.pc +
match self.pc_len {
PcLength::Four => 4,
PcLength::Two => 2,
}
}
pub(crate) fn jump_to(&mut self, destination: u64) { self.pc = destination & !1u64 }
pub(crate) fn next_pc(&mut self) {
self.pc += match self.pc_len {
PcLength::Four => 4,
PcLength::Two => 2,
}
}
pub(crate) fn read_reg(&self, reg: RegIndex) -> u64 { self.regs.read(reg) }
pub(crate) fn read_reg_zext(&self, reg: RegIndex) -> u64 {
if self.get_xlen() == XLen::Bit32 { self.regs.read(reg) as u32 as u64 } else { self.regs.read(reg) }
}
pub(crate) fn write_register(&mut self, reg: RegIndex, data: u64) {
if reg.0 != 0 {
self.regs.write(reg, if self.get_xlen() == XLen::Bit32 { data as i32 as u64 } else { data })
}
}
pub(crate) fn read_addr(&mut self, address: u64, size: ReqType) -> SimulateResult<ReqType> {
self.bus.read(if self.get_xlen() == XLen::Bit32 { address as u32 as u64 } else { address }, size)
}
pub(crate) fn write_addr(&mut self, address: u64, data: ReqType) -> SimulateResult<()> {
self.bus.write(if self.get_xlen() == XLen::Bit32 { address as u32 as u64 } else { address }, data)
}
}
impl Cpu {
#[allow(unused)]
pub fn get_data(&self, address: u64) -> u32 { self.bus.get_data(address) }
#[allow(unused)]
pub fn dump_ram_to_file(&self, to_file: PathBuf) -> SimulateResult<()> { self.bus.dump_ram_to_file(to_file) }
#[allow(unused)]
pub fn dump_ram_range(&self, range: Range<usize>) -> SimulateResult<Vec<String>> { self.bus.dump_ram_range(range) }
pub fn dump_ram_range_to_file(&self, range: Range<usize>, to_file: PathBuf) -> SimulateResult<()> {
self.bus.dump_ram_range_to_file(range, to_file)
}
}
| 25.693431 | 117 | 0.584943 | 3.078125 |
f05b7050495370891bf951394304c4e6b993404b
| 864 |
py
|
Python
|
Algorithms/MostCommonWord/mostCommonWord.py
|
riddhi-27/HacktoberFest2020-Contributions
|
0a5c39169723b3ea3b6447d4005896900dd789bc
|
[
"MIT"
] | null | null | null |
Algorithms/MostCommonWord/mostCommonWord.py
|
riddhi-27/HacktoberFest2020-Contributions
|
0a5c39169723b3ea3b6447d4005896900dd789bc
|
[
"MIT"
] | null | null | null |
Algorithms/MostCommonWord/mostCommonWord.py
|
riddhi-27/HacktoberFest2020-Contributions
|
0a5c39169723b3ea3b6447d4005896900dd789bc
|
[
"MIT"
] | null | null | null |
"""Returns words from the given paragraph which has been repeated most,
incase of more than one words, latest most common word is returned. """
import string
def mostCommonWord(paragraph: str) -> str:
# translate function maps every punctuation in given string to white space
words = paragraph.translate(str.maketrans(string.punctuation, ' '*len(string.punctuation)))
words = words.lower().split()
unique_words = {}
highest = 0
res = ''
for word in words:
if word not in unique_words:
unique_words[word] = 0
unique_words[word] += 1
if unique_words[word] >= highest:
highest = unique_words[word]
res = word
return res
print(mostCommonWord("HacktoberFest is live! Riddhi is participating in HACKtoBERfEST.Happy Coding.")) #Output: hacktoberfest
| 34.56 | 125 | 0.66088 | 3.21875 |
b013d6621fd48e57ccb3931b4185b000e7a1ca78
| 3,050 |
rs
|
Rust
|
chain-storage/benches/jellyfish.rs
|
trevor-crypto/thaler
|
945bb91da28c4ee022c5a653296f6ffbb1a5576c
|
[
"Apache-2.0"
] | 144 |
2019-03-20T03:24:43.000Z
|
2020-10-06T00:11:30.000Z
|
chain-storage/benches/jellyfish.rs
|
trevor-crypto/thaler
|
945bb91da28c4ee022c5a653296f6ffbb1a5576c
|
[
"Apache-2.0"
] | 2,183 |
2019-03-20T04:18:14.000Z
|
2020-10-19T07:41:42.000Z
|
chain-storage/benches/jellyfish.rs
|
trevor-crypto/thaler
|
945bb91da28c4ee022c5a653296f6ffbb1a5576c
|
[
"Apache-2.0"
] | 75 |
2019-03-20T08:08:42.000Z
|
2020-10-18T14:49:18.000Z
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use chain_core::state::account::{StakedState, StakedStateAddress};
use chain_storage::buffer::MemStore;
use chain_storage::jellyfish::{get_with_proof, put_stakings, Version};
fn bench_insert_256(b: &mut Bencher) {
let stakings = (0x00u8..=0x0fu8)
.map(|version| {
(0x00u8..=0x0fu8)
.map(|i| {
let mut seed = [0; 20];
seed[0] = version;
seed[1] = i;
StakedState::default(StakedStateAddress::BasicRedeem(seed.into()))
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
b.iter(|| {
let mut store = MemStore::new();
for (version, xs) in stakings.iter().enumerate() {
put_stakings(&mut store, version as Version, xs.iter())
.expect("jellyfish error with in memory storage");
}
});
}
fn bench_insert(b: &mut Bencher) {
let stakings = (0x00u8..=0x0fu8)
.map(|version| {
(0x00u8..=0x0fu8)
.map(|i| {
let mut seed = [0; 20];
seed[0] = version;
seed[1] = i;
StakedState::default(StakedStateAddress::BasicRedeem(seed.into()))
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let mut store = MemStore::new();
for (version, xs) in stakings.iter().enumerate() {
put_stakings(&mut store, version as Version, xs.iter())
.expect("jellyfish error with in memory storage");
}
let mut seed = [0; 20];
seed[0] = 0x10;
let stakings = vec![StakedState::default(StakedStateAddress::BasicRedeem(
seed.into(),
))];
b.iter(|| {
put_stakings(&mut store, 0x10, stakings.iter()).unwrap();
});
}
fn bench_get(b: &mut Bencher) {
let stakings = (0x00u8..=0x0fu8)
.map(|version| {
(0x00u8..=0x0fu8)
.map(|i| {
let mut seed = [0; 20];
seed[0] = version;
seed[1] = i;
StakedState::default(StakedStateAddress::BasicRedeem(seed.into()))
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let mut store = MemStore::new();
for (version, xs) in stakings.iter().enumerate() {
put_stakings(&mut store, version as Version, xs.iter())
.expect("jellyfish error with in memory storage");
}
b.iter(|| {
get_with_proof(
&store,
0x0f,
&stakings.last().unwrap().last().unwrap().address,
);
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("jellyfish, insert 256", bench_insert_256);
c.bench_function("jellyfish, insert", bench_insert);
c.bench_function("jellyfish, get_with_proof", bench_get);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
| 32.795699 | 86 | 0.52459 | 3.078125 |
4e472616766dd55b67d976975faf088f0fcd0bd7
| 1,624 |
swift
|
Swift
|
FourCubed/NetworkServices/VenueModel.swift
|
PNadiadhara/FourCubed
|
afeb851a3f92f5617bf5a2216344c9a3ff12fabe
|
[
"MIT"
] | null | null | null |
FourCubed/NetworkServices/VenueModel.swift
|
PNadiadhara/FourCubed
|
afeb851a3f92f5617bf5a2216344c9a3ff12fabe
|
[
"MIT"
] | null | null | null |
FourCubed/NetworkServices/VenueModel.swift
|
PNadiadhara/FourCubed
|
afeb851a3f92f5617bf5a2216344c9a3ff12fabe
|
[
"MIT"
] | 2 |
2019-02-08T21:48:17.000Z
|
2019-02-08T22:12:28.000Z
|
//
// VenueModel.swift
// FourCubed
//
// Created by TingxinLi on 2/19/19.
// Copyright © 2019 Pritesh Nadiadhara. All rights reserved.
//
import Foundation
final class VenuesModel {
private static let filename = "VenuesList.plist"
private static var venusData = [Favorite]()
static func saveVenues() {
let path = DataPersistenceManager.filepathToDocumentsDirectory(filename: filename)
do {
let data = try PropertyListEncoder().encode(venusData)
try data.write(to: path, options: Data.WritingOptions.atomic)
} catch {
print("property list encoding error: \(error)")
}
}
static func getVenues() -> [Favorite] {
let path = DataPersistenceManager.filepathToDocumentsDirectory(filename: filename).path
if FileManager.default.fileExists(atPath: path) {
if let data = FileManager.default.contents(atPath: path) {
do {
venusData = try PropertyListDecoder().decode([Favorite].self, from: data)
} catch {
print("property list decoding error: \(error)")
}
}else {
print("getPhotoJournal - data is nil")
}
} else {
print("\(filename) does not exist")
}
return venusData
}
static func addVenues(item: Favorite) {
venusData.append(item)
saveVenues()
}
static func delete(atIndex index: Int) {
venusData.remove(at: index)
saveVenues()
}
}
| 28 | 95 | 0.567118 | 3.015625 |
a1365c221c6166e83aee4ca6c2a466f4d073da6c
| 2,740 |
go
|
Go
|
cmd/cmd_num.go
|
Louch2010/dhaiy
|
c15481e7e30129b5ed9eda75c5e8e2a870885165
|
[
"MIT"
] | 1 |
2017-09-04T04:42:48.000Z
|
2017-09-04T04:42:48.000Z
|
cmd/cmd_num.go
|
Louch2010/dhaiy
|
c15481e7e30129b5ed9eda75c5e8e2a870885165
|
[
"MIT"
] | null | null | null |
cmd/cmd_num.go
|
Louch2010/dhaiy
|
c15481e7e30129b5ed9eda75c5e8e2a870885165
|
[
"MIT"
] | null | null | null |
package cmd
import (
"strconv"
"time"
. "github.com/louch2010/dhaiy/common"
"github.com/louch2010/dhaiy/log"
)
//NSet命令处理
func HandleNSetCommand(client *Client) {
args := client.Reqest[1:]
var liveTime int = 0
if len(args) == 3 {
t, err := strconv.Atoi(args[2])
if err != nil {
log.Info("参数转换错误,liveTime:", args[2], err)
client.Response = GetCmdResponse(MESSAGE_COMMAND_PARAM_ERROR, "", ERROR_COMMAND_PARAM_ERROR, client)
return
}
liveTime = t
}
f, err := strconv.ParseFloat(args[1], 64)
if err != nil {
log.Info("参数类型错误,nset value:", args[0], err)
client.Response = GetCmdResponse(MESSAGE_COMMAND_NOT_SUPPORT_DATA, "", ERROR_COMMAND_NOT_SUPPORT_DATA, client)
return
}
//增加缓存项
item := client.CacheTable.Set(args[0], f, time.Duration(liveTime)*time.Second, DATA_TYPE_NUMBER)
client.Response = GetCmdResponse(MESSAGE_SUCCESS, item, nil, client)
}
//NGet命令处理
func HandleNGetCommand(client *Client) {
//请求体校验
args := client.Reqest[1:]
item := client.CacheTable.Get(args[0])
if item == nil {
client.Response = GetCmdResponse(MESSAGE_ITEM_NOT_EXIST, "", ERROR_ITEM_NOT_EXIST, client)
return
}
//数据类型校验
if item.DataType() != DATA_TYPE_NUMBER {
client.Response = GetCmdResponse(MESSAGE_COMMAND_NOT_SUPPORT_DATA, "", ERROR_COMMAND_NOT_SUPPORT_DATA, client)
return
}
response := GetCmdResponse(MESSAGE_SUCCESS, item.Value(), nil, client)
response.DataType = DATA_TYPE_NUMBER
client.Response = response
}
//Incr命令处理
func HandleIncrCommand(client *Client) {
//请求体校验
args := client.Reqest[1:]
item := client.CacheTable.Get(args[0])
var v float64 = 1
//不存在,则设置为0,存在增加1
if item == nil {
client.CacheTable.Set(args[0], v, 0, DATA_TYPE_NUMBER)
} else {
//数据类型校验
if item.DataType() != DATA_TYPE_NUMBER {
client.Response = GetCmdResponse(MESSAGE_COMMAND_NOT_SUPPORT_DATA, "", ERROR_COMMAND_NOT_SUPPORT_DATA, client)
return
}
o, _ := item.Value().(float64)
v = o + v
item.SetValue(v)
}
response := GetCmdResponse(MESSAGE_SUCCESS, v, nil, client)
response.DataType = DATA_TYPE_NUMBER
client.Response = response
}
//IncrBy命令处理
func HandleIncrByCommand(client *Client) {
//请求体校验
args := client.Reqest[1:]
item := client.CacheTable.Get(args[0])
v, _ := strconv.ParseFloat(args[1], 10)
//不存在,则设置为0,存在增加1
if item == nil {
client.CacheTable.Set(args[0], v, 0, DATA_TYPE_NUMBER)
} else {
//数据类型校验
if item.DataType() != DATA_TYPE_NUMBER {
client.Response = GetCmdResponse(MESSAGE_COMMAND_NOT_SUPPORT_DATA, "", ERROR_COMMAND_NOT_SUPPORT_DATA, client)
return
}
o, _ := item.Value().(float64)
v = o + v
item.SetValue(v)
}
response := GetCmdResponse(MESSAGE_SUCCESS, v, nil, client)
response.DataType = DATA_TYPE_NUMBER
client.Response = response
}
| 27.128713 | 113 | 0.716058 | 3.046875 |
ff3a9124dd183337b5ae79248205eddd2518629b
| 5,198 |
lua
|
Lua
|
script/core/diagnostics/type-check.lua
|
rski/lua-language-server
|
6bf7a86e3fab833031918d93eb9d9ecbdafe9353
|
[
"MIT"
] | null | null | null |
script/core/diagnostics/type-check.lua
|
rski/lua-language-server
|
6bf7a86e3fab833031918d93eb9d9ecbdafe9353
|
[
"MIT"
] | null | null | null |
script/core/diagnostics/type-check.lua
|
rski/lua-language-server
|
6bf7a86e3fab833031918d93eb9d9ecbdafe9353
|
[
"MIT"
] | null | null | null |
local files = require 'files'
local guide = require 'parser.guide'
local vm = require 'vm'
local infer = require 'core.infer'
local await = require 'await'
local hasVarargs
local function inTypes(param, args)
for _, v in ipairs(args) do
if param[1] == v[1] then
return true
elseif param[1] == 'number'
and v[1] == 'integer' then
return true
end
end
return false
end
local function excludeSituations(types)
if not types[1]
or not types[1][1]
or types[1].typeGeneric then
return true
end
return false
end
local function getInfoFromDefs(defs)
local paramsTypes = {}
local funcArgsType
local mark = {}
for _, def in ipairs(defs) do
funcArgsType = {}
if def.value then
def = def.value
end
if mark[def] then
goto CONTINUE
end
mark[def] = true
if def.type == 'function'
or def.type == 'doc.type.function' then
if def.args then
for _, arg in ipairs(def.args) do
local types
if arg.docParam and arg.docParam.extends then
types = arg.docParam.extends.types
---变长参数
elseif arg.name and arg.name[1] == '...' then
types = {
[1] = {
[1] = '...',
type = 'varargs'
}
}
elseif arg.type == 'doc.type.arg' then
types = arg.extends.types
else
goto CONTINUE
end
---如果是很复杂的type,比如泛型什么的,先不检查
if excludeSituations(types) then
goto CONTINUE
end
funcArgsType[#funcArgsType+1] = types
end
end
if #funcArgsType > 0 then
paramsTypes[#paramsTypes+1] = funcArgsType
end
end
::CONTINUE::
end
return paramsTypes
end
local function matchParams(paramsTypes, i, arg)
local flag = ''
local messages = {}
for _, paramTypes in ipairs(paramsTypes) do
if not paramTypes[i] then
goto CONTINUE
end
for _, param in ipairs(paramTypes[i]) do
---如果形参的类型在实参里面
if inTypes(param, arg)
or param[1] == 'any'
or arg.type == 'any' then
flag = ''
return true
elseif param[1] == '...' then
hasVarargs = true
return true
else
flag = flag ..' ' .. param[1]
end
end
if flag ~= '' then
local argm = '[ '
for _, v in ipairs(arg) do
argm = argm .. v[1]..' '
end
argm = argm .. ']'
local message = 'Argument of type in '..argm..' is not assignable to parameter of type in ['..flag..' ]'
if not messages[message] then
messages[message] = true
messages[#messages+1] = message
end
end
::CONTINUE::
end
return false, messages
end
return function (uri, callback)
local ast = files.getState(uri)
if not ast then
return
end
guide.eachSourceType(ast.ast, 'call', function (source)
if not source.args then
return
end
await.delay()
local callArgs = source.args
local callArgsType = {}
for _, arg in ipairs(callArgs) do
local infers = infer.searchInfers(arg)
if infers['_G'] or infer['_ENV'] then
infers['_G'] = nil
infers['_ENV'] = nil
infers['table'] = true
end
local types = {}
for k in pairs(infers) do
if k then
types[#types+1] = {
[1] = k,
type = k
}
end
end
if #types < 1 then
return
end
types.start = arg.start
types.finish = arg.finish
callArgsType[#callArgsType+1] = types
end
local func = source.node
local defs = vm.getDefs(func)
---只检查有emmy注释定义的函数
local paramsTypes = getInfoFromDefs(defs)
---遍历实参
for i, arg in ipairs(callArgsType) do
---遍历形参
hasVarargs = false
local match, messages = matchParams(paramsTypes, i, arg)
if hasVarargs then
return
end
---都不匹配
if not match then
if #messages > 0 then
callback{
start = arg.start,
finish = arg.finish,
message = table.concat(messages, '\n')
}
end
end
end
---所有参数都匹配了
end)
end
| 29.202247 | 116 | 0.449981 | 3.046875 |
6cb38b453256f072361c569665e361f66ed480b8
| 1,214 |
kt
|
Kotlin
|
app/src/main/java/com/zero/neon/game/stage/StageController.kt
|
MAliffadlan/permainan-pesawat
|
29c43454c0f0d8d40b982b04d3190305b0da04d4
|
[
"MIT"
] | 53 |
2021-12-11T12:36:03.000Z
|
2022-03-17T22:36:27.000Z
|
app/src/main/java/com/zero/neon/game/stage/StageController.kt
|
MAliffadlan/permainan-pesawat
|
29c43454c0f0d8d40b982b04d3190305b0da04d4
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/zero/neon/game/stage/StageController.kt
|
MAliffadlan/permainan-pesawat
|
29c43454c0f0d8d40b982b04d3190305b0da04d4
|
[
"MIT"
] | 4 |
2022-01-02T14:10:24.000Z
|
2022-03-20T12:37:00.000Z
|
package com.zero.neon.game.stage
import androidx.compose.runtime.saveable.Saver
import com.zero.neon.utils.DateUtils
class StageController(
private val dateUtils: DateUtils = DateUtils(),
private var stageIndex: Int = 0,
private var stageStartSnapshotMillis: Long = dateUtils.currentTimeMillis()
) {
fun getGameStage(readyForNextStage: Boolean = false): Stage {
val stageTimeExpired =
stageStartSnapshotMillis + getStage().durationSec * 1000 < dateUtils.currentTimeMillis()
val hasNextStage = stageIndex < stages.lastIndex
if (stageTimeExpired && hasNextStage) {
if (!readyForNextStage) return StageBreak
stageIndex++
stageStartSnapshotMillis = dateUtils.currentTimeMillis()
}
return getStage()
}
private fun getStage(): Stage {
return stages[stageIndex]
}
companion object {
fun saver(): Saver<StageController, *> = Saver(
save = {
Pair(it.stageIndex, it.stageStartSnapshotMillis)
},
restore = {
StageController(stageIndex = it.first, stageStartSnapshotMillis = it.second)
}
)
}
}
| 31.947368 | 100 | 0.637562 | 3.140625 |
6591a3c532e745f5085d37bbe7a35e7d851a0c53
| 3,296 |
rs
|
Rust
|
medicines/api/src/main.rs
|
alsuren/products
|
b0ef8b13f9dfee457c25a3537619bd652541bf28
|
[
"MIT"
] | null | null | null |
medicines/api/src/main.rs
|
alsuren/products
|
b0ef8b13f9dfee457c25a3537619bd652541bf28
|
[
"MIT"
] | null | null | null |
medicines/api/src/main.rs
|
alsuren/products
|
b0ef8b13f9dfee457c25a3537619bd652541bf28
|
[
"MIT"
] | null | null | null |
use anyhow::anyhow;
use core::fmt::Display;
use std::{env, net::SocketAddr, str::FromStr};
use tracing::Level;
use warp::{
self,
http::{header, Method, StatusCode},
Filter, Rejection, Reply,
};
mod azure_context;
mod document;
mod pagination;
mod product;
mod schema;
mod substance;
const PORT: u16 = 8000;
use crate::{azure_context::create_context, schema::create_schema};
pub fn healthz() -> impl Filter<Extract = impl Reply, Error = Rejection> + Copy {
warp::path!("healthz")
.and(warp::get())
.map(warp::reply)
.map(|reply| warp::reply::with_status(reply, StatusCode::NO_CONTENT))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
if get_env_or_default("JSON_LOGS", true) {
use_json_log_subscriber()
} else {
use_unstructured_log_subscriber()
}
let log = warp::log("medicines-api");
let schema = create_schema();
let context = warp::any().map(create_context);
let cors = warp::cors()
.allow_methods(vec![Method::GET, Method::POST])
.allow_headers(vec![
header::AUTHORIZATION,
header::ACCEPT,
header::CONTENT_TYPE,
])
.allow_any_origin();
let graphql_filter =
juniper_warp::make_graphql_filter(schema, context.boxed()).with(cors.clone());
let addr = format!("0.0.0.0:{}", get_env_or_default("PORT", PORT.to_string()))
.parse::<SocketAddr>()?;
let _ = tokio::join!(tokio::spawn(async move {
warp::serve(
healthz()
.or(warp::path("graphiql").and(juniper_warp::graphiql_filter("/graphql", None)))
.or(warp::path("graphql").and(
warp::options()
.map(warp::reply)
.with(cors)
.with(warp::log("cors-only")),
))
.or(warp::path("graphql").and(graphql_filter))
.with(log),
)
.run(addr)
.await;
}));
Ok(())
}
fn use_json_log_subscriber() {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
.json()
.with_timer(tracing_subscriber::fmt::time::ChronoUtc::rfc3339())
.with_max_level(Level::INFO)
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
}
fn use_unstructured_log_subscriber() {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
.with_timer(tracing_subscriber::fmt::time::ChronoUtc::rfc3339())
.with_max_level(Level::DEBUG)
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
}
pub fn get_env_or_default<T>(key: &str, default: T) -> T
where
T: FromStr + Display,
{
get_env(key).unwrap_or_else(|e| {
tracing::warn!(r#"defaulting {} to "{}" ({})"#, key, &default, e);
default
})
}
pub fn get_env<T>(key: &str) -> anyhow::Result<T>
where
T: FromStr,
{
env::var(key)?
.parse::<T>()
.map_err(|_| anyhow!("failed to parse for {}", key))
}
| 28.66087 | 100 | 0.597998 | 3.015625 |
0ce945d91f14b7115bc5eeecc89a0cbddf6f0ae2
| 2,925 |
py
|
Python
|
radical_translations/agents/tests/test_models.py
|
kingsdigitallab/radical_translations
|
c18ca1ccc0ab2d88ae472dc2eda58e2ff9dcc76a
|
[
"MIT"
] | 3 |
2022-02-08T18:03:44.000Z
|
2022-03-18T18:10:43.000Z
|
radical_translations/agents/tests/test_models.py
|
kingsdigitallab/radical_translations
|
c18ca1ccc0ab2d88ae472dc2eda58e2ff9dcc76a
|
[
"MIT"
] | 19 |
2020-05-11T15:36:35.000Z
|
2022-02-08T11:26:40.000Z
|
radical_translations/agents/tests/test_models.py
|
kingsdigitallab/radical_translations
|
c18ca1ccc0ab2d88ae472dc2eda58e2ff9dcc76a
|
[
"MIT"
] | null | null | null |
from collections import defaultdict
import pytest
from radical_translations.agents.models import Organisation, Person
pytestmark = pytest.mark.django_db
@pytest.mark.usefixtures("vocabulary")
class TestOrganisation:
def test_agent_type(self, title):
obj = Person(name="person name")
obj.save()
assert obj.agent_type == "person"
obj = Organisation(name="organisation name")
obj.save()
assert obj.agent_type == "organisation"
def test_from_gsx_entry(self):
assert Organisation.from_gsx_entry(None) is None
entry = defaultdict(defaultdict)
entry["gsx$organisation"]["$t"] = ""
assert Organisation.from_gsx_entry(entry) is None
entry["gsx$organisation"]["$t"] = "Organisation 1"
assert Organisation.from_gsx_entry(entry) is not None
entry["gsx$type"]["$t"] = "Publisher"
assert Organisation.from_gsx_entry(entry) is not None
entry["gsx$location"]["$t"] = "0001: London [UK]"
assert Organisation.from_gsx_entry(entry) is not None
assert Organisation.objects.count() == 1
@pytest.mark.usefixtures("vocabulary")
class TestPerson:
def test_from_gsx_entry(self):
assert Person.from_gsx_entry(None) is None
entry = defaultdict(defaultdict)
entry["gsx$name"]["$t"] = ""
assert Person.from_gsx_entry(entry) is None
entry["gsx$name"]["$t"] = "Person 1"
assert Person.from_gsx_entry(entry) is not None
entry["gsx$gender"]["$t"] = "f"
p = Person.from_gsx_entry(entry)
assert p is not None
assert p.gender == "f"
entry["gsx$birth"]["$t"] = "1790"
p = Person.from_gsx_entry(entry)
assert p is not None
assert p.date_birth.date_display == "1790"
entry["gsx$locationsresidence"]["$t"] = "0001: London [UK]; 0002: Paris [FR]"
p = Person.from_gsx_entry(entry)
assert p is not None
assert "London" in p.based_near.first().address
assert "Paris" in p.based_near.last().address
entry["gsx$locationbirth"]["$t"] = "0001: London [UK]"
p = Person.from_gsx_entry(entry)
assert p is not None
assert "London" in p.place_birth.address
entry["gsx$locationdeath"]["$t"] = "0002: Paris [FR]"
p = Person.from_gsx_entry(entry)
assert p is not None
assert "Paris" in p.place_death.address
entry["gsx$occupations"]["$t"] = "tester"
p = Person.from_gsx_entry(entry)
assert p is not None
assert "tester" in p.roles.first().label.lower()
entry["gsx$organisations"]["$t"] = "Organisation 1"
p = Person.from_gsx_entry(entry)
assert p is not None
entry["gsx$collaborators"]["$t"] = "Person 2; Person 3"
p = Person.from_gsx_entry(entry)
assert p is not None
assert Person.objects.count() == 3
| 31.793478 | 85 | 0.624274 | 3.03125 |
2629fe896ea7cf424053dbe4a168352be5774d01
| 4,334 |
java
|
Java
|
src/main/java/im/yangqiang/android/unicorn/core/log/ILogger.java
|
carltony/Unicorn
|
5cf1422d9837819ccda0d5100100445a4925c8f8
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/im/yangqiang/android/unicorn/core/log/ILogger.java
|
carltony/Unicorn
|
5cf1422d9837819ccda0d5100100445a4925c8f8
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/im/yangqiang/android/unicorn/core/log/ILogger.java
|
carltony/Unicorn
|
5cf1422d9837819ccda0d5100100445a4925c8f8
|
[
"BSD-2-Clause"
] | null | null | null |
package im.yangqiang.android.unicorn.core.log;
public interface ILogger
{
/**
* Send a {@link android.util.Log#VERBOSE} log message.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
*/
int v(String tag, String msg);
/**
* Send a {@link android.util.Log#VERBOSE} log message and log the exception.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
* @param tr
* An exception to log
*/
int v(String tag, String msg, Throwable tr);
/**
* Send a {@link android.util.Log#DEBUG} log message.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
*/
int d(String tag, String msg);
/**
* Send a {@link android.util.Log#DEBUG} log message and log the exception.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
* @param tr
* An exception to log
*/
int d(String tag, String msg, Throwable tr);
/**
* Send an {@link android.util.Log#INFO} log message.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
*/
int i(String tag, String msg);
/**
* Send a {@link android.util.Log#INFO} log message and log the exception.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
* @param tr
* An exception to log
*/
int i(String tag, String msg, Throwable tr);
/**
* Send a {@link android.util.Log#WARN} log message.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
*/
int w(String tag, String msg);
/**
* Send a {@link android.util.Log#WARN} log message and log the exception.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
* @param tr
* An exception to log
*/
int w(String tag, String msg, Throwable tr);
/**
* Send an {@link android.util.Log#ERROR} log message.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
*/
int e(String tag, String msg);
/**
* Send a {@link android.util.Log#ERROR} log message and log the exception.
*
* @param tag
* Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg
* The message you would like logged.
* @param tr
* An exception to log
*/
int e(String tag, String msg, Throwable tr);
void open();
void close();
void println(int priority, String tag, String message);
/**
* 是否开启
*
* @return
*/
boolean isOpen();
}
| 31.635036 | 84 | 0.550761 | 3.046875 |
3e2defade92d63d813de05aa9b8fa46ea1a24b82
| 1,871 |
kt
|
Kotlin
|
math/src/main/kotlin/com/oneliang/ktx/util/math/check/Checker.kt
|
oneliang/util-kotlin
|
66c603ee9da407384cfc283102079e43d23e5b90
|
[
"Apache-2.0"
] | 1 |
2021-11-26T14:53:16.000Z
|
2021-11-26T14:53:16.000Z
|
math/src/main/kotlin/com/oneliang/ktx/util/math/check/Checker.kt
|
oneliang/util-kotlin
|
66c603ee9da407384cfc283102079e43d23e5b90
|
[
"Apache-2.0"
] | null | null | null |
math/src/main/kotlin/com/oneliang/ktx/util/math/check/Checker.kt
|
oneliang/util-kotlin
|
66c603ee9da407384cfc283102079e43d23e5b90
|
[
"Apache-2.0"
] | 2 |
2020-06-10T08:19:59.000Z
|
2020-08-27T10:52:00.000Z
|
package com.oneliang.ktx.util.math.check
object Checker {
enum class CheckType(val value: Int) {
RANGE_LEFT_OPEN_RIGHT_OPEN(0),//(,)
RANGE_LEFT_OPEN_RIGHT_CLOSED(1),//(,]
RANGE_LEFT_CLOSED_RIGHT_OPEN(2),//[,)
RANGE_LEFT_CLOSED_RIGHT_CLOSED(3)//[,]
}
enum class ParameterCheckType(val value: Int) {
PERCENT(0), DIFF(1)
}
fun check(value: Double, consultValue: Double, parameterArray: Array<Double>, checkType: CheckType, parameterCheckType: ParameterCheckType): Boolean {
if (parameterArray.isEmpty() || parameterArray.size != 2) {
error("match rule parameter size error, $checkType need two parameter")
}
val left = when (parameterCheckType) {
ParameterCheckType.PERCENT -> value * parameterArray[0]
else -> value + parameterArray[0]
}
val right = when (parameterCheckType) {
ParameterCheckType.PERCENT -> value * parameterArray[1]
else -> value + parameterArray[1]
}
when (checkType) {
CheckType.RANGE_LEFT_OPEN_RIGHT_OPEN -> {
if (!(left < consultValue && consultValue < right)) {
return false
}
}
CheckType.RANGE_LEFT_OPEN_RIGHT_CLOSED -> {
if (!(left < consultValue && consultValue <= right)) {
return false
}
}
CheckType.RANGE_LEFT_CLOSED_RIGHT_OPEN -> {
if (!(left <= consultValue && consultValue < right)) {
return false
}
}
CheckType.RANGE_LEFT_CLOSED_RIGHT_CLOSED -> {
if (!(left <= consultValue && consultValue <= right)) {
return false
}
}
}
return true
}
}
| 36.686275 | 154 | 0.54356 | 3.25 |
e53f54ac6e9b7bfd8125401457db0a165684d866
| 3,415 |
lua
|
Lua
|
CoreScripts/Modules/DevConsole/Components/ScrollingTextBox.lua
|
jackrestaki/Core-Scripts
|
31e68fd04caa585a0a52889aa2efda37ced4203e
|
[
"Apache-2.0"
] | null | null | null |
CoreScripts/Modules/DevConsole/Components/ScrollingTextBox.lua
|
jackrestaki/Core-Scripts
|
31e68fd04caa585a0a52889aa2efda37ced4203e
|
[
"Apache-2.0"
] | null | null | null |
CoreScripts/Modules/DevConsole/Components/ScrollingTextBox.lua
|
jackrestaki/Core-Scripts
|
31e68fd04caa585a0a52889aa2efda37ced4203e
|
[
"Apache-2.0"
] | null | null | null |
local CorePackages = game:GetService("CorePackages")
local UserInputService = game:GetService("UserInputService")
local TextService = game:GetService("TextService")
local Roact = require(CorePackages.Roact)
local TEXTBOX_RIGHTSIDE_THRESHOLD = 0.9
local ScrollingTextBox = Roact.Component:extend("ScrollingTextBox")
function ScrollingTextBox:init(props)
local fontDims = TextService:GetTextSize("A", props.TextSize, props.Font, Vector2.new(0, 0))
self.adjustOffset = function()
if self.clipBox.current and self.textboxRef.current then
-- this logic only works for monospace font
-- cursorposition returns 1 for the left most cursor position
local fontDims = self.state.fontDims
local cursorPos = self.textboxRef.current.CursorPosition - 1
local innerCursorPos = cursorPos - (math.ceil(self.state.innerXOffset/fontDims.X))
local maxCursorPos = math.floor(self.clipBox.current.AbsoluteSize.X * TEXTBOX_RIGHTSIDE_THRESHOLD / fontDims.X)
if innerCursorPos > maxCursorPos then
local newOffset = (cursorPos - maxCursorPos) * fontDims.X
self:setState({
innerXOffset = newOffset
})
elseif innerCursorPos < 0 then
local newOffset = cursorPos * fontDims.X
self:setState({
innerXOffset = newOffset
})
end
end
end
self.clipBox = Roact.createRef()
self.textboxRef = self.props[Roact.Ref] or Roact.createRef()
self.state = {
fontDims = fontDims,
innerXOffset = 0,
}
end
function ScrollingTextBox:didMount()
if not self.onFocusConnection then
self.onFocusConnection = UserInputService.InputBegan:Connect(function(input)
if self.textboxRef.current and self.textboxRef.current:IsFocused() then
if input.KeyCode == Enum.KeyCode.Home then
self.textboxRef.current.CursorPosition = 0
elseif input.KeyCode == Enum.KeyCode.End then
-- plus one for the position after the last character
self.textboxRef.current.CursorPosition = #self.textboxRef.current.text + 1
else
self.adjustOffset()
end
end
end)
end
end
function ScrollingTextBox:willUnmount()
if self.onFocusConnection then
self.onFocusConnection:Disconnect()
self.onFocusConnection = nil
end
end
function ScrollingTextBox:render()
local position = self.props.Position
local size = self.props.Size
local placeHolderText = self.props.PlaceholderText
local textColor = self.props.TextColor3
local textSize = self.props.TextSize
local font = self.props.Font
local text = self.props.Text
local clearTextOnFocus = self.props.ClearTextOnFocus
local showNativeInput = self.props.ShowNativeInput
local textboxOnFocusLost = self.props.TextBoxFocusLost
local innerXOffset = self.state.innerXOffset
return Roact.createElement("Frame", {
Position = position,
Size = size,
BackgroundTransparency = 1,
ClipsDescendants = true,
[Roact.Ref] = self.clipBox,
}, {
TextBox = Roact.createElement("TextBox", {
Position = UDim2.new(0, -innerXOffset, 0, 0),
Size = UDim2.new(1, innerXOffset, 1, 0),
BackgroundTransparency = 1,
ShowNativeInput = showNativeInput,
ClearTextOnFocus = clearTextOnFocus,
TextColor3 = textColor,
TextXAlignment = 0,
TextSize = textSize,
Text = text,
Font = font,
PlaceholderText = placeHolderText,
[Roact.Ref] = self.textboxRef,
[Roact.Change.CursorPosition] = self.adjustOffset,
[Roact.Event.FocusLost] = textboxOnFocusLost,
}),
})
end
return ScrollingTextBox
| 29.188034 | 114 | 0.747877 | 3.109375 |
81129d757f28a58fdc44ce1cb2c97c7f85796b39
| 623 |
rs
|
Rust
|
examples/basic-stdio.rs
|
sonro/linurgy
|
432e42fe9820db18a5b9b0ff5ba651502d535e1e
|
[
"Apache-2.0",
"MIT"
] | 1 |
2019-07-31T16:37:40.000Z
|
2019-07-31T16:37:40.000Z
|
examples/basic-stdio.rs
|
sonro/linurgy
|
432e42fe9820db18a5b9b0ff5ba651502d535e1e
|
[
"Apache-2.0",
"MIT"
] | 3 |
2020-02-11T18:26:30.000Z
|
2022-01-27T14:49:35.000Z
|
examples/basic-stdio.rs
|
sonro/linurgy
|
432e42fe9820db18a5b9b0ff5ba651502d535e1e
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
use std::io::{stdin, Read, Result};
/// Edit stdin and output to stdout.
///
/// This will add a line of dashes after every line. This will only output
/// after the user has ended the input stream. If you want to watch a file,
/// or use the program more interactively, use `buffered_edit` instead.
fn main() -> Result<()> {
// appeneds "---\n" after every line
let editor = linurgy::factory::appender("---\n", 1);
// input buffer
let mut input = String::new();
// read the input
stdin().read_to_string(&mut input)?;
// write the output
print!("{}", editor.edit(&input));
Ok(())
}
| 27.086957 | 75 | 0.624398 | 3.078125 |
3dbbd19191e48ecd9f1740a330c6175eca70e428
| 1,529 |
swift
|
Swift
|
Pods/Reductio/Source/Keyword.swift
|
danielsogl/DHBW-Sentiment-Analyse-App
|
05bd4208530b453594398938ffca9d1402a8d031
|
[
"MIT"
] | 456 |
2016-03-10T00:50:57.000Z
|
2022-03-14T22:03:44.000Z
|
Pods/Reductio/Source/Keyword.swift
|
danielsogl/DHBW-Sentiment-Analyse-App
|
05bd4208530b453594398938ffca9d1402a8d031
|
[
"MIT"
] | 8 |
2016-07-07T12:53:15.000Z
|
2020-11-15T15:10:18.000Z
|
Pods/Reductio/Source/Keyword.swift
|
danielsogl/DHBW-Sentiment-Analyse-App
|
05bd4208530b453594398938ffca9d1402a8d031
|
[
"MIT"
] | 39 |
2016-04-29T01:35:17.000Z
|
2022-01-05T05:58:24.000Z
|
/**
This file is part of the Reductio package.
(c) Sergio Fernández <[email protected]>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
*/
import Foundation
internal final class Keyword {
private let ngram: Int = 3
private var words: [String]
private let ranking = TextRank<String>()
init(text: String) {
self.words = Keyword.preprocess(text)
}
func execute() -> [String] {
filterWords()
buildGraph()
return ranking.execute()
.sorted { $0.1 > $1.1 }
.map { $0.0 }
}
func filterWords() {
self.words = self.words
.filter(removeShortWords)
.filter(removeStopWords)
}
func buildGraph() {
for (index, node) in words.enumerated() {
var (min, max) = (index-ngram, index+ngram)
if min < 0 { min = words.startIndex }
if max > words.count { max = words.endIndex }
words[min..<max].forEach { word in
ranking.add(edge: node, to: word)
}
}
}
}
private extension Keyword {
static func preprocess(_ text: String) -> [String] {
return text.lowercased()
.components(separatedBy: CharacterSet.letters.inverted)
}
func removeShortWords(_ word: String) -> Bool {
return word.count > 2
}
func removeStopWords(_ word: String) -> Bool {
return !stopwords.contains(word)
}
}
| 24.269841 | 72 | 0.580118 | 3.015625 |
f02f263b4792b69303bcdec39c484284dc805802
| 1,221 |
py
|
Python
|
src/prefect/engine/result_handlers/secret_result_handler.py
|
trapped/prefect
|
128f11570c35e7156d65ba65fdcbc1f4ccd7c2b7
|
[
"Apache-2.0"
] | 1 |
2019-12-20T07:43:55.000Z
|
2019-12-20T07:43:55.000Z
|
src/prefect/engine/result_handlers/secret_result_handler.py
|
trapped/prefect
|
128f11570c35e7156d65ba65fdcbc1f4ccd7c2b7
|
[
"Apache-2.0"
] | null | null | null |
src/prefect/engine/result_handlers/secret_result_handler.py
|
trapped/prefect
|
128f11570c35e7156d65ba65fdcbc1f4ccd7c2b7
|
[
"Apache-2.0"
] | null | null | null |
import json
from typing import Any
import prefect
from prefect.engine.result_handlers import ResultHandler
class SecretResultHandler(ResultHandler):
"""
Hook for storing and retrieving sensitive task results from a Secret store. Only intended to be used
for Secret tasks.
Args:
- secret_task (Task): the Secret Task that this result handler will be used for
"""
def __init__(self, secret_task: "prefect.tasks.secrets.Secret") -> None:
self.secret_task = secret_task
super().__init__()
def read(self, name: str) -> Any:
"""
Read a secret from a provided name with the provided Secret class;
this method actually retrieves the secret from the Secret store.
Args:
- name (str): the name of the secret to retrieve
Returns:
- Any: the deserialized result
"""
return self.secret_task.run() # type: ignore
def write(self, result: Any) -> str:
"""
Returns the name of the secret.
Args:
- result (Any): the result to write
Returns:
- str: the JSON representation of the result
"""
return self.secret_task.name
| 27.133333 | 104 | 0.626536 | 3.125 |
1c0c623935b2f86e5daa88fa3e319596d098a539
| 1,857 |
kt
|
Kotlin
|
app/src/androidTest/java/com/ersiver/newsster/db/RemoteKeyDaoTest.kt
|
l2hyunwoo/Newsster
|
b0e11062d62e0661f4c2774df7f45309493c4b83
|
[
"Apache-2.0"
] | 153 |
2020-09-09T21:42:27.000Z
|
2022-03-21T07:36:56.000Z
|
app/src/androidTest/java/com/ersiver/newsster/db/RemoteKeyDaoTest.kt
|
l2hyunwoo/Newsster
|
b0e11062d62e0661f4c2774df7f45309493c4b83
|
[
"Apache-2.0"
] | 1 |
2020-09-13T20:02:00.000Z
|
2020-09-13T20:02:00.000Z
|
app/src/androidTest/java/com/ersiver/newsster/db/RemoteKeyDaoTest.kt
|
l2hyunwoo/Newsster
|
b0e11062d62e0661f4c2774df7f45309493c4b83
|
[
"Apache-2.0"
] | 35 |
2020-09-13T17:51:35.000Z
|
2022-03-30T19:13:28.000Z
|
package com.ersiver.newsster.db
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.ersiver.newsster.utils.TestUtil
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@ExperimentalCoroutinesApi
@SmallTest
@RunWith(AndroidJUnit4::class)
class RemoteKeyDaoTest : LocalDatabase() {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
private lateinit var remoteKeyDao: RemoteKeyDao
@Before
fun setup() {
remoteKeyDao = database.remoteKeyDao()
}
@Test
fun insertAndLoadById() = runBlockingTest {
val article = TestUtil.createArticle()
val remoteKey = TestUtil.createRemoteKey()
val remoteKeys = listOf(remoteKey)
remoteKeyDao.insertAll(remoteKeys)
val loaded = remoteKeyDao.remoteKeyByArticle(article.id)
assertThat(loaded, `is`(notNullValue()))
assertThat(loaded.articleId, `is`(article.id))
assertThat(loaded.nextKey, `is`(remoteKey.nextKey))
assertThat(loaded.prevKey, `is`(remoteKey.prevKey))
}
@Test
fun insertAndDelete() = runBlockingTest {
val article = TestUtil.createArticle()
val remoteKey = TestUtil.createRemoteKey()
val remoteKeys = listOf(remoteKey)
remoteKeyDao.insertAll(remoteKeys)
remoteKeyDao.clearRemoteKeys()
val load = remoteKeyDao.remoteKeyByArticle(article.id)
assertThat(load, `is`(nullValue()))
}
}
| 31.474576 | 66 | 0.739903 | 3 |
46364e8834db099b942a076e60e45c4d914b79f9
| 1,866 |
lua
|
Lua
|
BGAnimations/ScreenGameplay underlay/PerPlayer/StepStatistics/SongBackground.lua
|
Fieoner/Simply-Love-SM5-Horizontal
|
051aee51934a2a9865659958d460c9404a0584be
|
[
"MIT"
] | 1 |
2021-11-19T20:04:34.000Z
|
2021-11-19T20:04:34.000Z
|
BGAnimations/ScreenGameplay underlay/PerPlayer/StepStatistics/SongBackground.lua
|
Fieoner/Simply-Love-SM5-Horizontal
|
051aee51934a2a9865659958d460c9404a0584be
|
[
"MIT"
] | null | null | null |
BGAnimations/ScreenGameplay underlay/PerPlayer/StepStatistics/SongBackground.lua
|
Fieoner/Simply-Love-SM5-Horizontal
|
051aee51934a2a9865659958d460c9404a0584be
|
[
"MIT"
] | null | null | null |
local player = ...
-- AspectRatios is a global table defined in _fallback/Scripts/02 Utilities.lua
-- that lists aspect ratios supported by SM5 as key/value pairs. I am misusing it here to index
-- my own crop_amount table with the numbers it provides so I can look up how much to crop the
-- song's background by. Indexing with floating-point keys seems inadvisable, but I don't have
-- enough CS background to say for certain. I'll change this if (when) issues are identified.
local crop_amount = {
-- notefield is not centered
[false] = {
[AspectRatios.FourThree] = 0.5,
[AspectRatios.SixteenNine] = 0.5,
[AspectRatios.SixteenTen] = 0.5,
},
-- notefield is centered
[true] = {
-- centered notefield + 4:3 AspectRatio means that StepStats should be disabled and we
-- should never get here, but specify 1 to crop the entire background away Just In Case.
[AspectRatios.FourThree] = 1,
-- These are supported, however, when the notefield is centered.
[AspectRatios.SixteenNine] = 0.3515,
[AspectRatios.SixteenTen] = 0.333333,
}
}
return Def.Sprite{
InitCommand=function(self)
-- round the DisplayAspectRatio value from the user's Preferences.ini file to not exceed
-- 5 decimal places of precision to match the AspectRatios table from the _fallback theme
local ar = round(PREFSMAN:GetPreference("DisplayAspectRatio"), 5)
local centered = PREFSMAN:GetPreference("Center1Player")
if player == PLAYER_1 then
self:cropright( crop_amount[centered][ar] )
elseif player == PLAYER_2 then
self:cropleft( crop_amount[centered][ar] )
end
end,
CurrentSongChangedMessageCommand=function(self)
-- Background scaling and cropping is handled by the _fallback theme via
-- scale_or_crop_background(), which is defined in _fallback/Scripts/02 Actor.lua
self:LoadFromCurrentSongBackground():scale_or_crop_background()
end
}
| 38.875 | 96 | 0.750268 | 3.015625 |
0c873f69a18440e8e7c7b2463204d9290fbcbf4a
| 6,513 |
py
|
Python
|
fsmonitor/polling.py
|
ljmccarthy/fsmonitor
|
4d84d9817dce7b274cb4586b5c2091dea96982f9
|
[
"MIT"
] | 26 |
2018-03-24T06:38:19.000Z
|
2022-02-18T10:22:51.000Z
|
fsmonitor/polling.py
|
ljmccarthy/fsmonitor
|
4d84d9817dce7b274cb4586b5c2091dea96982f9
|
[
"MIT"
] | 5 |
2018-06-19T21:35:00.000Z
|
2018-06-26T21:11:38.000Z
|
fsmonitor/polling.py
|
ljmccarthy/fsmonitor
|
4d84d9817dce7b274cb4586b5c2091dea96982f9
|
[
"MIT"
] | 9 |
2018-06-19T21:35:53.000Z
|
2022-03-26T17:01:11.000Z
|
# Copyright (c) 2012 Luke McCarthy <[email protected]>
#
# This is free software released under the MIT license.
# See COPYING file for details, or visit:
# http://www.opensource.org/licenses/mit-license.php
#
# The file is part of FSMonitor, a file-system monitoring library.
# https://github.com/shaurz/fsmonitor
import sys, os, time, threading, errno
from .common import FSEvent, FSMonitorError
def get_dir_contents(path):
return [(filename, os.stat(os.path.join(path, filename)))
for filename in os.listdir(path)]
class FSMonitorDirWatch(object):
def __init__(self, path, flags, user):
self.path = path
self.flags = flags
self.user = user
self.enabled = True
self._timestamp = time.time()
try:
self._contents = get_dir_contents(path)
self._deleted = False
except OSError as e:
self._contents = []
self._deleted = (e.errno == errno.ENOENT)
def __repr__(self):
return "<FSMonitorDirWatch %r>" % self.path
@classmethod
def new_state(cls, path):
return [(filename, os.stat(os.path.join(path, filename)))
for filename in os.listdir(path)]
def getstate(self):
return self._contents
def delstate(self):
self._contents = []
self._deleted = True
def setstate(self, state):
self._contents = state
self._deleted = False
state = property(getstate, setstate, delstate)
class FSMonitorFileWatch(object):
def __init__(self, path, flags, user):
self.path = path
self.flags = flags
self.user = user
self.enabled = True
self._timestamp = time.time()
try:
self._stat = os.stat(path)
self._deleted = False
except OSError as e:
self._stat = None
self._deleted = (e.errno == errno.ENOENT)
def __repr__(self):
return "<FSMonitorFileWatch %r>" % self.path
@classmethod
def new_state(cls, path):
return os.stat(path)
def getstate(self):
return self._stat
def delstate(self):
self._stat = None
self._deleted = True
def setstate(self, state):
self._stat = state
self._deleted = False
state = property(getstate, setstate, delstate)
class FSMonitorWatch(object):
def __init__(self, path, flags, user):
self.path = path
self.flags = flags
self.user = user
self.enabled = True
self._timestamp = time.time()
try:
self._contents = get_dir_contents(path)
self._deleted = False
except OSError as e:
self._contents = []
self._deleted = (e.errno == errno.ENOENT)
def __repr__(self):
return "<FSMonitorWatch %r>" % self.path
def _compare_contents(watch, new_contents, events_out, before):
name_to_new_stat = dict(new_contents)
for name, old_stat in watch._contents:
new_stat = name_to_new_stat.get(name)
if new_stat:
_compare_stat(watch, new_stat, events_out, before, old_stat, name)
else:
events_out.append(FSEvent(watch, FSEvent.Delete, name))
old_names = frozenset(x[0] for x in watch._contents)
for name, new_stat in new_contents:
if name not in old_names:
events_out.append(FSEvent(watch, FSEvent.Create, name))
def _compare_stat(watch, new_stat, events_out, before, old_stat, filename):
if new_stat.st_atime != old_stat.st_atime and new_stat.st_atime < before:
events_out.append(FSEvent(watch, FSEvent.Access, filename))
if new_stat.st_mtime != old_stat.st_mtime:
events_out.append(FSEvent(watch, FSEvent.Modify, filename))
def round_fs_resolution(t):
if sys.platform == "win32":
return t // 2 * 2
else:
return t // 1
class FSMonitor(object):
def __init__(self):
self.__lock = threading.Lock()
self.__dir_watches = set()
self.__file_watches = set()
self.polling_interval = 0.5
@property
def watches(self):
with self.__lock:
return list(self.__dir_watches) + list(self.__file_watches)
def add_dir_watch(self, path, flags=FSEvent.All, user=None):
watch = FSMonitorDirWatch(path, flags, user)
with self.__lock:
self.__dir_watches.add(watch)
return watch
def add_file_watch(self, path, flags=FSEvent.All, user=None):
watch = FSMonitorFileWatch(path, flags, user)
with self.__lock:
self.__file_watches.add(watch)
return watch
def remove_watch(self, watch):
with self.__lock:
if watch in self.__dir_watches:
self.__dir_watches.discard(watch)
elif watch in self.__file_watches:
self.__file_watches.discard(watch)
def remove_all_watches(self):
with self.__lock:
self.__dir_watches.clear()
self.__file_watches.clear()
def enable_watch(self, watch, enable=True):
watch.enabled = enable
def disable_watch(self, watch):
watch.enabled = False
def read_events(self, timeout=None):
now = start_time = time.time()
watches = self.watches
watches.sort(key=lambda watch: abs(now - watch._timestamp), reverse=True)
events = []
for watch in watches:
now = time.time()
if watch._timestamp < now:
tdiff = now - watch._timestamp
if tdiff < self.polling_interval:
time.sleep(self.polling_interval - tdiff)
watch._timestamp = now
if not watch.enabled:
continue
before = round_fs_resolution(time.time())
try:
new_state = watch.new_state(watch.path)
except OSError as e:
if e.errno == errno.ENOENT:
if not watch._deleted:
del watch.state
events.append(FSEvent(watch, FSEvent.DeleteSelf))
else:
if isinstance(watch, FSMonitorDirWatch):
_compare_contents(watch, new_state, events, before)
elif isinstance(watch, FSMonitorFileWatch):
_compare_stat(watch, new_state, events, before,
watch.state, watch.path)
watch.state = new_state
return events
| 29.876147 | 81 | 0.60172 | 3.03125 |
1665cd156a52fd6633baad6621f5ef7bf5785868
| 3,344 |
tsx
|
TypeScript
|
packages/cascader/src/popup/search-popup.tsx
|
illa-family/illa-design
|
00f4a50d9bcfe337304f6316e8e86d5c19e60e08
|
[
"Apache-2.0"
] | 30 |
2021-11-25T10:49:45.000Z
|
2022-03-24T12:47:16.000Z
|
packages/cascader/src/popup/search-popup.tsx
|
illa-family/illa-design
|
00f4a50d9bcfe337304f6316e8e86d5c19e60e08
|
[
"Apache-2.0"
] | 10 |
2021-11-29T11:19:53.000Z
|
2022-03-25T07:28:39.000Z
|
packages/cascader/src/popup/search-popup.tsx
|
illa-family/illa-design
|
00f4a50d9bcfe337304f6316e8e86d5c19e60e08
|
[
"Apache-2.0"
] | 5 |
2021-11-24T07:50:39.000Z
|
2022-03-02T06:59:03.000Z
|
import { useEffect, useState, useRef, SyntheticEvent } from "react"
import isEqual from "react-fast-compare"
import { Empty } from "@illa-design/empty"
import { Checkbox } from "@illa-design/checkbox"
import { Node } from "../node"
import { OptionProps, SearchPopupProps } from "../interface"
import {
applyOptionStyle,
flexCenterStyle,
optionLabelStyle,
optionListStyle,
searchListWrapper,
textMargin,
} from "./style"
export const SearchPopup = <T extends OptionProps>(
props: SearchPopupProps<T>,
) => {
const { store, multiple, onChange, inputValue, style, value = [] } = props
const wrapperRef = useRef<HTMLDivElement>(null)
const [options, setOptions] = useState<Node<T>[]>(
store?.searchNodeByLabel(inputValue) || [],
)
const activeItemRef = useRef<HTMLLIElement | null>(null)
const isFirst = useRef<boolean>(true)
const clickOption = (
option: Node<T>,
checked: boolean,
e: SyntheticEvent,
) => {
e?.stopPropagation()
if (option.disabled) {
return
}
if (multiple) {
option.setCheckedState(checked)
let checkedValues
if (checked) {
checkedValues = value?.concat([option.pathValue])
} else {
checkedValues = value?.filter((item) => {
return !isEqual(item, option.pathValue)
})
}
onChange?.(checkedValues)
} else {
onChange?.([option.pathValue])
}
}
const isDidMount = useRef(false)
useEffect(() => {
if (isDidMount.current) {
if (store) {
setOptions(store.searchNodeByLabel(inputValue))
}
} else {
isDidMount.current = true
}
}, [inputValue])
useEffect(() => {
isFirst.current = false
}, [])
return options.length ? (
<div
ref={wrapperRef}
css={searchListWrapper}
onClick={(e) => e?.stopPropagation()}
>
<ul css={optionListStyle} style={style}>
{options.map((option, i) => {
const pathNodes = option.getPathNodes()
const label = pathNodes.map((x) => x.label).join(" / ")
const checked = value.some((x) => {
return isEqual(x, option.pathValue)
})
return (
<li
css={applyOptionStyle({
active: checked,
disabled: option.disabled,
})}
ref={(node) => {
if (checked && isFirst.current && !activeItemRef.current) {
node?.scrollIntoView()
activeItemRef.current = node
}
}}
onClick={(e) => {
clickOption(option, !checked, e)
}}
key={i}
>
{multiple ? (
<>
<Checkbox
css={textMargin}
checked={checked}
value={option.value}
disabled={option.disabled}
onChange={(checked, e) => {
clickOption(option, checked, e)
}}
/>
<div css={optionLabelStyle}>{label}</div>
</>
) : (
label
)}
</li>
)
})}
</ul>
</div>
) : (
<Empty css={flexCenterStyle} style={style} />
)
}
| 26.539683 | 76 | 0.513457 | 3.125 |
e8f4b23ed19c18a99bdef84f2585aee923db8769
| 3,306 |
py
|
Python
|
pyathena/util/rebin.py
|
changgoo/pyathena-1
|
c461ac3390d773537ce52393e3ebf68a3282aa46
|
[
"MIT"
] | 1 |
2019-10-03T13:59:14.000Z
|
2019-10-03T13:59:14.000Z
|
pyathena/util/rebin.py
|
changgoo/pyathena-1
|
c461ac3390d773537ce52393e3ebf68a3282aa46
|
[
"MIT"
] | 3 |
2020-09-23T23:36:17.000Z
|
2022-01-11T06:16:56.000Z
|
pyathena/util/rebin.py
|
changgoo/pyathena-1
|
c461ac3390d773537ce52393e3ebf68a3282aa46
|
[
"MIT"
] | 2 |
2019-06-10T04:26:16.000Z
|
2019-12-04T22:27:02.000Z
|
from __future__ import print_function
import numpy as np
def rebin_xyz(arr, bin_factor, fill_value=None):
"""
Function to rebin masked 3d array.
Parameters
----------
arr : ndarray
Masked or unmasked 3d numpy array. Shape is assumed to be (nz, ny, nx).
bin_factor : int
binning factor
fill_value: float
If arr is a masked array, fill masked elements with fill_value.
If *None*, masked elements will be neglected in calculating average.
Default value is *None*.
Return
------
arr_rebin: ndarray
Smaller size, (averaged) 3d array. Shape is assumed to be
(nz//bin_factor, ny//bin_factor, nx//bin_factor)
"""
if bin_factor == 1:
return arr
# number of cells in the z-direction and xy-direction
nz0 = arr.shape[0]
ny0 = arr.shape[1]
nx0 = arr.shape[2]
# size of binned array
nz1 = nz0 // bin_factor
ny1 = ny0 // bin_factor
nx1 = nx0 // bin_factor
if np.ma.is_masked(arr) and fill_value is not None:
np.ma.set_fill_value(arr, fill_value)
arr = arr.filled()
# See
# https://stackoverflow.com/questions/4624112/grouping-2d-numpy-array-in-average/4624923#4624923
return arr.reshape([nz1, nz0//nz1, ny1, ny0//ny1, nx1, nx0//nx1]).mean(axis=-1).mean(axis=3).mean(axis=1)
def rebin_xy(arr, bin_factor, fill_value=None):
"""
Function to rebin masked 3d array in the x-y dimension.
Parameters
----------
arr : ndarray
Masked or unmasked 3d numpy array. Shape is assumed to be (nz, ny, nx).
bin_factor : int
binning factor
fill_value: float
If arr is a masked array, fill masked elements with fill_value.
If *None*, masked elements will be neglected in calculating average.
Default value is *None*.
Return
------
arr_rebin: ndarray
Smaller size, (averaged) 3d array. Shape is assumed to be
(nz, ny//bin_factor, nx//bin_factor)
"""
if bin_factor == 1:
return arr
# number of cells in the z-direction and xy-direction
nz = arr.shape[0]
ny0 = arr.shape[1]
nx0 = arr.shape[2]
# size of binned array
ny1 = ny0 // bin_factor
nx1 = nx0 // bin_factor
if np.ma.is_masked(arr) and fill_value is not None:
np.ma.set_fill_value(arr, fill_value)
arr = arr.filled()
# See
# https://stackoverflow.com/questions/4624112/grouping-2d-numpy-array-in-average/4624923#4624923
return arr.reshape([nz, ny1, ny0//ny1, nx1, nx0//nx1]).mean(axis=-1).mean(axis=2)
if __name__ == '__main__':
# Test of rebin_xy
mask = True
# Define test data
big = np.ma.array([[5, 5, 1, 2],
[5, 5, 2, 1],
[2, 1, 1, 1],
[2, 1, 1, 1]])
if mask:
big.mask = [[1, 1, 0, 0],
[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 1, 0]]
big = np.tile(big, (1, 1, 1))
small1 = rebin_xy_masked(big, 2, fill_value=0.0)
small2 = rebin_xy_masked(big, 2, fill_value=None)
print('Original array\n', big)
print('With fill value 0.0\n', small1)
print('Without fill value\n', small2)
| 28.747826 | 109 | 0.578947 | 3.53125 |
f15740e4503472d8982d83e20726fe0dd4127f1d
| 13,239 |
rb
|
Ruby
|
spec/lib/core_ext/array_spec.rb
|
Munyola/OpenSplitTime
|
20e1e96917fdeee4103c9492b16856d4d734f2bb
|
[
"MIT"
] | 16 |
2017-04-28T14:58:39.000Z
|
2021-12-10T17:18:48.000Z
|
spec/lib/core_ext/array_spec.rb
|
Munyola/OpenSplitTime
|
20e1e96917fdeee4103c9492b16856d4d734f2bb
|
[
"MIT"
] | 193 |
2016-01-31T04:39:41.000Z
|
2022-03-15T19:15:26.000Z
|
spec/lib/core_ext/array_spec.rb
|
Munyola/OpenSplitTime
|
20e1e96917fdeee4103c9492b16856d4d734f2bb
|
[
"MIT"
] | 8 |
2016-05-11T22:57:33.000Z
|
2021-10-04T14:42:46.000Z
|
# frozen_string_literal: true
require_relative '../../../lib/core_ext/array'
RSpec.describe Array do
describe '#average' do
it 'computes the average of elements in the Array' do
array = [1, 2, 3]
expect(array.average).to eq(2)
end
it 'works properly when the answer is not an integer' do
array = [1, 2]
expect(array.average).to eq(1.5)
end
end
describe '#elements_before' do
context 'when the "inclusive" parameter is set to false' do
subject { array.elements_before(element, inclusive: false) }
context 'when the element is included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'returns all elements in the array indexed prior to the provided parameter' do
expect(subject).to eq(%w(cat bird sheep))
end
end
context 'when nil is provided and the array includes a nil element' do
let(:array) { [1, 2, 3, nil, 5] }
let(:element) { nil }
it 'returns the elements prior to nil' do
expect(subject).to eq([1, 2, 3])
end
end
context 'when the element appears more than once' do
let(:array) { %w(cat bird sheep ferret sheep coyote) }
let(:element) { 'sheep' }
it 'bases the result on the first match of the provided parameter' do
expect(subject).to eq(%w(cat bird))
end
end
context 'when the first element is provided' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'cat' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
context 'when the provided parameter is not included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'buffalo' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
end
context 'when the "inclusive" parameter is set to true' do
subject { array.elements_before(element, inclusive: true) }
context 'when the element is included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'returns all elements in the array indexed prior to the provided parameter' do
expect(subject).to eq(%w(cat bird sheep ferret))
end
end
context 'when nil is provided and the array includes a nil element' do
let(:array) { [1, 2, 3, nil, 5] }
let(:element) { nil }
it 'returns the elements prior to nil' do
expect(subject).to eq([1, 2, 3, nil])
end
end
context 'when the element appears more than once' do
let(:array) { %w(cat bird sheep ferret sheep coyote) }
let(:element) { 'sheep' }
it 'bases the result on the first match of the provided parameter' do
expect(subject).to eq(%w(cat bird sheep))
end
end
context 'when the first element is provided' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'cat' }
it 'returns the first element' do
expect(subject).to eq(['cat'])
end
end
context 'when the provided parameter is not included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'buffalo' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
end
context 'when the "inclusive" parameter is not provided' do
subject { array.elements_before(element) }
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'functions as thought the "inclusive" parameter were set to false' do
expect(subject).to eq(%w(cat bird sheep))
end
end
end
describe '#elements_after' do
context 'when the "inclusive" parameter is set to false' do
subject { array.elements_after(element, inclusive: false) }
context 'when the element is included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'returns all elements in the array indexed after the provided parameter' do
expect(subject).to eq(%w(coyote))
end
end
context 'when nil is provided and the array includes a nil element' do
let(:array) { [1, 2, 3, nil, 5] }
let(:element) { nil }
it 'returns the elements after nil' do
expect(subject).to eq([5])
end
end
context 'when the element appears more than once' do
let(:array) { %w(cat bird sheep ferret sheep coyote) }
let(:element) { 'sheep' }
it 'bases the result on the first match of the provided parameter' do
expect(subject).to eq(%w(ferret sheep coyote))
end
end
context 'when the last element is provided' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'coyote' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
context 'when the provided parameter is not included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'buffalo' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
end
context 'when the "inclusive" parameter is set to true' do
subject { array.elements_after(element, inclusive: true) }
context 'when the element is included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'returns the element and all elements in the array indexed after the provided parameter' do
expect(subject).to eq(%w(ferret coyote))
end
end
context 'when nil is provided and the array includes a nil element' do
let(:array) { [1, 2, 3, nil, 5] }
let(:element) { nil }
it 'returns nil and all elements after nil' do
expect(subject).to eq([nil, 5])
end
end
context 'when the element appears more than once' do
let(:array) { %w(cat bird sheep ferret sheep coyote) }
let(:element) { 'sheep' }
it 'bases the result on the first match of the provided parameter' do
expect(subject).to eq(%w(sheep ferret sheep coyote))
end
end
context 'when the last element is provided' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'coyote' }
it 'returns the last element' do
expect(subject).to eq(['coyote'])
end
end
context 'when the provided parameter is not included in the array' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'buffalo' }
it 'returns an empty array' do
expect(subject).to eq([])
end
end
end
context 'when the "inclusive" parameter is not provided' do
subject { array.elements_after(element) }
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'ferret' }
it 'functions as thought the "inclusive" parameter were set to false' do
expect(subject).to eq(%w(coyote))
end
end
end
describe '#element_before' do
subject { array.element_before(element) }
context 'when the element is found and is not the first element' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'sheep' }
it 'returns the element immediately before the provided element' do
expect(subject).to eq('bird')
end
end
context 'when the element is found and is the first element' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'cat' }
it 'returns nil' do
expect(subject).to eq(nil)
end
end
end
describe '#element_after' do
subject { array.element_after(element) }
context 'when the element is found and is not the last element' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'sheep' }
it 'returns the element immediately after the provided element' do
expect(subject).to eq('ferret')
end
end
context 'when the element is found and is the last element' do
let(:array) { %w(cat bird sheep ferret coyote) }
let(:element) { 'coyote' }
it 'returns nil' do
expect(subject).to eq(nil)
end
end
end
describe '#included_before?' do
it 'returns true if the subject element is included in the array indexed prior to the index element' do
array = %w(cat bird sheep ferret coyote)
index_element = 'ferret'
subject_element = 'bird'
expect(array.included_before?(index_element, subject_element)).to eq(true)
end
it 'returns false if the subject element is not included in the array indexed prior to the index element' do
array = %w(cat bird sheep ferret coyote)
index_element = 'ferret'
subject_element = 'coyote'
expect(array.included_before?(index_element, subject_element)).to eq(false)
end
it 'returns false if the index element is not found in the array' do
array = %w(cat bird sheep ferret coyote)
index_element = 'buffalo'
subject_element = 'bird'
expect(array.included_before?(index_element, subject_element)).to eq(false)
end
it 'returns false if the subject element is not found in the array' do
array = %w(cat bird sheep ferret coyote)
index_element = 'sheep'
subject_element = 'buffalo'
expect(array.included_before?(index_element, subject_element)).to eq(false)
end
it 'works as expected when nil is provided as the index element and the subject element appears before' do
array = [1, 2, 3, nil, 5]
index_element = nil
subject_element = 2
expect(array.included_before?(index_element, subject_element)).to eq(true)
end
it 'works as expected when nil is provided as the index element and the subject element does not appear before' do
array = [1, 2, 3, nil, 5]
index_element = nil
subject_element = 5
expect(array.included_before?(index_element, subject_element)).to eq(false)
end
it 'works as expected when nil is provided as the subject element and appears before' do
array = [1, nil, 3, 4, 5]
index_element = 4
subject_element = nil
expect(array.included_before?(index_element, subject_element)).to eq(true)
end
it 'works as expected when nil is provided as the subject element and does not appear before' do
array = [1, 2, 3, 4, 5]
index_element = 4
subject_element = nil
expect(array.included_before?(index_element, subject_element)).to eq(false)
end
end
describe '#included_after?' do
it 'returns true if the subject element is included in the array indexed after the index element' do
array = %w(cat bird sheep ferret coyote)
index_element = 'bird'
subject_element = 'ferret'
expect(array.included_after?(index_element, subject_element)).to eq(true)
end
it 'returns false if the subject element is not included in the array indexed after the index element' do
array = %w(cat bird sheep ferret coyote)
index_element = 'bird'
subject_element = 'cat'
expect(array.included_after?(index_element, subject_element)).to eq(false)
end
it 'returns false if the index element is not found in the array' do
array = %w(cat bird sheep ferret coyote)
index_element = 'buffalo'
subject_element = 'bird'
expect(array.included_after?(index_element, subject_element)).to eq(false)
end
it 'returns false if the subject element is not found in the array' do
array = %w(cat bird sheep ferret coyote)
index_element = 'sheep'
subject_element = 'buffalo'
expect(array.included_after?(index_element, subject_element)).to eq(false)
end
it 'works as expected when nil is provided as the index element and the subject element appears after' do
array = [1, nil, 3, 4, 5]
index_element = nil
subject_element = 4
expect(array.included_after?(index_element, subject_element)).to eq(true)
end
it 'works as expected when nil is provided as the index element and the subject element does not appear after' do
array = [1, 2, 3, nil, 5]
index_element = nil
subject_element = 2
expect(array.included_after?(index_element, subject_element)).to eq(false)
end
it 'works as expected when nil is provided as the subject element and appears after' do
array = [1, 2, 3, nil, 5]
index_element = 2
subject_element = nil
expect(array.included_after?(index_element, subject_element)).to eq(true)
end
it 'works as expected when nil is provided as the subject element and does not appear after' do
array = [1, 2, 3, 4, 5]
index_element = 4
subject_element = nil
expect(array.included_after?(index_element, subject_element)).to eq(false)
end
end
end
| 33.263819 | 118 | 0.630032 | 3.296875 |
0a097baa41ac337d49e83084a248f6a18260547f
| 2,061 |
ts
|
TypeScript
|
src/lib/critical_path/critical_path.ts
|
smoogly/tasklauncher
|
2264c08f7cd5a8350f060e56008e63de5c044a9d
|
[
"MIT"
] | 3 |
2021-11-22T09:04:44.000Z
|
2022-03-04T07:58:14.000Z
|
src/lib/critical_path/critical_path.ts
|
smoogly/tasklauncher
|
2264c08f7cd5a8350f060e56008e63de5c044a9d
|
[
"MIT"
] | null | null | null |
src/lib/critical_path/critical_path.ts
|
smoogly/tasklauncher
|
2264c08f7cd5a8350f060e56008e63de5c044a9d
|
[
"MIT"
] | 1 |
2022-02-14T17:40:10.000Z
|
2022-02-14T17:40:10.000Z
|
import { AnyInput, Task } from "../work_api";
import { Execution } from "../execution";
import { Stats, TaskExecutionStat } from "../parallelize";
import { alignDurations, formatDuration } from "../util/time";
export type CritPathExpectedTaskShape = Task<AnyInput, Execution & { duration: Promise<number | null> }> & { taskName: string };
export async function criticalPath(executionStats: Stats<TaskExecutionStat<CritPathExpectedTaskShape>>) {
if (depth(executionStats) < 2) { return null; } // Ignore all-parallel task trees
const path = calculateCriticalPath(await extractTaskDurations(executionStats));
const totalDuration = formatDuration(path.reduce((tot, stat) => tot + stat.duration, 0));
const align = alignDurations(path.map(({ duration }) => duration));
const pathStr = path.reverse().map(({ name, duration }) => `${ align(duration) } ${ name }`).join("\n");
return { totalDuration, pathStr };
}
type Durations = Stats<{ name: string, duration: number }>;
export async function extractTaskDurations(stats: Stats<TaskExecutionStat<CritPathExpectedTaskShape>>): Promise<Durations> {
const [duration, dependencies] = await Promise.all([stats.stats?.output.duration, Promise.all(stats.dependencies.map(extractTaskDurations))]);
return {
stats: stats.stats && duration ? { name: stats.stats.task.taskName, duration } : null,
dependencies,
};
}
export function depth(stats: Stats<unknown>): number {
const ownIncrement = stats.stats === null ? 0 : 1;
return stats.dependencies.map(depth).reduce((a, b) => Math.max(a, b), 0) + ownIncrement;
}
export function calculateCriticalPath(stats: Durations): { name: string, duration: number }[] {
const tail = !stats.dependencies.length ? [] : stats.dependencies
.map(calculateCriticalPath)
.map(path => ({ path, duration: path.reduce((tot, step) => tot + step.duration, 0) }))
.reduce((a, b) => a.duration > b.duration ? a : b)
.path;
if (!stats.stats) { return tail; }
return [stats.stats, ...tail];
}
| 49.071429 | 146 | 0.683649 | 3.015625 |
3bbea758c7784620aacd7636cf98a167fd38b0b4
| 2,353 |
c
|
C
|
heclib/heclib_c/src/Utilities/numberBytesInCharArray.c
|
HydrologicEngineeringCenter/heclib
|
dd3111ee2a8d0c80b88d21bd529991f154fec40a
|
[
"MIT"
] | 19 |
2021-03-09T17:42:30.000Z
|
2022-03-21T21:46:47.000Z
|
heclib/heclib_c/src/Utilities/numberBytesInCharArray.c
|
HydrologicEngineeringCenter/heclib
|
dd3111ee2a8d0c80b88d21bd529991f154fec40a
|
[
"MIT"
] | 22 |
2021-06-17T20:01:28.000Z
|
2022-03-21T21:33:29.000Z
|
heclib/heclib_c/src/Utilities/numberBytesInCharArray.c
|
HydrologicEngineeringCenter/heclib
|
dd3111ee2a8d0c80b88d21bd529991f154fec40a
|
[
"MIT"
] | 3 |
2021-06-16T17:48:30.000Z
|
2022-01-13T16:44:47.000Z
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "heclib7.h"
int numberBytesInDoubleCharArray(const char **charArray, int numberRows, int numberColumns, int *expandedSize)
{
// Counts the number of bytes in numberStrings null terminated strings in charArray.
// Any character less than 0 is considered filler and ignored.
// If max is set (> 0), then limit that number of bytes
int i;
int j;
int ipos;
int numberBytes;
int len;
int *maxColumnSize;
const char *cstring;
numberBytes = 0;
maxColumnSize = (int *)calloc((size_t)numberColumns, WORD_SIZE);
for (i=0; i<numberRows; i++) {
for (j=0; j<numberColumns; j++) {
ipos = (i * numberColumns) + j;
cstring = charArray[ipos];
len = (int)strlen(cstring) + 1;
numberBytes += len;
if (len > maxColumnSize[j]) {
maxColumnSize[j] = len;
}
}
}
*expandedSize = 0;
for (j=0; j<numberColumns; j++) {
*expandedSize += maxColumnSize[j];
}
*expandedSize *= numberRows;
if (maxColumnSize) {
free(maxColumnSize);
}
return numberBytes;
}
int compressCharArray(const char **charArrayIn, char *charArrayOut, int numberRows, int numberColumns, int max)
{
// Counts the number of bytes in numberStrings null terminated strings in charArray.
// Any character less than 0 is considered filler and ignored.
// If max is set (> 0), then limit that number of bytes
int i;
int j;
int ipos;
int numberBytes;
int len;
const char *cstring;
numberBytes = 0;
for (i=0; i<numberRows; i++) {
for (j=0; j<numberColumns; j++) {
ipos = (i * numberColumns) + j;
cstring = charArrayIn[ipos];
len = (int)strlen(cstring) + 1;
if ((numberBytes + len) > max) {
}
stringCopy(&charArrayOut[numberBytes], (max - numberBytes), cstring, len);
numberBytes += len;
}
}
return numberBytes;
}
int buildTablePointerArray(char *charArrayIn, char **tablePointerArrayOut, int numberRows, int numberColumns, int max)
{
int i;
int j;
int ipos;
int numberBytes;
int len;
char *cstring;
numberBytes = 0;
for (i=0; i<numberRows; i++) {
for (j=0; j<numberColumns; j++) {
cstring = &charArrayIn[numberBytes];
ipos = (i * numberColumns) + j;
tablePointerArrayOut[ipos] = cstring;
len = (int)strlen(cstring) + 1;
numberBytes += len;
if (numberBytes > max) {
// FIX ME
}
}
}
return numberBytes;
}
| 22.409524 | 118 | 0.666383 | 3.328125 |
b2b541552dee04f9e9bcd11e4c109a74ce0c81b7
| 1,697 |
py
|
Python
|
timesketch/lib/cypher/insertable_string.py
|
Marwolf/timesketch
|
8fbbb3d0a5a50dc0214fc56a9bbec82050908103
|
[
"Apache-2.0"
] | null | null | null |
timesketch/lib/cypher/insertable_string.py
|
Marwolf/timesketch
|
8fbbb3d0a5a50dc0214fc56a9bbec82050908103
|
[
"Apache-2.0"
] | null | null | null |
timesketch/lib/cypher/insertable_string.py
|
Marwolf/timesketch
|
8fbbb3d0a5a50dc0214fc56a9bbec82050908103
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2017 Google Inc. All rights reserved.
#
# 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.
"""Module containing the InsertableString class."""
class InsertableString(object):
"""Class that accumulates insert and replace operations for a string and
later performs them all at once so that positions in the original string
can be used in all of the operations.
"""
def __init__(self, input_string):
self.input_string = input_string
self.to_insert = []
def insert_at(self, pos, s):
"""Add an insert operation at given position."""
self.to_insert.append((pos, pos, s))
def replace_range(self, start, end, s):
"""Add a replace operation for given range. Assume that all
replace_range operations are disjoint, otherwise undefined behavior.
"""
self.to_insert.append((start, end, s))
def apply_insertions(self):
"""Return a string obtained by performing all accumulated operations."""
to_insert = reversed(sorted(self.to_insert))
result = self.input_string
for start, end, s in to_insert:
result = result[:start] + s + result[end:]
return result
| 39.465116 | 80 | 0.696523 | 3.09375 |
56949acc22aff33bb3dd24f326bbc4d841b95b4b
| 1,688 |
ts
|
TypeScript
|
src/main/main.ts
|
thenewboston-developers/Wallet
|
2aa3d75c0031f382edeaed3cae5856123bcb77b6
|
[
"MIT"
] | 8 |
2021-09-01T06:05:56.000Z
|
2022-01-10T19:20:22.000Z
|
src/main/main.ts
|
thenewboston-developers/Wallet
|
2aa3d75c0031f382edeaed3cae5856123bcb77b6
|
[
"MIT"
] | 9 |
2021-08-22T12:59:46.000Z
|
2021-11-01T01:10:35.000Z
|
src/main/main.ts
|
thenewboston-developers/Wallet
|
2aa3d75c0031f382edeaed3cae5856123bcb77b6
|
[
"MIT"
] | 1 |
2021-09-26T07:21:28.000Z
|
2021-09-26T07:21:28.000Z
|
/* eslint global-require: off, no-console: off, @typescript-eslint/no-var-requires: off */
/**
* This module executes inside of electron's main process. You can start
* electron renderer process from here and communicate with the other processes
* through IPC.
*
* When running `npm run build` or `npm run build:main`, this file is compiled to
* `./src/main.js` using webpack. This gives us some performance wins.
*/
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import {app, ipcMain} from 'electron';
import AppUpdater from './AppUpdater';
import './ipcMain';
import MainWindow from './MainWindow';
import './Store';
import {isDevelopment} from './util';
export default AppUpdater;
ipcMain.on('ipc-example', async (event, arg) => {
const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
console.log(msgTemplate(arg));
event.reply('ipc-example', msgTemplate('pong'));
});
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
if (isDevelopment) {
require('electron-debug')();
}
/**
* Add event listeners...
*/
app.on('window-all-closed', () => {
// Respect the OSX convention of having the application in memory even
// after all windows have been closed
if (process.platform !== 'darwin') {
app.quit();
}
});
app
.whenReady()
.then(() => {
MainWindow.createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (!MainWindow.exists()) MainWindow.createWindow();
});
})
.catch(console.log);
| 28.133333 | 90 | 0.675948 | 3.0625 |
a35f0bb4674f8d9b57373ad32980024a4004d632
| 8,405 |
kt
|
Kotlin
|
openrndr-ktessellation/src/commonMain/kotlin/Normal.kt
|
reinvdwoerd/openrndr
|
83d7ce4b53b205b54a0cbcae57f60c7a6280d34d
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
openrndr-ktessellation/src/commonMain/kotlin/Normal.kt
|
reinvdwoerd/openrndr
|
83d7ce4b53b205b54a0cbcae57f60c7a6280d34d
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
openrndr-ktessellation/src/commonMain/kotlin/Normal.kt
|
reinvdwoerd/openrndr
|
83d7ce4b53b205b54a0cbcae57f60c7a6280d34d
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
package org.openrndr.ktessellation
import kotlin.math.abs
import kotlin.math.sqrt
internal object Normal {
var SLANTED_SWEEP = false
var S_UNIT_X /* Pre-normalized */ = 0.0
var S_UNIT_Y = 0.0
private const val TRUE_PROJECT = false
private fun Dot(u: DoubleArray, v: DoubleArray): Double {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
}
fun Normalize(v: DoubleArray) {
var len = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]
require(len > 0)
len = sqrt(len)
v[0] /= len
v[1] /= len
v[2] /= len
}
fun LongAxis(v: DoubleArray): Int {
var i = 0
if (abs(v[1]) > abs(v[0])) {
i = 1
}
if (abs(v[2]) > abs(v[i])) {
i = 2
}
return i
}
fun ComputeNormal(tess: GLUtessellatorImpl, norm: DoubleArray) {
var v: GLUvertex
val v1: GLUvertex
val v2: GLUvertex
var c: Double
var tLen2: Double
var maxLen2: Double
val maxVal: DoubleArray
val minVal: DoubleArray
val d1: DoubleArray
val d2: DoubleArray
val tNorm: DoubleArray
val vHead: GLUvertex = tess.mesh!!.vHead
var i: Int
maxVal = DoubleArray(3)
minVal = DoubleArray(3)
val minVert: Array<GLUvertex?> = arrayOfNulls<GLUvertex>(3)
val maxVert: Array<GLUvertex?> = arrayOfNulls<GLUvertex>(3)
d1 = DoubleArray(3)
d2 = DoubleArray(3)
tNorm = DoubleArray(3)
maxVal[2] = -2 * GLU.TESS_MAX_COORD
maxVal[1] = maxVal[2]
maxVal[0] = maxVal[1]
minVal[2] = 2 * GLU.TESS_MAX_COORD
minVal[1] = minVal[2]
minVal[0] = minVal[1]
v = vHead.next?:error("vhead next == null")
while (v !== vHead) {
i = 0
while (i < 3) {
c = v.coords.get(i)
if (c < minVal[i]) {
minVal[i] = c
minVert[i] = v
}
if (c > maxVal[i]) {
maxVal[i] = c
maxVert[i] = v
}
++i
}
v = v.next ?: error("v.next == null")
}
/* Find two vertices separated by at least 1/sqrt(3) of the maximum
* distance between any two vertices
*/i = 0
if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0]) {
i = 1
}
if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i]) {
i = 2
}
if (minVal[i] >= maxVal[i]) {
/* All vertices are the same -- normal doesn't matter */
norm[0] = 0.0
norm[1] = 0.0
norm[2] = 1.0
return
}
/* Look for a third vertex which forms the triangle with maximum area
* (Length of normal == twice the triangle area)
*/maxLen2 = 0.0
v1 = minVert[i] ?: error("minVert[$i] == null")
v2 = maxVert[i] ?: error("maxVert[$i] == null")
d1[0] = v1.coords[0] - v2.coords[0]
d1[1] = v1.coords[1] - v2.coords[1]
d1[2] = v1.coords[2] - v2.coords[2]
v = vHead.next ?: error("vHead.next == null")
while (v !== vHead) {
d2[0] = v.coords[0] - v2.coords[0]
d2[1] = v.coords[1] - v2.coords[1]
d2[2] = v.coords[2] - v2.coords[2]
tNorm[0] = d1[1] * d2[2] - d1[2] * d2[1]
tNorm[1] = d1[2] * d2[0] - d1[0] * d2[2]
tNorm[2] = d1[0] * d2[1] - d1[1] * d2[0]
tLen2 = tNorm[0] * tNorm[0] + tNorm[1] * tNorm[1] + tNorm[2] * tNorm[2]
if (tLen2 > maxLen2) {
maxLen2 = tLen2
norm[0] = tNorm[0]
norm[1] = tNorm[1]
norm[2] = tNorm[2]
}
v = v.next ?: error("v.next == null")
}
if (maxLen2 <= 0) {
/* All points lie on a single line -- any decent normal will do */
norm[2] = 0.0
norm[1] = norm[2]
norm[0] = norm[1]
norm[LongAxis(d1)] = 1.0
}
}
fun CheckOrientation(tess: GLUtessellatorImpl) {
var f: GLUface
val fHead: GLUface = tess.mesh!!.fHead
var v: GLUvertex
val vHead: GLUvertex = tess.mesh!!.vHead
var e: GLUhalfEdge
/* When we compute the normal automatically, we choose the orientation
* so that the the sum of the signed areas of all contours is non-negative.
*/
var area: Double = 0.0
f = fHead.next ?: error("fHead.next == null")
while (f !== fHead) {
e = f.anEdge ?: error("f.anEdge == null")
if (e.winding <= 0) {
f = f.next ?: error("f.next == null")
continue
}
do {
area += (e.Org!!.s - e.Sym!!.Org!!.s) * (e!!.Org!!.t + e!!.Sym!!.Org!!.t)
e = e.Lnext ?: error("e.Lnext == null")
} while (e !== f.anEdge)
f = f.next ?: error("f.next == null")
}
if (area < 0) {
/* Reverse the orientation by flipping all the t-coordinates */
v = vHead.next ?: error("vHead.next == null")
while (v !== vHead) {
v.t = -v.t
v = v.next ?: error("v.next == null")
}
tess.tUnit[0] = -tess.tUnit[0]
tess.tUnit[1] = -tess.tUnit[1]
tess.tUnit[2] = -tess.tUnit[2]
}
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
fun __gl_projectPolygon(tess: GLUtessellatorImpl) {
var v: GLUvertex
val vHead: GLUvertex = tess.mesh!!.vHead
val w: Double
val norm = DoubleArray(3)
val sUnit: DoubleArray
val tUnit: DoubleArray
val i: Int
var computedNormal = false
norm[0] = tess.normal.get(0)
norm[1] = tess.normal.get(1)
norm[2] = tess.normal.get(2)
if (norm[0] == 0.0 && norm[1] == 0.0 && norm[2] == 0.0) {
ComputeNormal(tess, norm)
computedNormal = true
}
sUnit = tess.sUnit
tUnit = tess.tUnit
i = LongAxis(norm)
if (TRUE_PROJECT) {
/* Choose the initial sUnit vector to be approximately perpendicular
* to the normal.
*/
Normalize(norm)
sUnit[i] = 0.0
sUnit[(i + 1) % 3] = S_UNIT_X
sUnit[(i + 2) % 3] = S_UNIT_Y
/* Now make it exactly perpendicular */w = Dot(sUnit, norm)
sUnit[0] -= w * norm[0]
sUnit[1] -= w * norm[1]
sUnit[2] -= w * norm[2]
Normalize(sUnit)
/* Choose tUnit so that (sUnit,tUnit,norm) form a right-handed frame */tUnit[0] =
norm[1] * sUnit[2] - norm[2] * sUnit[1]
tUnit[1] = norm[2] * sUnit[0] - norm[0] * sUnit[2]
tUnit[2] = norm[0] * sUnit[1] - norm[1] * sUnit[0]
Normalize(tUnit)
} else {
/* Project perpendicular to a coordinate axis -- better numerically */
sUnit[i] = 0.0
sUnit[(i + 1) % 3] = S_UNIT_X
sUnit[(i + 2) % 3] = S_UNIT_Y
tUnit[i] = 0.0
tUnit[(i + 1) % 3] = if (norm[i] > 0) -S_UNIT_Y else S_UNIT_Y
tUnit[(i + 2) % 3] = if (norm[i] > 0) S_UNIT_X else -S_UNIT_X
}
/* Project the vertices onto the sweep plane */
v = vHead.next ?: error("vHead.next == null")
while (v !== vHead) {
v.s = Dot(v.coords, sUnit)
v.t = Dot(v.coords, tUnit)
v = v.next ?: error("v.next == null")
}
if (computedNormal) {
CheckOrientation(tess)
}
}
init {
if (SLANTED_SWEEP) {
/* The "feature merging" is not intended to be complete. There are
* special cases where edges are nearly parallel to the sweep line
* which are not implemented. The algorithm should still behave
* robustly (ie. produce a reasonable tesselation) in the presence
* of such edges, however it may miss features which could have been
* merged. We could minimize this effect by choosing the sweep line
* direction to be something unusual (ie. not parallel to one of the
* coordinate axes).
*/
S_UNIT_X = 0.50941539564955385 /* Pre-normalized */
S_UNIT_Y = 0.86052074622010633
} else {
S_UNIT_X = 1.0
S_UNIT_Y = 0.0
}
}
}
| 33.486056 | 89 | 0.491136 | 3.34375 |
699d613d2fddf6861123c679debe540856f77136
| 2,519 |
swift
|
Swift
|
AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift
|
JessieTW2019/watson-developer-cloud
|
37f73e620f3624b4d828704e5a27511a97efe9e7
|
[
"Apache-2.0"
] | null | null | null |
AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift
|
JessieTW2019/watson-developer-cloud
|
37f73e620f3624b4d828704e5a27511a97efe9e7
|
[
"Apache-2.0"
] | null | null | null |
AssistantV1.playground/Pages/Synonyms.xcplaygroundpage/Contents.swift
|
JessieTW2019/watson-developer-cloud
|
37f73e620f3624b4d828704e5a27511a97efe9e7
|
[
"Apache-2.0"
] | null | null | null |
//:## Synonyms
import PlaygroundSupport
// Enable support for asynchronous completion handlers
PlaygroundPage.current.needsIndefiniteExecution = true
import AssistantV1
let assistant = setupAssistantV1()
let workspaceID = WatsonCredentials.AssistantV1Workspace
// Setup
assistant.createEntity(
workspaceID: workspaceID,
entity: "beverage",
values: [
CreateValue(value: "water"),
CreateValue(value: "orange juice"),
CreateValue(value: "soda", synonyms: ["pop", "soft drink"])
])
{
response, error in
guard let entity = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
}
//:### List entity value synonyms
assistant.listSynonyms(workspaceID: workspaceID, entity: "beverage", value: "soda") {
response, error in
guard let synonyms = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonyms)
}
//:### Add entity value synonym
assistant.createSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Get entity value synonym
assistant.getSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Update entity value synonym
assistant.updateSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "OJ",
newSynonym: "O.J.")
{
response, error in
guard let synonym = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(synonym)
}
//:### Delete entity value synonym
assistant.deleteSynonym(
workspaceID: workspaceID,
entity: "beverage",
value: "orange juice",
synonym: "O.J.")
{
_, error in
if let error = error {
print(error.localizedDescription)
return
}
print("synonym deleted")
}
// Cleanup
assistant.deleteEntity(workspaceID: workspaceID, entity: "beverage") {
_, error in
if let error = error {
print(error.localizedDescription)
return
}
}
| 19.679688 | 85 | 0.646288 | 3.375 |
77156586b30ad8debe9639a36c9301b1dd3c0340
| 3,409 |
rs
|
Rust
|
Rust/Fork/math_expr_parser/src/tokenizer.rs
|
TK4E/some
|
48f97e6d660135627fde9c5b564ca83785d5aab4
|
[
"MIT"
] | null | null | null |
Rust/Fork/math_expr_parser/src/tokenizer.rs
|
TK4E/some
|
48f97e6d660135627fde9c5b564ca83785d5aab4
|
[
"MIT"
] | 4 |
2021-11-04T02:48:04.000Z
|
2021-11-04T03:33:12.000Z
|
Rust/Fork/math_expr_parser/src/tokenizer.rs
|
TK4E/some
|
48f97e6d660135627fde9c5b564ca83785d5aab4
|
[
"MIT"
] | null | null | null |
use std::collections::VecDeque;
use std::fmt;
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub enum Op {
Mul,
Div,
Sub,
Add,
Pow,
}
impl fmt::Display for Op {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
let s = match self {
Op::Mul => "*",
Op::Div => "/",
Op::Sub => "-",
Op::Add => "+",
Op::Pow => "^",
};
write!(f, "{}", s)
}
}
#[derive(Debug,Clone,Copy)]
pub enum Token {
Digit(f64),
Bracket(bool),
Op(Op),
}
fn digit_checker(ch: char) -> bool {
ch.is_ascii_digit() || ch == '.'
}
fn space_checker(ch: char) -> bool {
ch.is_whitespace()
}
#[derive(Debug)]
pub struct Tokenizer {
stack: VecDeque<Token>,
pointer: usize,
}
impl Tokenizer {
pub fn tokenize(s: &str) -> Result<VecDeque<Token>, String> {
let mut t = Tokenizer {
pointer: 0,
stack: VecDeque::with_capacity(s.len()),
};
let s_len = s.len();
while t.pointer < s_len {
t.read(s)?;
// t.trim();
}
t.stack.shrink_to_fit();
Ok(t.stack)
}
fn push(&mut self, token: Token, count: usize) {
self.stack.push_back(token);
self.pointer += count;
}
fn read(&mut self, src: &str) -> Result<(), String> {
let s = &src[self.pointer..];
let ch = s.chars().nth(0).unwrap();
let next = s.chars().nth(1);
match ch {
' ' => {
self.pointer += 1;
}
'(' => self.push(Token::Bracket(true), 1),
')' => self.push(Token::Bracket(false), 1),
'*' => self.push(Token::Op(Op::Mul), 1),
'/' => self.push(Token::Op(Op::Div), 1),
'^' => self.push(Token::Op(Op::Pow), 1),
'+' => {
if let Some(n) = next {
if !space_checker(n) {
self.pointer += 1;
return Ok(());
}
}
self.push(Token::Op(Op::Add), 1)
},
'-' => {
self.handle_sub(next)?;
},
x if x.is_ascii_digit() => self.handle_digit(s)?,
_ => return Err(format!("unrecognized input `{}` at position {}", ch, self.pointer + 1)),
}
Ok(())
}
fn handle_digit(&mut self, s_part: &str) -> Result<(), String> {
let (digit_str, digit_str_len) = Tokenizer::take_while(s_part, digit_checker);
if let Ok(d) = digit_str.parse() {
self.push(Token::Digit(d), digit_str_len);
Ok(())
} else {
Err(format!("cannot parse digit `{}` at position {}", digit_str, self.pointer + 1))
}
}
fn handle_sub(&mut self, next_ch: Option<char> ) -> Result<(), String> {
if let Some(n) = next_ch {
if !space_checker(n) {
if digit_checker(n) || n == '(' {
self.push(Token::Digit(-1.0), 0);
self.push(Token::Op(Op::Mul), 1);
return Ok(());
} else {
return Err(format!("invalid operation sequence at position {}", self.pointer + 1));
}
}
self.push(Token::Op(Op::Sub), 1);
Ok(())
} else {
Err(format!("invalid end with operation `-` at position {}", self.pointer + 1))
}
}
fn take_while<F>(s: &str, checker: F) -> (&str, usize)
where
F: Fn(char) -> bool,
{
let len = s.len();
let mut idx = 1;
if idx < len {
let mut ch = s.chars().nth(idx).unwrap();
while checker(ch) {
idx += 1;
if idx == len {
break;
}
ch = s.chars().nth(idx).unwrap();
}
}
(&s[..idx], idx)
}
}
| 22.281046 | 95 | 0.503667 | 3.40625 |
a1a02d10d7b08de4eef96cb3a6933fa8e088b71d
| 1,415 |
c
|
C
|
Class-2/Process.C/process-file/main.c
|
Phoebus-Ma/C-Helper
|
14455116e1762dba12698e3d21bf0c28b4f90558
|
[
"MIT"
] | null | null | null |
Class-2/Process.C/process-file/main.c
|
Phoebus-Ma/C-Helper
|
14455116e1762dba12698e3d21bf0c28b4f90558
|
[
"MIT"
] | null | null | null |
Class-2/Process.C/process-file/main.c
|
Phoebus-Ma/C-Helper
|
14455116e1762dba12698e3d21bf0c28b4f90558
|
[
"MIT"
] | null | null | null |
/**
* C process use file communication example.
*
* License - MIT.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#define TEMP_FILE_NAME "communication.tmp"
/**
* child_process_function - Read data from file.
*/
int child_process_function(void)
{
int fd = -1;
char buf[32 + 1] = { 0 };
sleep(1);
fd = open(TEMP_FILE_NAME, O_RDONLY);
if (0 > fd) {
printf("Error in open.");
return -1;
}
read(fd, buf, 32);
printf("Child process read: %s.\n", buf);
close(fd);
return 0;
}
/**
* parent_process_function - Write data to file.
*/
int parent_process_function(void)
{
int fd = open(TEMP_FILE_NAME, O_WRONLY | O_CREAT, 0664);
if (0 > fd) {
printf("Error in open.");
return -1;
}
printf("Parent process write: Hello.\n");
write(fd, "Hello", 5 + 1);
close(fd);
return 0;
}
/**
* Main function.
*/
int main(void)
{
pid_t pid = -1;
pid = fork();
switch (pid)
{
case -1:
printf("Error in fork.\n");
break;
/* Child process. */
case 0:
child_process_function();
exit(0);
break;
/* Parent process. */
default:
parent_process_function();
wait(NULL);
break;
}
return 0;
}
| 14.894737 | 60 | 0.540636 | 3.21875 |
04f873836f05feb785301c63c970bec935606b98
| 1,373 |
sql
|
SQL
|
SummerNoteApi&S3/sql/summernote.sql
|
nob0dj/springWebAPI
|
f43546dcd102cdecd326ea8bf34b407a4d134004
|
[
"BSD-3-Clause"
] | null | null | null |
SummerNoteApi&S3/sql/summernote.sql
|
nob0dj/springWebAPI
|
f43546dcd102cdecd326ea8bf34b407a4d134004
|
[
"BSD-3-Clause"
] | 14 |
2020-03-04T21:44:27.000Z
|
2021-12-09T20:50:57.000Z
|
SummerNoteApi&S3/sql/summernote.sql
|
nob0dj/springWebAPI
|
f43546dcd102cdecd326ea8bf34b407a4d134004
|
[
"BSD-3-Clause"
] | 1 |
2019-08-05T01:06:58.000Z
|
2019-08-05T01:06:58.000Z
|
--==============================================================
-- summernote테이블 생성
--==============================================================
create table summernote(
id number,
writer varchar2(256), --글쓴이: not null처리 안함
contents clob, --내용: not null처리 안함
reg_date date default sysdate,
is_temp char(1) default 'N', --임시파일여부
constraint pk_summernote primary key(id),
constraint ck_summernote check(is_temp in('Y','N'))
);
create sequence seq_summernote;
select * from summernote order by id desc;
--==============================================================
-- s3object 테이블 생성
--==============================================================
--s3에 업로드된 파일은 객체(object)라고 부른다.
create table s3object(
id number,
original_filename varchar2(256) not null,
renamed_filename varchar2(256) not null,
resource_url varchar2(512) not null,
content_type varchar2(256),
file_size number,
download_count number default 0,
reg_date date default sysdate,
constraint pk_s3object primary key(id)
);
--drop table s3object;
--truncate table s3object;
create sequence seq_s3object;
select
*
from
summernote;
--delete from summernote where is_temp = 'Y';
--commit;
select
*
from
s3object
order by id desc;
| 26.921569 | 65 | 0.530226 | 3 |
2a3a6a96bf78f31928778743515b597ad0e548ea
| 3,402 |
java
|
Java
|
Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java
|
rainmaple/WIFI_BussinessBigDataAnalyseSystem
|
c65e1bd467bc43ef608d3913de60f11f7779b63d
|
[
"MIT"
] | 36 |
2018-05-17T06:35:07.000Z
|
2021-11-17T11:29:53.000Z
|
Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java
|
SunWenBiao/WIFI_BussinessBigDataAnalyseSystem
|
d732f48b894fa0242e817e449896290dca4ea5e6
|
[
"MIT"
] | 2 |
2018-08-03T09:30:53.000Z
|
2019-09-16T01:52:44.000Z
|
Program source code/Receive_server_ web_page_request_server_source_code/web03/src/handle/NewOldHandler.java
|
SunWenBiao/WIFI_BussinessBigDataAnalyseSystem
|
d732f48b894fa0242e817e449896290dca4ea5e6
|
[
"MIT"
] | 21 |
2018-06-12T07:50:55.000Z
|
2021-01-14T09:09:58.000Z
|
package handle;
import dao.DaoUtil;
public class NewOldHandler {
private static String TABLE_NAME="new_old";
public static String GetRate(){
String[] qua={"1"};
String New=DaoUtil.getValueByFamily(TABLE_NAME,"1","new",qua)[0];
String Old=DaoUtil.getValueByFamily(TABLE_NAME,"1","old",qua)[0];
return String.format("%.2f",Double.valueOf(New)/(Double.valueOf(New)+Double.valueOf(Old))*100);
}
protected static String[] RateFormat(String[] rate){
String[] format=new String[rate.length];
for(int i=0;i<=rate.length-1;i++){
if(rate[i]!=null) format[i]=String.format("%.2f", Double.valueOf(rate[i]));
else{
format[i]=null;
}
}
return format;
}
public static String[] GetNewNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
return DaoUtil.getValueByFamily(TABLE_NAME,"1","new",qua);
}
public static String[] GetOldNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
return DaoUtil.getValueByFamily(TABLE_NAME,"1","old",qua);
}
public static double[] GetHisRate() {
double[] rate=new double[4];
String[] qua={"1"};
String[] Family="h_hour,h_day,h_week,h_month".split(",");
for(int i=0;i<=3;i++){
rate[i] = Double.valueOf(DaoUtil.getValueByFamily(TABLE_NAME,"1",Family[i],qua)[0]);
}
return rate;
}
public static String[] FormatRate(double[] rate) {
String[] result=new String[rate.length];
for(int i=0;i<=rate.length-1;i++){
result[i]=String.format("%.2f", rate[i]);
}
return result;
}
public static String[] GetRateStatus(double[] r) {
String[] result=new String[r.length];
for(int i=0;i<=r.length-1;i++){
if(r[i]>0.5){
result[i]="正常";
}else{
result[i]="衰退";
}
}
return result;
}
public static String[] GetHourNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","hour",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetDayNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","day",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetWeekNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","week",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
public static String[] GetMonthNum(int length){
String[] qua=new String[length];
for(int i=0;i<=length-1;i++){
qua[i]=String.valueOf(length-i);
}
String[] data=DaoUtil.getValueByFamily(TABLE_NAME,"1","month",qua);
if(data!=null){
for(int i=0;i<=data.length-1;i++){
if(data[i]!=null)data[i]=String.valueOf(Double.valueOf(data[i])*100);
}
}
return RateFormat(data);
}
}
| 28.115702 | 97 | 0.649618 | 3.390625 |
fb41d767ec9ac3a14599e66a987d942e1f329cc5
| 7,243 |
go
|
Go
|
main_test.go
|
andrzejressel/ResumeFodder
|
d9a0dafec775c1a2cbce451703b63b7d36e9306b
|
[
"MIT"
] | 1 |
2021-11-25T13:29:43.000Z
|
2021-11-25T13:29:43.000Z
|
main_test.go
|
andrzejressel/ResumeFodder
|
d9a0dafec775c1a2cbce451703b63b7d36e9306b
|
[
"MIT"
] | null | null | null |
main_test.go
|
andrzejressel/ResumeFodder
|
d9a0dafec775c1a2cbce451703b63b7d36e9306b
|
[
"MIT"
] | null | null | null |
package main
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/andrzejressel/ResumeFodder/command"
"github.com/andrzejressel/ResumeFodder/data"
"github.com/andrzejressel/ResumeFodder/testutils"
)
func TestNoArgs(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe"})
if err == nil || err.Error() != "No command was specified." {
t.Fatalf("err should be [No command was specified.], found [%s]\n", err)
}
}
func TestInit_NoArg(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "init"})
if command != "init" {
t.Fatalf("command should be [init], found [%s]\n", command)
}
if len(args) != 1 || args[0] != "resume.json" {
t.Fatalf("args should be [resume.json], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestInit_InvalidFilename(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "init", "bad_extension.foo"})
if err == nil || err.Error() != "Filename to initialize must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Filename to initialize must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
}
func TestInit_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "init", "resume.xml"})
if command != "init" {
t.Fatalf("command should be [init], found [%s]\n", command)
}
if len(args) != 1 || args[0] != "resume.xml" {
t.Fatalf("args should be [resume.xml], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestConvert_NoArgs(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "convert"})
if err == nil || err.Error() != "You must specify input and output filenames (e.g. \"ResumeFodder.exe convert resume.json resume.xml\")" {
t.Fatalf("err should be [You must specify input and output filenames (e.g. \"ResumeFodder.exe convert resume.json resume.xml\")], found [%s]\n", err)
}
}
func TestConvert_InvalidFilename(t *testing.T) {
// Source and target must be XML or JSON
_, _, err := ParseArgs([]string{"resume.exe", "convert", "bad_extension.foo", "resume.json"})
if err == nil || err.Error() != "Source file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Source file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.xml", "bad_extension.foo"})
if err == nil || err.Error() != "Target file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Target file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
// Conversion from one format must be to the other
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.xml", "copy.xml"})
if err == nil || err.Error() != "When converting an XML source file, the target filename must have a '.json' extension" {
t.Fatalf("err should be [When converting an XML source file, the target filename must have a '.json' extension], found [%s]\n", err)
}
_, _, err = ParseArgs([]string{"resume.exe", "convert", "resume.json", "copy.json"})
if err == nil || err.Error() != "When converting a JSON source file, the target filename must have an '.xml' extension" {
t.Fatalf("err should be [When converting a JSON source file, the target filename must have an '.xml' extension], found [%s]\n", err)
}
}
func TestConvert_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "convert", "resume.xml", "resume.json"})
if command != "convert" {
t.Fatalf("command should be [convert], found [%s]\n", command)
}
if len(args) != 2 || args[0] != "resume.xml" || args[1] != "resume.json" {
t.Fatalf("args should be [resume.xml resume.json], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
func TestExport_NoArg(t *testing.T) {
_, _, err := ParseArgs([]string{"resume.exe", "export"})
if err == nil || err.Error() != "You must specify input and output filenames (e.g. \"ResumeFodder.exe export resume.json resume.doc\"), and optionally a template name." {
t.Fatalf("err should be [You must specify input and output filenames (e.g. \"ResumeFodder.exe export resume.json resume.doc\"), and optionally a template name.], found [%s]\n", err)
}
}
func TestExport_InvalidSourceFilename(t *testing.T) {
// Source must be XML or JSON
_, _, err := ParseArgs([]string{"resume.exe", "export", "bad_extension.foo", "resume.doc"})
if err == nil || err.Error() != "Source file must have a '.json' or '.xml' extension." {
t.Fatalf("err should be [Source file must have a '.json' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_InvalidTargetFilename(t *testing.T) {
// Target must be DOC or XML
_, _, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "bad_extension.foo"})
if err == nil || err.Error() != "Target file must have a '.doc' or '.xml' extension." {
t.Fatalf("err should be [Target file must have a '.doc' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_InvalidTemplateFilename(t *testing.T) {
// Template must be DOC or XML
_, _, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc", "templates/bad_extension.foo"})
if err == nil || err.Error() != "Template file must have a '.doc' or '.xml' extension." {
t.Fatalf("err should be [Template file must have a '.doc' or '.xml' extension.], found [%s]\n", err)
}
}
func TestExport_NoTemplateFilename(t *testing.T) {
_, args, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc"})
if err != nil {
t.Fatal(err)
}
if args[2] != "standard.xml" {
t.Fatal(errors.New("When no template file is specified, the default value of \"standard.xml\" should be used"))
}
}
func TestExport_Valid(t *testing.T) {
command, args, err := ParseArgs([]string{"resume.exe", "export", "resume.xml", "resume.doc", "templates/default.xml"})
if command != "export" {
t.Fatalf("command should be [export], found [%s]\n", command)
}
if len(args) != 3 || args[0] != "resume.xml" || args[1] != "resume.doc" || args[2] != "templates/default.xml" {
t.Fatalf("args should be [resume.xml resume.json templates/default.xml], found %s\n", args)
}
if err != nil {
t.Fatalf("err should be nil, found [%s]\n", err)
}
}
// Tests that when the export command can't find a template at the specified location, that the command will try
// prepending that with the "templates" directory. This test logically belongs in the "command/command_test.go" test
// file within the base "ResumeFodder" project, but instead lives here because it requires the current working
// directory to be the project root.
func TestExportResumeFile_TemplateDefaultPath(t *testing.T) {
xmlFilename := filepath.Join(os.TempDir(), "testresume.xml")
testutils.DeleteFileIfExists(t, xmlFilename)
defer testutils.DeleteFileIfExists(t, xmlFilename)
resumeData := testutils.GenerateTestResumeData()
err := data.ToXmlFile(resumeData, xmlFilename)
if err != nil {
t.Fatal(err)
}
outputFilename := filepath.Join(os.TempDir(), "resume.doc")
templateFilename := "standard.xml"
err = command.ExportResumeFile(xmlFilename, outputFilename, templateFilename)
if err != nil {
t.Fatal(err)
}
}
| 42.110465 | 183 | 0.666022 | 3.046875 |
62bd4fc1127fff41ad17f17e29783ba1e312deac
| 5,271 |
swift
|
Swift
|
Sources/Pipable/Pipable.swift
|
ColdGrub1384/Pipable
|
657043e43cec85552590ad10cca4fd2b2bebcc86
|
[
"MIT"
] | 3 |
2021-11-17T05:01:34.000Z
|
2022-02-24T05:22:01.000Z
|
Sources/Pipable/Pipable.swift
|
ColdGrub1384/Pipable
|
657043e43cec85552590ad10cca4fd2b2bebcc86
|
[
"MIT"
] | null | null | null |
Sources/Pipable/Pipable.swift
|
ColdGrub1384/Pipable
|
657043e43cec85552590ad10cca4fd2b2bebcc86
|
[
"MIT"
] | 2 |
2021-11-17T05:01:34.000Z
|
2021-11-19T01:03:12.000Z
|
import UIKit
import AVKit
/// A protocol for implementing Picture in Picture in a`UIView`.
///
/// If a view conforms to this protocol, it is automatically compatible with Picture in Picture.
/// An instance of `AVPictureInPictureController` is automatically created for the view, which allows entering and exiting PIP. Each time the content of the view is changed, you must call `updatePictureInPictureSnapshot`.
@available(iOS 15.0, *)
public protocol Pipable where Self: UIView {
/// The delegate for the PIP events.
var pictureInPictureDelegate: PictureInPictureDelegate? { get set }
/// The size of the preview displayed in Picture in Picture.
/// You can return the size of the target view to keep the same aspect ratio, but text content may not be easily readable.
/// You can also return a different size. If you do so, the view will be resized while taking the snapshots.
var previewSize: CGSize { get }
/// Called before a snapshot is taken. Setup the view if necessary.
func willTakeSnapshot()
/// Called after taking a snapshot. Undo the changes done on `willTakeSnapshot` if necessary.
func didTakeSnapshot()
}
@available(iOS 15.0, *)
extension Pipable {
/// The Picture in Picture controller created automatically by conforming to `Pipable`. Use this object to start or exit PIP. Before entering PIP, the application must start a playback `AVAudioSession`, which requires a background mode.
public var pictureInPictureController: AVPictureInPictureController? {
setupPlayerIfNeeded()
return player?.pipController
}
/// Updates the snapshot displayed in PIP. You may want to call this method everytime the content of a `UITextView` changes for example.
/// While taking it, the view will be resized to `previewSize`.
public func updatePictureInPictureSnapshot() {
setupPlayerIfNeeded()
player?.frame.size = frame.size
(player?.layer as? AVSampleBufferDisplayLayer)?.flush()
willTakeSnapshot()
(player?.layer as? AVSampleBufferDisplayLayer)?.enqueue(getSnapshot())
didTakeSnapshot()
}
}
/// A set of method to respond to PIP events.
@available(iOS 9, *)
public protocol PictureInPictureDelegate where Self: AnyObject {
/// User entered PIP.
func didEnterPictureInPicture()
/// User exited PIP.
func didExitPictureInPicture()
/// PIP failed to start.
func didFailToEnterPictureInPicture(error: Error)
/// Called when the user presses the pause button.
func didPause()
/// Called when the user presses the resume button.
func didResume()
/// Return`true` to show the pause button and `false` to show the play button.
var isPlaying: Bool { get }
}
@available(iOS 15.0, *)
extension Pipable {
var player: PlayerView? {
subviews.first(where: { $0 is PlayerView }) as? PlayerView
}
func setupPlayerIfNeeded() {
if player == nil {
let playerView = PlayerView()
playerView.delegate = pictureInPictureDelegate
playerView.isHidden = true
playerView.pipController = AVPictureInPictureController(contentSource: .init(sampleBufferDisplayLayer: playerView.layer as! AVSampleBufferDisplayLayer, playbackDelegate: playerView))
playerView.pipController?.delegate = playerView
addSubview(playerView)
}
player?.delegate = pictureInPictureDelegate
}
func getSnapshot() -> CMSampleBuffer {
let size = frame.size
let constraints = superview?.constraints ?? []
for constraint in constraints {
superview?.removeConstraint(constraint)
}
frame.size = previewSize
let snapshot = createSampleBufferFrom(pixelBuffer: buffer(from: asImage())!)!
frame.size = size
for constraint in constraints {
superview?.addConstraint(constraint)
}
return snapshot
}
}
@available(iOS 15.0, *)
extension Pipable {
func asImage() -> UIImage {
var offset: CGPoint?
if let scrollView = self as? UIScrollView {
offset = scrollView.contentOffset
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
if bottomOffset.y >= 0 {
scrollView.contentOffset = bottomOffset
}
}
let superview = self.superview
let index = self.subviews.firstIndex(of: self)
if window?.windowScene?.activationState == .background {
removeFromSuperview()
}
let renderer = UIGraphicsImageRenderer(bounds: bounds)
let image = renderer.image {
rendererContext in
layer.render(in: rendererContext.cgContext)
}
if offset != nil {
(self as? UIScrollView)?.contentOffset = offset!
}
if self.superview == nil {
superview?.insertSubview(self, at: index ?? 0)
}
return image
}
}
| 33.788462 | 240 | 0.641055 | 3.046875 |
b2e0de9c060c5c18b08f58d054b60642948a19ab
| 13,975 |
py
|
Python
|
SViTE/backup/sparselearning/snip.py
|
VITA-Group/SViTE
|
b0c62fd153c8b0b99917ab935ee76925c9de1149
|
[
"MIT"
] | 50 |
2021-05-29T00:52:45.000Z
|
2022-03-17T11:39:47.000Z
|
SViTE/backup/sparselearning/snip.py
|
VITA-Group/SViTE
|
b0c62fd153c8b0b99917ab935ee76925c9de1149
|
[
"MIT"
] | 2 |
2022-01-16T07:24:52.000Z
|
2022-03-29T01:56:24.000Z
|
SViTE/backup/sparselearning/snip.py
|
VITA-Group/SViTE
|
b0c62fd153c8b0b99917ab935ee76925c9de1149
|
[
"MIT"
] | 6 |
2021-06-27T22:24:16.000Z
|
2022-01-17T02:45:32.000Z
|
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import math
import copy
import types
def fgsm_attack(image, epsilon, data_grad):
print('Attacking...')
# Collect the element-wise sign of the data gradient
sign_data_grad = data_grad.sign()
# Create the perturbed image by adjusting each pixel of the input image
perturbed_image = image + epsilon*sign_data_grad
# Adding clipping to maintain [0,1] range
perturbed_image = torch.clamp(perturbed_image, 0, 1)
# Return the perturbed image
return perturbed_image
def snip_forward_conv2d(self, x):
return F.conv2d(x, self.weight * self.weight_mask, self.bias,
self.stride, self.padding, self.dilation, self.groups)
def snip_forward_linear(self, x):
return F.linear(x, self.weight * self.weight_mask, self.bias)
def SNIP(net, keep_ratio, train_dataloader, device):
# TODO: shuffle?
# Grab a single batch from the training dataset
inputs, targets = next(iter(train_dataloader))
inputs = inputs.to(device)
targets = targets.to(device)
inputs.requires_grad = True
# Let's create a fresh copy of the network so that we're not worried about
# affecting the actual training-phase
net = copy.deepcopy(net)
# Monkey-patch the Linear and Conv2d layer to learn the multiplicative mask
# instead of the weights
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
layer.weight_mask = nn.Parameter(torch.ones_like(layer.weight))
nn.init.xavier_normal_(layer.weight)
layer.weight.requires_grad = False
# Override the forward methods:
if isinstance(layer, nn.Conv2d):
layer.forward = types.MethodType(snip_forward_conv2d, layer)
if isinstance(layer, nn.Linear):
layer.forward = types.MethodType(snip_forward_linear, layer)
# Compute gradients (but don't apply them)
net.zero_grad()
outputs = net.forward(inputs)
loss = F.nll_loss(outputs, targets)
loss.backward()
grads_abs = []
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grads_abs.append(torch.abs(layer.weight_mask.grad))
# Gather all scores in a single vector and normalise
all_scores = torch.cat([torch.flatten(x) for x in grads_abs])
norm_factor = torch.sum(all_scores)
all_scores.div_(norm_factor)
num_params_to_keep = int(len(all_scores) * keep_ratio)
threshold, _ = torch.topk(all_scores, num_params_to_keep, sorted=True)
acceptable_score = threshold[-1]
keep_masks = []
for g in grads_abs:
keep_masks.append(((g / norm_factor) >= acceptable_score).float())
print(torch.sum(torch.cat([torch.flatten(x == 1) for x in keep_masks])))
return keep_masks
def SNIP_training(net, keep_ratio, train_dataloader, device, masks, death_rate):
# TODO: shuffle?
# Grab a single batch from the training dataset
inputs, targets = next(iter(train_dataloader))
inputs = inputs.to(device)
targets = targets.to(device)
print('Pruning rate:', death_rate)
# Let's create a fresh copy of the network so that we're not worried about
# affecting the actual training-phase
net = copy.deepcopy(net)
# Monkey-patch the Linear and Conv2d layer to learn the multiplicative mask
# instead of the weights
# for layer in net.modules():
# if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
# layer.weight_mask = nn.Parameter(torch.ones_like(layer.weight))
# # nn.init.xavier_normal_(layer.weight)
# # layer.weight.requires_grad = False
#
# # Override the forward methods:
# if isinstance(layer, nn.Conv2d):
# layer.forward = types.MethodType(snip_forward_conv2d, layer)
#
# if isinstance(layer, nn.Linear):
# layer.forward = types.MethodType(snip_forward_linear, layer)
# Compute gradients (but don't apply them)
net.zero_grad()
outputs = net.forward(inputs)
loss = F.nll_loss(outputs, targets)
loss.backward()
grads_abs = []
masks_copy = []
new_masks = []
for name in masks:
masks_copy.append(masks[name])
index = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
# clone mask
mask = masks_copy[index].clone()
num_nonzero = (masks_copy[index] != 0).sum().item()
num_zero = (masks_copy[index] == 0).sum().item()
# calculate score
scores = torch.abs(layer.weight.grad * layer.weight * masks_copy[index]) # weight * grad
norm_factor = torch.sum(scores)
scores.div_(norm_factor)
x, idx = torch.sort(scores.data.view(-1))
num_remove = math.ceil(death_rate * num_nonzero)
k = math.ceil(num_zero + num_remove)
if num_remove == 0.0: return masks_copy[index] != 0.0
mask.data.view(-1)[idx[:k]] = 0.0
new_masks.append(mask)
index += 1
return new_masks
def GraSP_fetch_data(dataloader, num_classes, samples_per_class):
datas = [[] for _ in range(num_classes)]
labels = [[] for _ in range(num_classes)]
mark = dict()
dataloader_iter = iter(dataloader)
while True:
inputs, targets = next(dataloader_iter)
for idx in range(inputs.shape[0]):
x, y = inputs[idx:idx+1], targets[idx:idx+1]
category = y.item()
if len(datas[category]) == samples_per_class:
mark[category] = True
continue
datas[category].append(x)
labels[category].append(y)
if len(mark) == num_classes:
break
X, y = torch.cat([torch.cat(_, 0) for _ in datas]), torch.cat([torch.cat(_) for _ in labels]).view(-1)
return X, y
def count_total_parameters(net):
total = 0
for m in net.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
total += m.weight.numel()
return total
def count_fc_parameters(net):
total = 0
for m in net.modules():
if isinstance(m, (nn.Linear)):
total += m.weight.numel()
return total
def GraSP(net, ratio, train_dataloader, device, num_classes=10, samples_per_class=25, num_iters=1, T=200, reinit=True):
eps = 1e-10
keep_ratio = ratio
old_net = net
net = copy.deepcopy(net) # .eval()
net.zero_grad()
weights = []
total_parameters = count_total_parameters(net)
fc_parameters = count_fc_parameters(net)
# rescale_weights(net)
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
if isinstance(layer, nn.Linear) and reinit:
nn.init.xavier_normal(layer.weight)
weights.append(layer.weight)
inputs_one = []
targets_one = []
grad_w = None
for w in weights:
w.requires_grad_(True)
print_once = False
for it in range(num_iters):
print("(1): Iterations %d/%d." % (it, num_iters))
inputs, targets = GraSP_fetch_data(train_dataloader, num_classes, samples_per_class)
N = inputs.shape[0]
din = copy.deepcopy(inputs)
dtarget = copy.deepcopy(targets)
inputs_one.append(din[:N//2])
targets_one.append(dtarget[:N//2])
inputs_one.append(din[N // 2:])
targets_one.append(dtarget[N // 2:])
inputs = inputs.to(device)
targets = targets.to(device)
outputs = net.forward(inputs[:N//2])/T
if print_once:
# import pdb; pdb.set_trace()
x = F.softmax(outputs)
print(x)
print(x.max(), x.min())
print_once = False
loss = F.cross_entropy(outputs, targets[:N//2])
# ===== debug ================
grad_w_p = autograd.grad(loss, weights)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
outputs = net.forward(inputs[N // 2:])/T
loss = F.cross_entropy(outputs, targets[N // 2:])
grad_w_p = autograd.grad(loss, weights, create_graph=False)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
ret_inputs = []
ret_targets = []
for it in range(len(inputs_one)):
print("(2): Iterations %d/%d." % (it, num_iters))
inputs = inputs_one.pop(0).to(device)
targets = targets_one.pop(0).to(device)
ret_inputs.append(inputs)
ret_targets.append(targets)
outputs = net.forward(inputs)/T
loss = F.cross_entropy(outputs, targets)
# ===== debug ==============
grad_f = autograd.grad(loss, weights, create_graph=True)
z = 0
count = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
z += (grad_w[count].data * grad_f[count]).sum()
count += 1
z.backward()
grads = dict()
old_modules = list(old_net.modules())
for idx, layer in enumerate(net.modules()):
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grads[old_modules[idx]] = -layer.weight.data * layer.weight.grad # -theta_q Hg
# Gather all scores in a single vector and normalise
all_scores = torch.cat([torch.flatten(x) for x in grads.values()])
norm_factor = torch.abs(torch.sum(all_scores)) + eps
print("** norm factor:", norm_factor)
all_scores.div_(norm_factor)
num_params_to_rm = int(len(all_scores) * (1-keep_ratio))
threshold, _ = torch.topk(all_scores, num_params_to_rm, sorted=True)
# import pdb; pdb.set_trace()
acceptable_score = threshold[-1]
print('** accept: ', acceptable_score)
keep_masks = []
for m, g in grads.items():
keep_masks.append(((g / norm_factor) <= acceptable_score).float())
# print(torch.sum(torch.cat([torch.flatten(x == 1) for x in keep_masks.values()])))
return keep_masks
def GraSP_Training(net, ratio, train_dataloader, device, num_classes=10, samples_per_class=25, num_iters=1, T=200, reinit=False):
eps = 1e-10
death_rate = ratio
net = copy.deepcopy(net) # .eval()
net.zero_grad()
weights = []
# rescale_weights(net)
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
if isinstance(layer, nn.Linear) and reinit:
nn.init.xavier_normal(layer.weight)
weights.append(layer.weight)
inputs_one = []
targets_one = []
grad_w = None
for w in weights:
w.requires_grad_(True)
print_once = False
for it in range(num_iters):
print("(1): Iterations %d/%d." % (it, num_iters))
inputs, targets = GraSP_fetch_data(train_dataloader, num_classes, samples_per_class)
N = inputs.shape[0]
din = copy.deepcopy(inputs)
dtarget = copy.deepcopy(targets)
inputs_one.append(din[:N//2])
targets_one.append(dtarget[:N//2])
inputs_one.append(din[N // 2:])
targets_one.append(dtarget[N // 2:])
inputs = inputs.to(device)
targets = targets.to(device)
outputs = net.forward(inputs[:N//2])/T
if print_once:
# import pdb; pdb.set_trace()
x = F.softmax(outputs)
print(x)
print(x.max(), x.min())
print_once = False
loss = F.cross_entropy(outputs, targets[:N//2])
# ===== debug ================
grad_w_p = autograd.grad(loss, weights)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
outputs = net.forward(inputs[N // 2:])/T
loss = F.cross_entropy(outputs, targets[N // 2:])
grad_w_p = autograd.grad(loss, weights, create_graph=False)
if grad_w is None:
grad_w = list(grad_w_p)
else:
for idx in range(len(grad_w)):
grad_w[idx] += grad_w_p[idx]
ret_inputs = []
ret_targets = []
for it in range(len(inputs_one)):
print("(2): Iterations %d/%d." % (it, num_iters))
inputs = inputs_one.pop(0).to(device)
targets = targets_one.pop(0).to(device)
ret_inputs.append(inputs)
ret_targets.append(targets)
outputs = net.forward(inputs)/T
loss = F.cross_entropy(outputs, targets)
# ===== debug ==============
grad_f = autograd.grad(loss, weights, create_graph=True)
z = 0
count = 0
for layer in net.modules():
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
z += (grad_w[count].data * grad_f[count]).sum()
count += 1
z.backward()
keep_masks = []
for idx, layer in enumerate(net.modules()):
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear):
grad = -layer.weight.data * layer.weight.grad
# scores = torch.flatten(grad) # -theta_q Hg
mask = grad != 0
num_nonzero = (grad != 0).sum().item()
num_positive = (grad > 0).sum().item()
num_zero = (grad == 0).sum().item()
num_remove = math.ceil(num_nonzero*death_rate)
if num_remove > num_positive:
k = num_remove + num_zero
else:
k = num_remove
threshold, idx = torch.topk(grad.data.view(-1), k, sorted=True)
mask.data.view(-1)[idx[:k]] = 0.0
keep_masks.append(mask)
return keep_masks
| 34.506173 | 129 | 0.606082 | 3.359375 |
85822bca1dd9230a7e76b14d951c40276e5feaee
| 9,602 |
js
|
JavaScript
|
public/js/ajax.js
|
alexrodri99/ideas-ajax
|
76166c916b61e853be041347cee70286e99835f1
|
[
"MIT"
] | null | null | null |
public/js/ajax.js
|
alexrodri99/ideas-ajax
|
76166c916b61e853be041347cee70286e99835f1
|
[
"MIT"
] | null | null | null |
public/js/ajax.js
|
alexrodri99/ideas-ajax
|
76166c916b61e853be041347cee70286e99835f1
|
[
"MIT"
] | null | null | null |
window.onload = function() {
modal = document.getElementById("myModal");
read();
}
function objetoAjax() {
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
/* Muestra todos los registros de la base de datos (sin filtrar y filtrados) */
function read() {
var section = document.getElementById('section-3');
var buscador = document.getElementById('searchNote').value;
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
ajax.open('POST', 'read', true);
var datasend = new FormData();
datasend.append('filtro', buscador);
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
var tabla = '';
tabla += '<table class="table table-light">';
tabla += '<thead>';
tabla += '<tr class="thead-dark">';
/* tabla += '<th>Id</th>'; */
tabla += '<th>Título</th>';
tabla += '<th>Descripción</th>';
tabla += '<th>Actualizar</th>';
tabla += '<th>Borrar</th>';
tabla += '</tr>';
tabla += '</thead>';
tabla += '<tbody>';
for (let i = 0; i < respuesta.length; i++) {
//const element = array[i];
tabla += '<tr>';
/* tabla += '<td>' + respuesta[i].id + '</td>'; */
tabla += '<td>' + respuesta[i].title + '</td>';
tabla += '<td>' + respuesta[i].description + '</td>';
tabla += '<td><button class="btn btn-primary" onclick="openmodal(' + respuesta[i].id + ','' + respuesta[i].title + '','' + respuesta[i].description + '')">Actualizar</button></td>';
tabla += '<td><button class="btn btn-danger" onclick="eliminar(' + respuesta[i].id + ')" type="submit">Borrar</button></td>';
tabla += '</tr>';
}
tabla += '</tbody>';
tabla += '</table>';
section.innerHTML = tabla;
}
}
ajax.send(datasend);
}
/* Actualiza el campo favorito de un pokemon en la base de datos */
function create() {
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var title = document.getElementById('title').value;
var description = document.getElementById('description').value;
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'create', true);
var datasend = new FormData();
datasend.append('title', title)
datasend.append('description', description)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha añadido la nota correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
document.getElementById('forminsert').reset();
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
}
}
ajax.send(datasend);
}
function eliminar(id) {
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'delete', true);
var datasend = new FormData();
datasend.append('id', id)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha eliminado la nota correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
}
}
ajax.send(datasend);
}
function actualizar() {
//poner variables dentro de la funcion function actualizar(id,title,description)
var token = document.getElementById('token').getAttribute('content');
var ajax = new objetoAjax();
var id = document.getElementById('id').value;
var title = document.getElementById('titlee').value;
var description = document.getElementById('descriptionn').value;
console.log(id);
console.log(title);
console.log(description);
var mensaje = document.getElementById('mensaje');
ajax.open('POST', 'update', true);
var datasend = new FormData();
datasend.append('id', id)
datasend.append('title', title)
datasend.append('description', description)
datasend.append('_token', token)
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var respuesta = JSON.parse(ajax.responseText);
if (respuesta.resultado == 'OK') {
mensaje.innerHTML = 'Se ha actualizado correctamente';
setTimeout(function() {
mensaje.innerHTML = 'Aquí verás las últimas modificaciones...';
}, 2000);
read();
} else {
mensaje.innerHTML = 'Ha ocurrido un error. ' + respuesta.resultado;
}
closeModal();
}
}
ajax.send(datasend);
}
function openmodal(id, titulo, desc) {
form = document.getElementById("formm");
form.setAttribute("method", "post");
form.setAttribute("onsubmit", "actualizar(); return false;");
//form.setAttribute("onsubmit", "actualizar(" + id + "," + titulo + "," + desc + "); return false;");
form.setAttribute("class", "border p-3 form");
div = document.createElement('DIV');
div.setAttribute("class", "form-group")
label = document.createElement('LABEL');
label.innerHTML = "Título";
input = document.createElement('INPUT');
input.setAttribute("value", titulo)
input.setAttribute("type", "text")
input.setAttribute("name", "title")
input.setAttribute("id", "titlee")
input.setAttribute("class", "form-control")
input0 = document.createElement('INPUT');
input0.setAttribute("value", id)
input0.setAttribute("type", "hidden")
input0.setAttribute("name", "id")
input0.setAttribute("id", "id")
input0.setAttribute("class", "form-control")
div1 = document.createElement('DIV');
div1.setAttribute("class", "form-group")
label1 = document.createElement('LABEL');
label1.innerHTML = "Descripción";
input1 = document.createElement('INPUT');
input1.setAttribute("value", desc)
input1.setAttribute("type", "text")
input1.setAttribute("name", "description")
input1.setAttribute("id", "descriptionn")
input1.setAttribute("class", "form-control")
btn = document.createElement('input');
btn.setAttribute("type", "submit")
btn.setAttribute("class", "btn btn-primary")
btn.setAttribute("value", "Actualizar")
form.appendChild(div);
div.appendChild(label);
div.appendChild(input);
div.appendChild(input0);
form.appendChild(div1);
div1.appendChild(label1);
div1.appendChild(input1);
form.appendChild(btn);
//document.getElementById("content").innerHTML += '<form action="{{url(' + info + '.$nota->' + id + ')}}" method="post"><label>Título</label><br><input type="text" id="title" name="title" value="' + titulo + '"></br><label>Descripción</label><br><input type="text" id="description" name="description" value="' + desc + '"><br><input type="submit" class="btn-outline-primary" value="Crear"></form>';
//document.getElementById("content").innerHTML += '<label>Título </label>';
//document.getElementById("content").innerHTML += '<input type="text" id="title" name="title" value="' + titulo + '"></br>';
//document.getElementById("content").innerHTML += '<label>Descripción</label>';
//document.getElementById("content").innerHTML += '<input type="text" id="description" name="description" value="' + desc + '"><br>';
//document.getElementById("content").innerHTML += '<input type="submit" class="btn-outline-primary" value="Crear">';
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
document.getElementById("formm").removeChild(div)
document.getElementById("formm").removeChild(div1)
document.getElementById("formm").removeChild(btn)
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById("formm").removeChild(div)
document.getElementById("formm").removeChild(div1)
document.getElementById("formm").removeChild(btn)
}
}
/* comillas en envío de variables de entrada en funciones JS: ' */
/* EX:
1. filtro favoritos
2. liberar pokémons (quitar la imagen)
*/
| 38.103175 | 402 | 0.595189 | 3.0625 |
b1b636f69ad450e458aa8a0155c9f596efccc01c
| 888 |
c
|
C
|
A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c
|
MarcoBuster/ITIS
|
1c5f627f4f48898a5dd05746a71372a425cd6bc0
|
[
"MIT"
] | 5 |
2017-10-12T20:32:37.000Z
|
2018-01-22T16:42:29.000Z
|
A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c
|
MarcoBuster/ITIS
|
1c5f627f4f48898a5dd05746a71372a425cd6bc0
|
[
"MIT"
] | null | null | null |
A.S. 2017-2018/Compiti 24:03:2018/Analizzatore di nomi inseriti/main.c
|
MarcoBuster/ITIS
|
1c5f627f4f48898a5dd05746a71372a425cd6bc0
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
/*
* TODO:
* quanti nomi
* nome più lungo
* ordine alfabetico
*/
int main() {
char input[100][100];
int i;
int count, longest = 0, longest_index = 0;
for (i=0; i<100 && input[i - 1][0] != '*'; i++) {
printf("\nInserisci nome (dio porco): ");
gets(input[i]);
}
count = i - 2;
printf("\nNomi inseriti: %d", count);
for (i = 0; i < count; i++) {
if (strlen(input[i]) > longest) {
longest = (int) strlen(input[i]);
longest_index = i;
}
}
printf("\nNome più lungo inserito (dio cane): ");
puts(input[longest_index]);
printf("[debug]: alfabeto italiano (dio cane)");
for (i=65; i<90; i++) {
printf("%c", (char) i);
}
for (i=0; i<count; i++) {
printf("%d. ", i);
puts(input[i]);
}
return 0;
}
| 20.651163 | 53 | 0.48536 | 3.296875 |
dda18707b174bf35d646f30590c4df82fc378209
| 26,202 |
go
|
Go
|
cf/terminal/terminalfakes/fake_ui.go
|
heyjcollins/cli
|
a9dc02860cef013b7c373613416f25800926ce3b
|
[
"Apache-2.0"
] | 1,624 |
2015-01-03T00:52:09.000Z
|
2022-03-29T18:39:10.000Z
|
cf/terminal/terminalfakes/fake_ui.go
|
heyjcollins/cli
|
a9dc02860cef013b7c373613416f25800926ce3b
|
[
"Apache-2.0"
] | 1,946 |
2015-01-04T03:22:41.000Z
|
2022-03-29T17:26:43.000Z
|
cf/terminal/terminalfakes/fake_ui.go
|
heyjcollins/cli
|
a9dc02860cef013b7c373613416f25800926ce3b
|
[
"Apache-2.0"
] | 869 |
2015-01-05T12:58:38.000Z
|
2022-03-12T07:50:53.000Z
|
// Code generated by counterfeiter. DO NOT EDIT.
package terminalfakes
import (
"io"
"sync"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/terminal"
)
type FakeUI struct {
AskStub func(string) string
askMutex sync.RWMutex
askArgsForCall []struct {
arg1 string
}
askReturns struct {
result1 string
}
askReturnsOnCall map[int]struct {
result1 string
}
AskForPasswordStub func(string) string
askForPasswordMutex sync.RWMutex
askForPasswordArgsForCall []struct {
arg1 string
}
askForPasswordReturns struct {
result1 string
}
askForPasswordReturnsOnCall map[int]struct {
result1 string
}
ConfirmStub func(string) bool
confirmMutex sync.RWMutex
confirmArgsForCall []struct {
arg1 string
}
confirmReturns struct {
result1 bool
}
confirmReturnsOnCall map[int]struct {
result1 bool
}
ConfirmDeleteStub func(string, string) bool
confirmDeleteMutex sync.RWMutex
confirmDeleteArgsForCall []struct {
arg1 string
arg2 string
}
confirmDeleteReturns struct {
result1 bool
}
confirmDeleteReturnsOnCall map[int]struct {
result1 bool
}
ConfirmDeleteWithAssociationsStub func(string, string) bool
confirmDeleteWithAssociationsMutex sync.RWMutex
confirmDeleteWithAssociationsArgsForCall []struct {
arg1 string
arg2 string
}
confirmDeleteWithAssociationsReturns struct {
result1 bool
}
confirmDeleteWithAssociationsReturnsOnCall map[int]struct {
result1 bool
}
FailedStub func(string, ...interface{})
failedMutex sync.RWMutex
failedArgsForCall []struct {
arg1 string
arg2 []interface{}
}
LoadingIndicationStub func()
loadingIndicationMutex sync.RWMutex
loadingIndicationArgsForCall []struct {
}
NotifyUpdateIfNeededStub func(coreconfig.Reader)
notifyUpdateIfNeededMutex sync.RWMutex
notifyUpdateIfNeededArgsForCall []struct {
arg1 coreconfig.Reader
}
OkStub func()
okMutex sync.RWMutex
okArgsForCall []struct {
}
PrintCapturingNoOutputStub func(string, ...interface{})
printCapturingNoOutputMutex sync.RWMutex
printCapturingNoOutputArgsForCall []struct {
arg1 string
arg2 []interface{}
}
PrintPaginatorStub func([]string, error)
printPaginatorMutex sync.RWMutex
printPaginatorArgsForCall []struct {
arg1 []string
arg2 error
}
SayStub func(string, ...interface{})
sayMutex sync.RWMutex
sayArgsForCall []struct {
arg1 string
arg2 []interface{}
}
ShowConfigurationStub func(coreconfig.Reader) error
showConfigurationMutex sync.RWMutex
showConfigurationArgsForCall []struct {
arg1 coreconfig.Reader
}
showConfigurationReturns struct {
result1 error
}
showConfigurationReturnsOnCall map[int]struct {
result1 error
}
TableStub func([]string) *terminal.UITable
tableMutex sync.RWMutex
tableArgsForCall []struct {
arg1 []string
}
tableReturns struct {
result1 *terminal.UITable
}
tableReturnsOnCall map[int]struct {
result1 *terminal.UITable
}
WarnStub func(string, ...interface{})
warnMutex sync.RWMutex
warnArgsForCall []struct {
arg1 string
arg2 []interface{}
}
WriterStub func() io.Writer
writerMutex sync.RWMutex
writerArgsForCall []struct {
}
writerReturns struct {
result1 io.Writer
}
writerReturnsOnCall map[int]struct {
result1 io.Writer
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeUI) Ask(arg1 string) string {
fake.askMutex.Lock()
ret, specificReturn := fake.askReturnsOnCall[len(fake.askArgsForCall)]
fake.askArgsForCall = append(fake.askArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("Ask", []interface{}{arg1})
fake.askMutex.Unlock()
if fake.AskStub != nil {
return fake.AskStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.askReturns
return fakeReturns.result1
}
func (fake *FakeUI) AskCallCount() int {
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
return len(fake.askArgsForCall)
}
func (fake *FakeUI) AskCalls(stub func(string) string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = stub
}
func (fake *FakeUI) AskArgsForCall(i int) string {
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
argsForCall := fake.askArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) AskReturns(result1 string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = nil
fake.askReturns = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskReturnsOnCall(i int, result1 string) {
fake.askMutex.Lock()
defer fake.askMutex.Unlock()
fake.AskStub = nil
if fake.askReturnsOnCall == nil {
fake.askReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.askReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskForPassword(arg1 string) string {
fake.askForPasswordMutex.Lock()
ret, specificReturn := fake.askForPasswordReturnsOnCall[len(fake.askForPasswordArgsForCall)]
fake.askForPasswordArgsForCall = append(fake.askForPasswordArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("AskForPassword", []interface{}{arg1})
fake.askForPasswordMutex.Unlock()
if fake.AskForPasswordStub != nil {
return fake.AskForPasswordStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.askForPasswordReturns
return fakeReturns.result1
}
func (fake *FakeUI) AskForPasswordCallCount() int {
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
return len(fake.askForPasswordArgsForCall)
}
func (fake *FakeUI) AskForPasswordCalls(stub func(string) string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = stub
}
func (fake *FakeUI) AskForPasswordArgsForCall(i int) string {
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
argsForCall := fake.askForPasswordArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) AskForPasswordReturns(result1 string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = nil
fake.askForPasswordReturns = struct {
result1 string
}{result1}
}
func (fake *FakeUI) AskForPasswordReturnsOnCall(i int, result1 string) {
fake.askForPasswordMutex.Lock()
defer fake.askForPasswordMutex.Unlock()
fake.AskForPasswordStub = nil
if fake.askForPasswordReturnsOnCall == nil {
fake.askForPasswordReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.askForPasswordReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeUI) Confirm(arg1 string) bool {
fake.confirmMutex.Lock()
ret, specificReturn := fake.confirmReturnsOnCall[len(fake.confirmArgsForCall)]
fake.confirmArgsForCall = append(fake.confirmArgsForCall, struct {
arg1 string
}{arg1})
fake.recordInvocation("Confirm", []interface{}{arg1})
fake.confirmMutex.Unlock()
if fake.ConfirmStub != nil {
return fake.ConfirmStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmCallCount() int {
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
return len(fake.confirmArgsForCall)
}
func (fake *FakeUI) ConfirmCalls(stub func(string) bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = stub
}
func (fake *FakeUI) ConfirmArgsForCall(i int) string {
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
argsForCall := fake.confirmArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) ConfirmReturns(result1 bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = nil
fake.confirmReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmReturnsOnCall(i int, result1 bool) {
fake.confirmMutex.Lock()
defer fake.confirmMutex.Unlock()
fake.ConfirmStub = nil
if fake.confirmReturnsOnCall == nil {
fake.confirmReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDelete(arg1 string, arg2 string) bool {
fake.confirmDeleteMutex.Lock()
ret, specificReturn := fake.confirmDeleteReturnsOnCall[len(fake.confirmDeleteArgsForCall)]
fake.confirmDeleteArgsForCall = append(fake.confirmDeleteArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
fake.recordInvocation("ConfirmDelete", []interface{}{arg1, arg2})
fake.confirmDeleteMutex.Unlock()
if fake.ConfirmDeleteStub != nil {
return fake.ConfirmDeleteStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmDeleteReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmDeleteCallCount() int {
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
return len(fake.confirmDeleteArgsForCall)
}
func (fake *FakeUI) ConfirmDeleteCalls(stub func(string, string) bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = stub
}
func (fake *FakeUI) ConfirmDeleteArgsForCall(i int) (string, string) {
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
argsForCall := fake.confirmDeleteArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ConfirmDeleteReturns(result1 bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = nil
fake.confirmDeleteReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteReturnsOnCall(i int, result1 bool) {
fake.confirmDeleteMutex.Lock()
defer fake.confirmDeleteMutex.Unlock()
fake.ConfirmDeleteStub = nil
if fake.confirmDeleteReturnsOnCall == nil {
fake.confirmDeleteReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmDeleteReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteWithAssociations(arg1 string, arg2 string) bool {
fake.confirmDeleteWithAssociationsMutex.Lock()
ret, specificReturn := fake.confirmDeleteWithAssociationsReturnsOnCall[len(fake.confirmDeleteWithAssociationsArgsForCall)]
fake.confirmDeleteWithAssociationsArgsForCall = append(fake.confirmDeleteWithAssociationsArgsForCall, struct {
arg1 string
arg2 string
}{arg1, arg2})
fake.recordInvocation("ConfirmDeleteWithAssociations", []interface{}{arg1, arg2})
fake.confirmDeleteWithAssociationsMutex.Unlock()
if fake.ConfirmDeleteWithAssociationsStub != nil {
return fake.ConfirmDeleteWithAssociationsStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.confirmDeleteWithAssociationsReturns
return fakeReturns.result1
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsCallCount() int {
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
return len(fake.confirmDeleteWithAssociationsArgsForCall)
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsCalls(stub func(string, string) bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = stub
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsArgsForCall(i int) (string, string) {
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
argsForCall := fake.confirmDeleteWithAssociationsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsReturns(result1 bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = nil
fake.confirmDeleteWithAssociationsReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) ConfirmDeleteWithAssociationsReturnsOnCall(i int, result1 bool) {
fake.confirmDeleteWithAssociationsMutex.Lock()
defer fake.confirmDeleteWithAssociationsMutex.Unlock()
fake.ConfirmDeleteWithAssociationsStub = nil
if fake.confirmDeleteWithAssociationsReturnsOnCall == nil {
fake.confirmDeleteWithAssociationsReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.confirmDeleteWithAssociationsReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeUI) Failed(arg1 string, arg2 ...interface{}) {
fake.failedMutex.Lock()
fake.failedArgsForCall = append(fake.failedArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Failed", []interface{}{arg1, arg2})
fake.failedMutex.Unlock()
if fake.FailedStub != nil {
fake.FailedStub(arg1, arg2...)
}
}
func (fake *FakeUI) FailedCallCount() int {
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
return len(fake.failedArgsForCall)
}
func (fake *FakeUI) FailedCalls(stub func(string, ...interface{})) {
fake.failedMutex.Lock()
defer fake.failedMutex.Unlock()
fake.FailedStub = stub
}
func (fake *FakeUI) FailedArgsForCall(i int) (string, []interface{}) {
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
argsForCall := fake.failedArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) LoadingIndication() {
fake.loadingIndicationMutex.Lock()
fake.loadingIndicationArgsForCall = append(fake.loadingIndicationArgsForCall, struct {
}{})
fake.recordInvocation("LoadingIndication", []interface{}{})
fake.loadingIndicationMutex.Unlock()
if fake.LoadingIndicationStub != nil {
fake.LoadingIndicationStub()
}
}
func (fake *FakeUI) LoadingIndicationCallCount() int {
fake.loadingIndicationMutex.RLock()
defer fake.loadingIndicationMutex.RUnlock()
return len(fake.loadingIndicationArgsForCall)
}
func (fake *FakeUI) LoadingIndicationCalls(stub func()) {
fake.loadingIndicationMutex.Lock()
defer fake.loadingIndicationMutex.Unlock()
fake.LoadingIndicationStub = stub
}
func (fake *FakeUI) NotifyUpdateIfNeeded(arg1 coreconfig.Reader) {
fake.notifyUpdateIfNeededMutex.Lock()
fake.notifyUpdateIfNeededArgsForCall = append(fake.notifyUpdateIfNeededArgsForCall, struct {
arg1 coreconfig.Reader
}{arg1})
fake.recordInvocation("NotifyUpdateIfNeeded", []interface{}{arg1})
fake.notifyUpdateIfNeededMutex.Unlock()
if fake.NotifyUpdateIfNeededStub != nil {
fake.NotifyUpdateIfNeededStub(arg1)
}
}
func (fake *FakeUI) NotifyUpdateIfNeededCallCount() int {
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
return len(fake.notifyUpdateIfNeededArgsForCall)
}
func (fake *FakeUI) NotifyUpdateIfNeededCalls(stub func(coreconfig.Reader)) {
fake.notifyUpdateIfNeededMutex.Lock()
defer fake.notifyUpdateIfNeededMutex.Unlock()
fake.NotifyUpdateIfNeededStub = stub
}
func (fake *FakeUI) NotifyUpdateIfNeededArgsForCall(i int) coreconfig.Reader {
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
argsForCall := fake.notifyUpdateIfNeededArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) Ok() {
fake.okMutex.Lock()
fake.okArgsForCall = append(fake.okArgsForCall, struct {
}{})
fake.recordInvocation("Ok", []interface{}{})
fake.okMutex.Unlock()
if fake.OkStub != nil {
fake.OkStub()
}
}
func (fake *FakeUI) OkCallCount() int {
fake.okMutex.RLock()
defer fake.okMutex.RUnlock()
return len(fake.okArgsForCall)
}
func (fake *FakeUI) OkCalls(stub func()) {
fake.okMutex.Lock()
defer fake.okMutex.Unlock()
fake.OkStub = stub
}
func (fake *FakeUI) PrintCapturingNoOutput(arg1 string, arg2 ...interface{}) {
fake.printCapturingNoOutputMutex.Lock()
fake.printCapturingNoOutputArgsForCall = append(fake.printCapturingNoOutputArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("PrintCapturingNoOutput", []interface{}{arg1, arg2})
fake.printCapturingNoOutputMutex.Unlock()
if fake.PrintCapturingNoOutputStub != nil {
fake.PrintCapturingNoOutputStub(arg1, arg2...)
}
}
func (fake *FakeUI) PrintCapturingNoOutputCallCount() int {
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
return len(fake.printCapturingNoOutputArgsForCall)
}
func (fake *FakeUI) PrintCapturingNoOutputCalls(stub func(string, ...interface{})) {
fake.printCapturingNoOutputMutex.Lock()
defer fake.printCapturingNoOutputMutex.Unlock()
fake.PrintCapturingNoOutputStub = stub
}
func (fake *FakeUI) PrintCapturingNoOutputArgsForCall(i int) (string, []interface{}) {
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
argsForCall := fake.printCapturingNoOutputArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) PrintPaginator(arg1 []string, arg2 error) {
var arg1Copy []string
if arg1 != nil {
arg1Copy = make([]string, len(arg1))
copy(arg1Copy, arg1)
}
fake.printPaginatorMutex.Lock()
fake.printPaginatorArgsForCall = append(fake.printPaginatorArgsForCall, struct {
arg1 []string
arg2 error
}{arg1Copy, arg2})
fake.recordInvocation("PrintPaginator", []interface{}{arg1Copy, arg2})
fake.printPaginatorMutex.Unlock()
if fake.PrintPaginatorStub != nil {
fake.PrintPaginatorStub(arg1, arg2)
}
}
func (fake *FakeUI) PrintPaginatorCallCount() int {
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
return len(fake.printPaginatorArgsForCall)
}
func (fake *FakeUI) PrintPaginatorCalls(stub func([]string, error)) {
fake.printPaginatorMutex.Lock()
defer fake.printPaginatorMutex.Unlock()
fake.PrintPaginatorStub = stub
}
func (fake *FakeUI) PrintPaginatorArgsForCall(i int) ([]string, error) {
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
argsForCall := fake.printPaginatorArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) Say(arg1 string, arg2 ...interface{}) {
fake.sayMutex.Lock()
fake.sayArgsForCall = append(fake.sayArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Say", []interface{}{arg1, arg2})
fake.sayMutex.Unlock()
if fake.SayStub != nil {
fake.SayStub(arg1, arg2...)
}
}
func (fake *FakeUI) SayCallCount() int {
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
return len(fake.sayArgsForCall)
}
func (fake *FakeUI) SayCalls(stub func(string, ...interface{})) {
fake.sayMutex.Lock()
defer fake.sayMutex.Unlock()
fake.SayStub = stub
}
func (fake *FakeUI) SayArgsForCall(i int) (string, []interface{}) {
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
argsForCall := fake.sayArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) ShowConfiguration(arg1 coreconfig.Reader) error {
fake.showConfigurationMutex.Lock()
ret, specificReturn := fake.showConfigurationReturnsOnCall[len(fake.showConfigurationArgsForCall)]
fake.showConfigurationArgsForCall = append(fake.showConfigurationArgsForCall, struct {
arg1 coreconfig.Reader
}{arg1})
fake.recordInvocation("ShowConfiguration", []interface{}{arg1})
fake.showConfigurationMutex.Unlock()
if fake.ShowConfigurationStub != nil {
return fake.ShowConfigurationStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.showConfigurationReturns
return fakeReturns.result1
}
func (fake *FakeUI) ShowConfigurationCallCount() int {
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
return len(fake.showConfigurationArgsForCall)
}
func (fake *FakeUI) ShowConfigurationCalls(stub func(coreconfig.Reader) error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = stub
}
func (fake *FakeUI) ShowConfigurationArgsForCall(i int) coreconfig.Reader {
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
argsForCall := fake.showConfigurationArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) ShowConfigurationReturns(result1 error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = nil
fake.showConfigurationReturns = struct {
result1 error
}{result1}
}
func (fake *FakeUI) ShowConfigurationReturnsOnCall(i int, result1 error) {
fake.showConfigurationMutex.Lock()
defer fake.showConfigurationMutex.Unlock()
fake.ShowConfigurationStub = nil
if fake.showConfigurationReturnsOnCall == nil {
fake.showConfigurationReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.showConfigurationReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeUI) Table(arg1 []string) *terminal.UITable {
var arg1Copy []string
if arg1 != nil {
arg1Copy = make([]string, len(arg1))
copy(arg1Copy, arg1)
}
fake.tableMutex.Lock()
ret, specificReturn := fake.tableReturnsOnCall[len(fake.tableArgsForCall)]
fake.tableArgsForCall = append(fake.tableArgsForCall, struct {
arg1 []string
}{arg1Copy})
fake.recordInvocation("Table", []interface{}{arg1Copy})
fake.tableMutex.Unlock()
if fake.TableStub != nil {
return fake.TableStub(arg1)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.tableReturns
return fakeReturns.result1
}
func (fake *FakeUI) TableCallCount() int {
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
return len(fake.tableArgsForCall)
}
func (fake *FakeUI) TableCalls(stub func([]string) *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = stub
}
func (fake *FakeUI) TableArgsForCall(i int) []string {
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
argsForCall := fake.tableArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeUI) TableReturns(result1 *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = nil
fake.tableReturns = struct {
result1 *terminal.UITable
}{result1}
}
func (fake *FakeUI) TableReturnsOnCall(i int, result1 *terminal.UITable) {
fake.tableMutex.Lock()
defer fake.tableMutex.Unlock()
fake.TableStub = nil
if fake.tableReturnsOnCall == nil {
fake.tableReturnsOnCall = make(map[int]struct {
result1 *terminal.UITable
})
}
fake.tableReturnsOnCall[i] = struct {
result1 *terminal.UITable
}{result1}
}
func (fake *FakeUI) Warn(arg1 string, arg2 ...interface{}) {
fake.warnMutex.Lock()
fake.warnArgsForCall = append(fake.warnArgsForCall, struct {
arg1 string
arg2 []interface{}
}{arg1, arg2})
fake.recordInvocation("Warn", []interface{}{arg1, arg2})
fake.warnMutex.Unlock()
if fake.WarnStub != nil {
fake.WarnStub(arg1, arg2...)
}
}
func (fake *FakeUI) WarnCallCount() int {
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
return len(fake.warnArgsForCall)
}
func (fake *FakeUI) WarnCalls(stub func(string, ...interface{})) {
fake.warnMutex.Lock()
defer fake.warnMutex.Unlock()
fake.WarnStub = stub
}
func (fake *FakeUI) WarnArgsForCall(i int) (string, []interface{}) {
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
argsForCall := fake.warnArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeUI) Writer() io.Writer {
fake.writerMutex.Lock()
ret, specificReturn := fake.writerReturnsOnCall[len(fake.writerArgsForCall)]
fake.writerArgsForCall = append(fake.writerArgsForCall, struct {
}{})
fake.recordInvocation("Writer", []interface{}{})
fake.writerMutex.Unlock()
if fake.WriterStub != nil {
return fake.WriterStub()
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.writerReturns
return fakeReturns.result1
}
func (fake *FakeUI) WriterCallCount() int {
fake.writerMutex.RLock()
defer fake.writerMutex.RUnlock()
return len(fake.writerArgsForCall)
}
func (fake *FakeUI) WriterCalls(stub func() io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = stub
}
func (fake *FakeUI) WriterReturns(result1 io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = nil
fake.writerReturns = struct {
result1 io.Writer
}{result1}
}
func (fake *FakeUI) WriterReturnsOnCall(i int, result1 io.Writer) {
fake.writerMutex.Lock()
defer fake.writerMutex.Unlock()
fake.WriterStub = nil
if fake.writerReturnsOnCall == nil {
fake.writerReturnsOnCall = make(map[int]struct {
result1 io.Writer
})
}
fake.writerReturnsOnCall[i] = struct {
result1 io.Writer
}{result1}
}
func (fake *FakeUI) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.askMutex.RLock()
defer fake.askMutex.RUnlock()
fake.askForPasswordMutex.RLock()
defer fake.askForPasswordMutex.RUnlock()
fake.confirmMutex.RLock()
defer fake.confirmMutex.RUnlock()
fake.confirmDeleteMutex.RLock()
defer fake.confirmDeleteMutex.RUnlock()
fake.confirmDeleteWithAssociationsMutex.RLock()
defer fake.confirmDeleteWithAssociationsMutex.RUnlock()
fake.failedMutex.RLock()
defer fake.failedMutex.RUnlock()
fake.loadingIndicationMutex.RLock()
defer fake.loadingIndicationMutex.RUnlock()
fake.notifyUpdateIfNeededMutex.RLock()
defer fake.notifyUpdateIfNeededMutex.RUnlock()
fake.okMutex.RLock()
defer fake.okMutex.RUnlock()
fake.printCapturingNoOutputMutex.RLock()
defer fake.printCapturingNoOutputMutex.RUnlock()
fake.printPaginatorMutex.RLock()
defer fake.printPaginatorMutex.RUnlock()
fake.sayMutex.RLock()
defer fake.sayMutex.RUnlock()
fake.showConfigurationMutex.RLock()
defer fake.showConfigurationMutex.RUnlock()
fake.tableMutex.RLock()
defer fake.tableMutex.RUnlock()
fake.warnMutex.RLock()
defer fake.warnMutex.RUnlock()
fake.writerMutex.RLock()
defer fake.writerMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeUI) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ terminal.UI = new(FakeUI)
| 28.326486 | 123 | 0.764598 | 3 |
f016663abaaca777953a37d629e3e996752fe3d9
| 1,438 |
js
|
JavaScript
|
test/modules/util.js
|
stalniy/cytoscape.js
|
67d18c735a8c6b9a45974cf7cfff53ce4c6dcba2
|
[
"MIT"
] | 2 |
2019-06-12T09:46:40.000Z
|
2020-01-19T00:51:23.000Z
|
test/modules/util.js
|
stalniy/cytoscape.js
|
67d18c735a8c6b9a45974cf7cfff53ce4c6dcba2
|
[
"MIT"
] | null | null | null |
test/modules/util.js
|
stalniy/cytoscape.js
|
67d18c735a8c6b9a45974cf7cfff53ce4c6dcba2
|
[
"MIT"
] | null | null | null |
import { expect } from 'chai';
import { hashString, hashInt, hashIntsArray } from '../../src/util';
describe('util', function(){
describe('hash', function(){
it('gives same result with seed for one-char strings', function(){
var h1 = hashString('a');
var h2 = hashString('b', h1);
var h3 = hashString('ab');
expect(h2).to.equal(h3);
});
it('gives same result with seed for multi-char strings', function(){
var h1 = hashString('foo');
var h2 = hashString('bar', h1);
var h3 = hashString('foobar');
expect(h2).to.equal(h3);
});
it('gives different results for strings of opposite order', function(){
var h1 = hashString('foobar');
var h2 = hashString('raboof');
expect(h1).to.not.equal(h2);
});
// usecase : separate hashes can be joined
it('gives same result by hashing individual ints', function(){
var a = 846302;
var b = 466025;
var h1 = hashInt(a);
var h2 = hashInt(b, h1);
var h3 = hashIntsArray([a, b]);
expect(h2).to.equal(h3);
});
// main usecase is hashing ascii strings for style properties
it('hash is unique per ascii char', function(){
var min = 0;
var max = 127;
var hashes = {};
for( var i = min; i <= max; i++ ){
var h = hashInt(i);
expect( hashes[h] ).to.not.exist;
hashes[h] = true;
}
});
});
});
| 23.966667 | 75 | 0.560501 | 3.1875 |
39c4395ab44f73de22a611ba3438d01d3351c39a
| 1,153 |
js
|
JavaScript
|
node_modules/@wordpress/rich-text/build/is-active-list-type.js
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
node_modules/@wordpress/rich-text/build/is-active-list-type.js
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
node_modules/@wordpress/rich-text/build/is-active-list-type.js
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isActiveListType = isActiveListType;
var _getLineIndex = require("./get-line-index");
/**
* Internal dependencies
*/
/** @typedef {import('./create').RichTextValue} RichTextValue */
/**
* Whether or not the selected list has the given tag name.
*
* @param {RichTextValue} value The value to check.
* @param {string} type The tag name the list should have.
* @param {string} rootType The current root tag name, to compare with in
* case nothing is selected.
*
* @return {boolean} True if the current list type matches `type`, false if not.
*/
function isActiveListType(value, type, rootType) {
var replacements = value.replacements,
start = value.start;
var lineIndex = (0, _getLineIndex.getLineIndex)(value, start);
var replacement = replacements[lineIndex];
if (!replacement || replacement.length === 0) {
return type === rootType;
}
var lastFormat = replacement[replacement.length - 1];
return lastFormat.type === type;
}
//# sourceMappingURL=is-active-list-type.js.map
| 29.564103 | 80 | 0.673027 | 3.078125 |
f04fe6a0ae66518e152066d2f7472e765f8bd343
| 2,173 |
py
|
Python
|
tests/test_cli.py
|
KoichiYasuoka/pynlpir
|
8d5e994796a2b5d513f7db8d76d7d24a85d531b1
|
[
"MIT"
] | 537 |
2015-01-12T09:59:57.000Z
|
2022-03-29T09:22:30.000Z
|
tests/test_cli.py
|
KoichiYasuoka/pynlpir
|
8d5e994796a2b5d513f7db8d76d7d24a85d531b1
|
[
"MIT"
] | 110 |
2015-01-02T13:17:56.000Z
|
2022-03-24T07:43:02.000Z
|
tests/test_cli.py
|
KoichiYasuoka/pynlpir
|
8d5e994796a2b5d513f7db8d76d7d24a85d531b1
|
[
"MIT"
] | 150 |
2015-01-21T01:58:56.000Z
|
2022-02-23T16:16:40.000Z
|
"""Unit tests for pynlpir's cli.py file."""
import os
import shutil
import stat
import unittest
try:
from urllib.error import URLError
from urllib.request import urlopen
except ImportError:
from urllib2 import URLError, urlopen
from click.testing import CliRunner
from pynlpir import cli
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
LICENSE_FILE = os.path.join(TEST_DIR, 'data', 'NLPIR.user')
def can_reach_github():
"""Check if we can reach GitHub's website."""
try:
urlopen('http://github.com')
return True
except URLError:
return False
@unittest.skipIf(can_reach_github() is False, 'Unable to reach GitHub')
class TestCLI(unittest.TestCase):
"""Unit tests for the PyNLPIR CLI."""
def setUp(self):
self.runner = CliRunner()
def tearDown(self):
self.runner = None
def test_initial_license_download(self):
"""Tests that an initial license download works correctly."""
with self.runner.isolated_filesystem():
result = self.runner.invoke(cli.cli, ('update', '-d.'))
self.assertEqual(0, result.exit_code)
self.assertEqual('License updated.\n', result.output)
def test_license_update(self):
"Test that a regular license update works correctly."""
with self.runner.isolated_filesystem():
shutil.copyfile(LICENSE_FILE, os.path.basename(LICENSE_FILE))
result = self.runner.invoke(cli.cli, ('update', '-d.'))
self.assertEqual(0, result.exit_code)
self.assertEqual('License updated.\n', result.output)
result = self.runner.invoke(cli.cli, ('update', '-d.'))
self.assertEqual(0, result.exit_code)
self.assertEqual('Your license is already up-to-date.\n',
result.output)
def test_license_write_fail(self):
"""Test tha writing a license file fails appropriately."""
with self.runner.isolated_filesystem():
cwd = os.getcwd()
os.chmod(cwd, stat.S_IREAD)
with self.assertRaises((IOError, OSError)):
cli.update_license_file(cwd)
| 32.432836 | 73 | 0.645651 | 3.4375 |
dde7f0d0530e5d429916010771b60a3bd4d90edb
| 1,145 |
c
|
C
|
Programming-Lab/Assignment-05/two_matrix_multiplication.c
|
soham0-0/Coursework-DSA-and-Programming-Labs
|
e2245e40d9c752903716450de27f289b4eb882eb
|
[
"MIT"
] | null | null | null |
Programming-Lab/Assignment-05/two_matrix_multiplication.c
|
soham0-0/Coursework-DSA-and-Programming-Labs
|
e2245e40d9c752903716450de27f289b4eb882eb
|
[
"MIT"
] | null | null | null |
Programming-Lab/Assignment-05/two_matrix_multiplication.c
|
soham0-0/Coursework-DSA-and-Programming-Labs
|
e2245e40d9c752903716450de27f289b4eb882eb
|
[
"MIT"
] | null | null | null |
/*
Q.a) Write a program to multiply two given matrices.
*/
#include<stdio.h>
int main(){
int m1, n1, m2, n2;
printf("Enter m and n for mxn matrix A :");
scanf("%d %d", &m1, &n1);
int A[m1][n1];
printf("Enter Matric A: \n");
for(int i=0; i<m1; i++){
for(int j=0; j<n1; j++) scanf("%d", &A[i][j]);
}
printf("Enter m and n for mxn matrix B :");
scanf("%d %d", &m2, &n2);
int B[m2][n2];
printf("Enter Matric B: \n");
for(int i=0; i<m2; i++){
for(int j=0; j<n2; j++) scanf("%d", &B[i][j]);
}
if(n1==m2){
int ans[m1][n2];
for(int i=0; i<m1; i++){
for(int j=0; j<n2; j++) {
ans[i][j]=0;
for(int k=0; k<n1; k++){
ans[i][j]+=A[i][k]*B[k][j];
}
}
}
printf("The Resultant matrix A*B is: \n");
for(int i=0; i<m1; i++){
for(int j=0; j<n2; j++) {
printf("%d ", ans[i][j]);
}
printf("\n");
}
}else{
printf("Matrices are not multipliable. Aborting!!\n");
}
return 0;
}
| 26.022727 | 62 | 0.406114 | 3.203125 |
bde79e6579e4fc85f554baae177e4375ad9418fe
| 3,627 |
lua
|
Lua
|
tmplt/components/pageXXX/page_screenshot.lua
|
nyamamoto-neos/Tiled_Sample
|
45fd6b613b04fa56342cd2c20a9b2580443efaa5
|
[
"MIT"
] | null | null | null |
tmplt/components/pageXXX/page_screenshot.lua
|
nyamamoto-neos/Tiled_Sample
|
45fd6b613b04fa56342cd2c20a9b2580443efaa5
|
[
"MIT"
] | null | null | null |
tmplt/components/pageXXX/page_screenshot.lua
|
nyamamoto-neos/Tiled_Sample
|
45fd6b613b04fa56342cd2c20a9b2580443efaa5
|
[
"MIT"
] | 1 |
2021-07-08T01:31:53.000Z
|
2021-07-08T01:31:53.000Z
|
-- Code created by Kwik - Copyright: kwiksher.com {{year}}
-- Version: {{vers}}
-- Project: {{ProjName}}
--
local json = require('json')
local _M = {}
local _K = require("Application")
_K.screenshot = _M
local needle = "Storage"
-- Helper function that determines if a value is inside of a given table.
local function isValueInTable( haystack, needle )
assert( type(haystack) == "table", "isValueInTable() : First parameter must be a table." )
assert( needle ~= nil, "isValueInTable() : Second parameter must be not be nil." )
for key, value in pairs( haystack ) do
if ( value == needle ) then
return true
end
end
return false
end
-- Called when the user has granted or denied the requested permissions.
local function permissionsListener( event, deferred )
-- Print out granted/denied permissions.
print( "permissionsListener( " .. json.prettify( event or {} ) .. " )" )
-- Check again for camera (and storage) access.
local grantedPermissions = system.getInfo("grantedAppPermissions")
if ( grantedPermissions ) then
if ( not isValueInTable( grantedPermissions, needle ) ) then
print( "Lacking storage permission!" )
deferred:reject()
else
deferred:resolve()
end
end
end
function checkPermissions()
local deferred = Deferred()
if ( system.getInfo( "platform" ) == "android" and system.getInfo( "androidApiLevel" ) >= 23 ) then
local grantedPermissions = system.getInfo("grantedAppPermissions")
if ( grantedPermissions ) then
if ( not isValueInTable( grantedPermissions, needle ) ) then
print( "Lacking storage permission!" )
native.showPopup( "requestAppPermission", { appPermission={needle}, listener = function(event) permissionListener(event, deferred) end} )
else
deferred:resolve()
end
end
else
if media.hasSource( media.PhotoLibrary ) then
deferred:resolve()
else
deferred:reject()
end
end
return deferred:promise()
end
---------------------
function _M:localPos(UI)
if _K.allAudios.cam_shutter == nil then
_K.allAudios.cam_shutter = audio.loadSound(_K.audioDir.."shutter.mp3", _K.systemDir )
end
end
--
function _M:didShow(UI)
_M.layer = UI.layer
end
--
function _M:takeScreenShot(ptit, pmsg, shutter, buttonArr)
checkPermissions()
:done(function()
if shutter then
audio.play(_K.allAudios.cam_shutter, {channel=31})
end
if buttonArr then
for i=1, #buttonArr do
local myLayer = _M.layer[buttonArr[i]]
myLayer.alphaBeforeScreenshot = myLayer.alpha
myLayer.alpha = 0
end
end
--
local screenCap = display.captureScreen( true )
local alert = native.showAlert(ptit, pmsg, { "OK" } )
screenCap:removeSelf()
if buttonArr then
for i=1, #buttonArr do
local myLayer = _M.layer[buttonArr[i]]
myLayer.alpha = myLayer.alphaBeforeScreenshot
end
end
end)
:fail(function()
print("fail")
native.showAlert( "Corona", "Request permission is not granted on "..system.getInfo("model"), { "OK" } )
end)
end
--
function _M:toDispose(UI)
if _K.allAudios.cam_shutter then
audio.stop(31)
end
end
--
function _M:toDestroy(UI)
audio.dispose(_K.allAudios.cam_shutter)
_K.allAudios.cam_shutter = nil
end
--
function _M:willHide(UI)
end
--
function _M:localVars(UI)
end
--
return _M
| 30.225 | 153 | 0.628343 | 3.296875 |
b2bf04c3b73ed2e5d7a5d3616651ad7a3f22eac7
| 1,170 |
py
|
Python
|
buffers/introspective_buffer.py
|
GittiHab/mbrl-thesis-code
|
10ecd6ef7cbb2df4bd03ce9928e344eab4238a2e
|
[
"MIT"
] | null | null | null |
buffers/introspective_buffer.py
|
GittiHab/mbrl-thesis-code
|
10ecd6ef7cbb2df4bd03ce9928e344eab4238a2e
|
[
"MIT"
] | null | null | null |
buffers/introspective_buffer.py
|
GittiHab/mbrl-thesis-code
|
10ecd6ef7cbb2df4bd03ce9928e344eab4238a2e
|
[
"MIT"
] | null | null | null |
import numpy as np
from typing import Union, Optional, List, Dict, Any
from buffers.chunk_buffer import ChunkReplayBuffer
class IntrospectiveChunkReplayBuffer(ChunkReplayBuffer):
def __init__(self, buffer_size: int, *args, **kwargs):
super().__init__(buffer_size, *args, **kwargs)
self.sample_counts = np.zeros((buffer_size,), dtype=np.int)
self.first_access = np.zeros((buffer_size,), dtype=np.int) - 1
def _log_indices(self, indices):
self.sample_counts[indices] += 1
mask = np.zeros_like(self.first_access, dtype=bool)
mask[indices] = 1
self.first_access[(self.first_access == -1) & mask] = self.pos
def add(self,
obs: np.ndarray,
next_obs: np.ndarray,
action: np.ndarray,
reward: np.ndarray,
done: np.ndarray,
infos: List[Dict[str, Any]]
):
super().add(obs, next_obs, action, reward, done, infos)
def _get_chunk_batches(self, beginnings):
sampled_indices = super()._get_chunk_batches(beginnings)
self._log_indices(sampled_indices.flatten())
return sampled_indices
| 35.454545 | 70 | 0.638462 | 3.25 |
fb2c885c08cc9d7c61fc9798ed2675ae3535e38f
| 8,420 |
go
|
Go
|
server/sqlstore/migrations.go
|
Manimaran11/mattermost-plugin-incident-response
|
4aa1ef166aecb881a27239a5f6e3bdfaf9c31802
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
server/sqlstore/migrations.go
|
Manimaran11/mattermost-plugin-incident-response
|
4aa1ef166aecb881a27239a5f6e3bdfaf9c31802
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
server/sqlstore/migrations.go
|
Manimaran11/mattermost-plugin-incident-response
|
4aa1ef166aecb881a27239a5f6e3bdfaf9c31802
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
package sqlstore
import (
"encoding/json"
"fmt"
sq "github.com/Masterminds/squirrel"
"github.com/blang/semver"
"github.com/jmoiron/sqlx"
"github.com/mattermost/mattermost-plugin-incident-response/server/playbook"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/pkg/errors"
)
type Migration struct {
fromVersion semver.Version
toVersion semver.Version
migrationFunc func(sqlx.Ext, *SQLStore) error
}
var migrations = []Migration{
{
fromVersion: semver.MustParse("0.0.0"),
toVersion: semver.MustParse("0.1.0"),
migrationFunc: func(e sqlx.Ext, sqlStore *SQLStore) error {
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_System (
SKey VARCHAR(64) PRIMARY KEY,
SValue VARCHAR(1024) NULL
);
`); err != nil {
return errors.Wrapf(err, "failed creating table IR_System")
}
if e.DriverName() == model.DATABASE_DRIVER_MYSQL {
charset := "DEFAULT CHARACTER SET utf8mb4"
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_Incident (
ID VARCHAR(26) PRIMARY KEY,
Name VARCHAR(1024) NOT NULL,
Description VARCHAR(4096) NOT NULL,
IsActive BOOLEAN NOT NULL,
CommanderUserID VARCHAR(26) NOT NULL,
TeamID VARCHAR(26) NOT NULL,
ChannelID VARCHAR(26) NOT NULL UNIQUE,
CreateAt BIGINT NOT NULL,
EndAt BIGINT NOT NULL DEFAULT 0,
DeleteAt BIGINT NOT NULL DEFAULT 0,
ActiveStage BIGINT NOT NULL,
PostID VARCHAR(26) NOT NULL DEFAULT '',
PlaybookID VARCHAR(26) NOT NULL DEFAULT '',
ChecklistsJSON TEXT NOT NULL,
INDEX IR_Incident_TeamID (TeamID),
INDEX IR_Incident_TeamID_CommanderUserID (TeamID, CommanderUserID),
INDEX IR_Incident_ChannelID (ChannelID)
)
` + charset); err != nil {
return errors.Wrapf(err, "failed creating table IR_Incident")
}
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_Playbook (
ID VARCHAR(26) PRIMARY KEY,
Title VARCHAR(1024) NOT NULL,
Description VARCHAR(4096) NOT NULL,
TeamID VARCHAR(26) NOT NULL,
CreatePublicIncident BOOLEAN NOT NULL,
CreateAt BIGINT NOT NULL,
DeleteAt BIGINT NOT NULL DEFAULT 0,
ChecklistsJSON TEXT NOT NULL,
NumStages BIGINT NOT NULL DEFAULT 0,
NumSteps BIGINT NOT NULL DEFAULT 0,
INDEX IR_Playbook_TeamID (TeamID),
INDEX IR_PlaybookMember_PlaybookID (ID)
)
` + charset); err != nil {
return errors.Wrapf(err, "failed creating table IR_Playbook")
}
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_PlaybookMember (
PlaybookID VARCHAR(26) NOT NULL REFERENCES IR_Playbook(ID),
MemberID VARCHAR(26) NOT NULL,
INDEX IR_PlaybookMember_PlaybookID (PlaybookID),
INDEX IR_PlaybookMember_MemberID (MemberID)
)
` + charset); err != nil {
return errors.Wrapf(err, "failed creating table IR_PlaybookMember")
}
} else {
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_Incident (
ID TEXT PRIMARY KEY,
Name TEXT NOT NULL,
Description TEXT NOT NULL,
IsActive BOOLEAN NOT NULL,
CommanderUserID TEXT NOT NULL,
TeamID TEXT NOT NULL,
ChannelID TEXT NOT NULL UNIQUE,
CreateAt BIGINT NOT NULL,
EndAt BIGINT NOT NULL DEFAULT 0,
DeleteAt BIGINT NOT NULL DEFAULT 0,
ActiveStage BIGINT NOT NULL,
PostID TEXT NOT NULL DEFAULT '',
PlaybookID TEXT NOT NULL DEFAULT '',
ChecklistsJSON JSON NOT NULL
);
`); err != nil {
return errors.Wrapf(err, "failed creating table IR_Incident")
}
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_Playbook (
ID TEXT PRIMARY KEY,
Title TEXT NOT NULL,
Description TEXT NOT NULL,
TeamID TEXT NOT NULL,
CreatePublicIncident BOOLEAN NOT NULL,
CreateAt BIGINT NOT NULL,
DeleteAt BIGINT NOT NULL DEFAULT 0,
ChecklistsJSON JSON NOT NULL,
NumStages BIGINT NOT NULL DEFAULT 0,
NumSteps BIGINT NOT NULL DEFAULT 0
);
`); err != nil {
return errors.Wrapf(err, "failed creating table IR_Playbook")
}
if _, err := e.Exec(`
CREATE TABLE IF NOT EXISTS IR_PlaybookMember (
PlaybookID TEXT NOT NULL REFERENCES IR_Playbook(ID),
MemberID TEXT NOT NULL,
UNIQUE (PlaybookID, MemberID)
);
`); err != nil {
return errors.Wrapf(err, "failed creating table IR_PlaybookMember")
}
// 'IF NOT EXISTS' syntax is not supported in 9.4, so we need
// this workaround to make the migration idempotent
createIndex := func(indexName, tableName, columns string) string {
return fmt.Sprintf(`
DO
$$
BEGIN
IF to_regclass('%s') IS NULL THEN
CREATE INDEX %s ON %s (%s);
END IF;
END
$$;
`, indexName, indexName, tableName, columns)
}
if _, err := e.Exec(createIndex("IR_Incident_TeamID", "IR_Incident", "TeamID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_Incident_TeamID")
}
if _, err := e.Exec(createIndex("IR_Incident_TeamID_CommanderUserID", "IR_Incident", "TeamID, CommanderUserID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_Incident_TeamID_CommanderUserID")
}
if _, err := e.Exec(createIndex("IR_Incident_ChannelID", "IR_Incident", "ChannelID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_Incident_ChannelID")
}
if _, err := e.Exec(createIndex("IR_Playbook_TeamID", "IR_Playbook", "TeamID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_Playbook_TeamID")
}
if _, err := e.Exec(createIndex("IR_PlaybookMember_PlaybookID", "IR_PlaybookMember", "PlaybookID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_PlaybookMember_PlaybookID")
}
if _, err := e.Exec(createIndex("IR_PlaybookMember_MemberID", "IR_PlaybookMember", "MemberID")); err != nil {
return errors.Wrapf(err, "failed creating index IR_PlaybookMember_MemberID ")
}
}
return nil
},
},
{
fromVersion: semver.MustParse("0.1.0"),
toVersion: semver.MustParse("0.2.0"),
migrationFunc: func(e sqlx.Ext, sqlStore *SQLStore) error {
// prior to v1.0.0 of the plugin, this migration was used to trigger the data migration from the kvstore
return nil
},
},
{
fromVersion: semver.MustParse("0.2.0"),
toVersion: semver.MustParse("0.3.0"),
migrationFunc: func(e sqlx.Ext, sqlStore *SQLStore) error {
if e.DriverName() == model.DATABASE_DRIVER_MYSQL {
if _, err := e.Exec("ALTER TABLE IR_Incident ADD ActiveStageTitle VARCHAR(1024) DEFAULT ''"); err != nil {
return errors.Wrapf(err, "failed adding column ActiveStageTitle to table IR_Incident")
}
} else {
if _, err := e.Exec("ALTER TABLE IR_Incident ADD ActiveStageTitle TEXT DEFAULT ''"); err != nil {
return errors.Wrapf(err, "failed adding column ActiveStageTitle to table IR_Incident")
}
}
getIncidentsQuery := sqlStore.builder.
Select("ID", "ActiveStage", "ChecklistsJSON").
From("IR_Incident")
var incidents []struct {
ID string
ActiveStage int
ChecklistsJSON json.RawMessage
}
if err := sqlStore.selectBuilder(e, &incidents, getIncidentsQuery); err != nil {
return errors.Wrapf(err, "failed getting incidents to update their ActiveStageTitle")
}
for _, theIncident := range incidents {
var checklists []playbook.Checklist
if err := json.Unmarshal(theIncident.ChecklistsJSON, &checklists); err != nil {
return errors.Wrapf(err, "failed to unmarshal checklists json for incident id: '%s'", theIncident.ID)
}
numChecklists := len(checklists)
if numChecklists == 0 {
continue
}
if theIncident.ActiveStage < 0 || theIncident.ActiveStage >= numChecklists {
sqlStore.log.Warnf("index %d out of bounds, incident '%s' has %d stages: setting ActiveStageTitle to the empty string", theIncident.ActiveStage, theIncident.ID, numChecklists)
continue
}
incidentUpdate := sqlStore.builder.
Update("IR_Incident").
Set("ActiveStageTitle", checklists[theIncident.ActiveStage].Title).
Where(sq.Eq{"ID": theIncident.ID})
if _, err := sqlStore.execBuilder(e, incidentUpdate); err != nil {
return errors.Errorf("failed updating the ActiveStageTitle field of incident '%s'", theIncident.ID)
}
}
return nil
},
},
}
| 33.815261 | 180 | 0.669002 | 3.015625 |
f00ff90a15569e736314d9e7505d121e6996f894
| 4,216 |
py
|
Python
|
json_replacer.py
|
MrMusicMan/json-item-replacer
|
04362b5e5ecf3cf9dd12ef3e72a7a1474a5239fa
|
[
"Apache-2.0"
] | null | null | null |
json_replacer.py
|
MrMusicMan/json-item-replacer
|
04362b5e5ecf3cf9dd12ef3e72a7a1474a5239fa
|
[
"Apache-2.0"
] | null | null | null |
json_replacer.py
|
MrMusicMan/json-item-replacer
|
04362b5e5ecf3cf9dd12ef3e72a7a1474a5239fa
|
[
"Apache-2.0"
] | null | null | null |
import os
import json
import string
from tkinter import filedialog, simpledialog
from tkinter import *
class CsvImporter(object):
def __init__(self):
self.csv_data = None
self.languages = []
def import_csv(self, csv_filename):
with open(csv_filename, 'r') as file:
self.csv_data = {}
for key, line in enumerate(file):
# Create list of line item.
line_items = [x.strip() for x in line.split(',')]
# Header row?
if key == 0:
# Create dictionaries for each language, except the first.
self.languages = line_items[1:]
for language in self.languages:
self.csv_data[language] = {}
else:
# Populate each language's dictionary.
for key, language in enumerate(self.languages):
try:
# Key from first column, value from next.
self.csv_data[language].update({
line_items[0]: line_items[key + 1]
})
except IndexError:
# Sometimes, no item is expected.
pass
return self.csv_data
class JsonEditor(object):
def import_json(self, json_filename):
# Bring JSON in as an object.
with open(json_filename) as file:
json_data = json.load(file)
return json_data
def export_new_json(self, output_filename, json_data):
# Save the JSON object as a file.
f = open(output_filename, "w")
json_data = json.dumps(json_data)
f.write(json_data)
f.close()
return
def update_json(self, input_json, target_key, target_value, update_value):
# Duplicate input_json for modification.
output_json = input_json
if isinstance(input_json, dict):
# Loop through dictionary, searching for target_key, target_value
# and update output_json if there is an update_value
for key, value in input_json.items():
if key == target_key:
if target_value == value:
if update_value:
output_json[key] = update_value
# If we run into a list or another dictionary, recurse.
self.update_json(input_json[key], target_key, target_value, update_value)
elif isinstance(input_json, list):
# Loop through list, searching for lists and dictionaries.
for entity in input_json:
# Recurse through any new list or dictionary.
self.update_json(entity, target_key, target_value, update_value)
return output_json
if __name__ == '__main__':
root = Tk()
root.csv_filename = filedialog.askopenfilename(
title="Select CSV file with translations",
filetypes=(("CSV Files", "*.csv"),)
)
root.json_filename = filedialog.askopenfilename(
title="Select master JSON file to build tranlated JSON files",
filetypes=(("JSON Files","*.json"),("All Files", "*.*"))
)
target_key = simpledialog.askstring(
"Input",
"What is the target key for the values we are replacing?",
initialvalue="title"
)
base_output_filename = simpledialog.askstring(
"Input",
"What would you like the base file to be named?"
)
# Import CSV.
csv = CsvImporter()
csv_data = csv.import_csv(root.csv_filename)
# Import JSON.
make_json = JsonEditor()
# Make changes per language.
for language in csv_data:
# Edit JSON.
input_json = make_json.import_json(root.json_filename)
for key, value in csv_data[language].items():
updated_json = make_json.update_json(input_json, target_key, key, value)
# Create filename per language.
language_filename = base_output_filename + "_" + language + ".json"
made_json = make_json.export_new_json(language_filename, updated_json)
# Finished.
print("Success!")
| 34.842975 | 89 | 0.57851 | 3.171875 |
6547bff0921c0fa8bf1ae4180062d6c76818b672
| 3,553 |
py
|
Python
|
stochastic_hill_climbing/src/AdalineSGD.py
|
Wookhwang/Machine-Learning
|
8eaf8517057d4beb3272081cb2f2092687123f3d
|
[
"Apache-2.0"
] | null | null | null |
stochastic_hill_climbing/src/AdalineSGD.py
|
Wookhwang/Machine-Learning
|
8eaf8517057d4beb3272081cb2f2092687123f3d
|
[
"Apache-2.0"
] | 1 |
2020-01-19T10:14:41.000Z
|
2020-01-19T10:14:41.000Z
|
stochastic_hill_climbing/src/AdalineSGD.py
|
Wookhwang/Machine-Learning
|
8eaf8517057d4beb3272081cb2f2092687123f3d
|
[
"Apache-2.0"
] | null | null | null |
import numpy as np
# gradient descent는 tensorflow에 이미 구현이 되어있다.
# 확률적 선형 뉴런 분석기는 각 훈련 샘플에 대해서 조금씩 가중치를 업데이트 한다.
class AdalineSGD(object):
"""Adaptive Linear Neuron 분류기
매개변수
------------
eta : float
학습률 (0.0과 1.0 사이)
n_iter : int
훈련 데이터셋 반복 횟수
shuffle : bool (default true)
True로 설정하면 같은 반복이 되지 않도록 에포크마다 훈련 데이터를 섞습니다.
random_state : int
가중치 무작위 초기화를 위한 난수 생성기 시드
속성
-----------
w_ : 1d-array
학습된 가중치
cost_ : list
에포크마다 누적된 비용 함수의 제곱합
"""
def __init__(self, eta=0.01, n_iter=10, suffle=True, random_state=None):
self.eta = eta
self.n_iter = n_iter
self.suffle = suffle
self.random_state = random_state
self.w_initialize = False
def fit(self, X, y):
"""훈련 데이터 학습
매개변수
----------
X : {array-like}, shape = [n_samples, n_features]
n_samples개의 샘플과 n_features개의 특성으로 이루어진 훈련 데이터
y : array-like, shape = [n_samples]
타깃값
반환값
-------
self : object
"""
# 언제나 그렇듯 fit()은 분류기 훈련용
# 대신에 확률적 분류기에서는 _initialized_weights()을 사용해 행 갯수 만큼 가중치를 초기화
self._initialized_weights(X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
# _suffle()을 사용해서 훈련 데이터를 섞어줌. True일 때만
if self.suffle:
X, y = self._suffle(X, y)
cost = []
# 가중치 업데이트 하고, cost도 update해준다.
for xi, target in zip(X, y):
cost.append(self._update_weights(xi, target))
# 평균 비용을 구해서 cost_ 리스트에 추가시켜준다.
avg_cost = sum(cost) / len(y)
self.cost_.append(avg_cost)
return self
# partial_fit()은 온라인 학습용으로 구현 함.
# 지속적으로 업데이트 되는 훈련 셋이 들어올 때 사용
def partial_fit(self, X, y):
"""가중치를 다시 초기화하지 않고 훈련 데이터를 학습합니다."""
if not self.w_initialize:
self._intialized_weights(X.shape[1])
if y.ravel().shape[0] > 1:
for xi, target in zip(X, y):
self._update_weights(xi, target)
else:
self._update_weights(X, y)
return self
def _suffle(self, X, y):
"""훈련 데이터를 섞음"""
# permatation()을 통해 0~100까지 중복되지 않은 랜덤한 숫자 시퀸스를 생성 (y의 길이만큼)
# 이 숫자 시퀸스는 특성 행렬과 클래스 레이블 백터를 섞는 인덱스로 활용
r = self.rgen.permutation(len(y))
return X[r], y[r]
def _initialized_weights(self, m):
"""랜덤한 작은 수로 가중치를 초기화"""
self.rgen = np.random.RandomState(self.random_state)
self.w_ = self.rgen.normal(loc=0.0, scale=0.01, size=1+m)
self.w_initialize = True
def _update_weights(self, xi, target):
"""아달린 학습 규칙을 적용하여 가중치를 업데이트"""
output = self.activation(self.net_input(xi))
error = (target - output)
self.w_[1:] += self.eta * xi.dot(error)
self.w_[0] += self.eta * error
cost = 0.5 * error ** 2
return cost
def net_input(self, X):
"""최종 입력 계산"""
return np.dot(X, self.w_[1:]) + self.w_[0]
# 단순 항등 함수 (단일층 시녕망을 통해 정보의 흐름을 표현 하기 위한 함수)
def activation(self, X):
"""선형 활성화 계산"""
return X
def predict(self, X):
"""단위 계산 함수를 사용하여 클래스 테이블을 반환합니다."""
return np.where(self.activation(self.net_input(X)) >= 0.0, 1, -1)
# 입력 데이터의 특성에서 최종 입력, 활성화, 출력 순으로 진행
| 30.110169 | 77 | 0.509992 | 3.203125 |
0403d8f57af5cb1a56ed78e4828f2a755d6269aa
| 4,550 |
js
|
JavaScript
|
extension/app.js
|
Petingo/youtube-button-clicker
|
99d85b893420b2af6e8b1c36028120851d3c52b3
|
[
"MIT"
] | 6 |
2018-12-02T06:49:54.000Z
|
2019-07-23T11:28:42.000Z
|
extension/app.js
|
Petingo/youtube-button-clicker
|
99d85b893420b2af6e8b1c36028120851d3c52b3
|
[
"MIT"
] | 1 |
2019-11-14T08:12:17.000Z
|
2019-11-14T08:43:41.000Z
|
extension/app.js
|
Petingo/youtube-button-clicker
|
99d85b893420b2af6e8b1c36028120851d3c52b3
|
[
"MIT"
] | 1 |
2021-03-09T14:06:52.000Z
|
2021-03-09T14:06:52.000Z
|
; (function () {
console.log("1")
let videoAdDelay = 5;
let overlayAdDelay = 3;
let nextVideoDelay = 10;
chrome.storage.sync.get({
videoAdDelay: 5,
overlayAdDelay: 3,
nextVideoDelay: 10
}, function (config) {
console.log("retrived config:", config)
videoAdDelay = config.videoAdDelay;
overlayAdDelay = config.overlayAdDelay
nextVideoDelay = config.nextVideoDelay
console.log(videoAdDelay, overlayAdDelay, nextVideoDelay);
let setupStatus = {
videoPopup: false,
videoEnd: false,
ad: false
}
let tmp = setInterval(function () {
let playerContainer;
if (window.location.pathname !== '/watch') {
return;
}
// video automatically paused in background
let video = document.getElementsByTagName('video')[0]
if(video && !setupStatus.videoEnd){
setupStatus.videoEnd = true
video.addEventListener('ended', function (e) {
let endedVideo = window.location.href
console.log(window.location.href)
setTimeout(() => {
// console.log("check if we should go next")
// console.log(window.location.href)
if(window.location.href == endedVideo){
console.log("go to up next video")
document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > a.ytp-next-button.ytp-button").click()
} else {
console.log("already get to next")
}
}, nextVideoDelay * 1000)
});
}
// video has already paused popup
popupContainer = document.querySelector("body > ytd-app > ytd-popup-container")
if (popupContainer && !setupStatus.videoPopup) {
setupStatus.videoPopup = true
popupContainer.arrive("paper-dialog > yt-confirm-dialog-renderer .buttons.style-scope.yt-confirm-dialog-renderer #confirm-button paper-button", function () {
document.querySelector("body > ytd-app > ytd-popup-container > paper-dialog > yt-confirm-dialog-renderer .buttons.style-scope.yt-confirm-dialog-renderer #confirm-button paper-button").click()
})
}
// ad skipper
playerContainer = document.getElementById('player-container');
if (playerContainer && !setupStatus.ad) {
setupStatus.ad = true
videoAd = document.querySelector("#player-container .ytp-ad-skip-button-container")
overlayAd = document.querySelector("#player-container .ytp-ad-overlay-close-button")
if (videoAd) {
console.log("close video Ad")
click(videoAd, videoAdDelay * 1000)
}
if (overlayAd) {
console.log("close overlay Ad")
click(overlayAd, overlayAdDelay * 1000)
}
playerContainer.arrive(".ytp-ad-skip-button-container", function () {
console.log("close video Ad")
click(this, overlayAdDelay * 1000);
})
playerContainer.arrive(".ytp-ad-overlay-close-button", function () {
console.log("close overlay Ad")
click(this, videoAdDelay * 1000);
})
}
console.log(setupStatus)
let setupStatusResult = true
for(let key in setupStatus){
setupStatusResult = setupStatusResult && setupStatus[key]
}
if(setupStatus){
clearInterval(tmp);
}
}, 250);
});
function click(element, delay) {
setTimeout(function () {
// if (element.fireEvent) {
// element.fireEvent('onclick')
// } else {
// let click = document.createEvent('Events');
// click.initEvent('click', true, false);
// element.dispatchEvent(click);
// }
console.log("fired")
element.click()
}, delay);
}
})();
| 38.888889 | 211 | 0.509231 | 3.09375 |
569a033177632880e327260cefa137e5904d816d
| 4,831 |
ts
|
TypeScript
|
tests/get-day-info.spec.ts
|
yasser-mas/working-time
|
b1f444ae1e7eef22a4beb2fe95240fecc988b2ad
|
[
"MIT"
] | null | null | null |
tests/get-day-info.spec.ts
|
yasser-mas/working-time
|
b1f444ae1e7eef22a4beb2fe95240fecc988b2ad
|
[
"MIT"
] | 3 |
2020-07-18T00:10:53.000Z
|
2021-09-01T17:39:05.000Z
|
tests/get-day-info.spec.ts
|
yasser-mas/working-time
|
b1f444ae1e7eef22a4beb2fe95240fecc988b2ad
|
[
"MIT"
] | null | null | null |
import { expect, should, assert } from 'chai';
import TimerFactory from '../source/index';
import { Timer } from '../source/lib/timer';
import { VALID_TIMER_CONFIG } from './testing-data';
import { ITimerParams } from '../source/lib/interfaces/i-timer-params';
function getCopy(obj: ITimerParams ):ITimerParams{
return (JSON.parse(JSON.stringify(obj)));
}
describe('Get Day Info Test Cases', function() {
let timer : Timer ;
let timerConfig : ITimerParams ;
beforeEach(function() {
TimerFactory.clearTimer();
timer = TimerFactory.getTimerInstance();
timerConfig = getCopy(VALID_TIMER_CONFIG);
});
it('should be normal working day', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-07-25');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.false;
expect(dayInfo.isWeekend).to.be.false;
expect(dayInfo.workingHours).to.be.eql(timerConfig.normalWorkingHours[4]);
});
it('should throw exception on submit invalid date', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = '2019-07-25' as any ;
return timerInstance.getDayInfoAsync(day).catch(e =>{
expect(e.message).to.be.eql('Invalid Date !')
});
});
it('should throw exception on submit nullable date', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = null as any ;
return timerInstance.getDayInfoAsync(day).catch(e =>{
expect(e.message).to.be.eql('Invalid Date !')
});
});
it('should be weekend', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-07-26');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.false;
expect(dayInfo.isWeekend).to.be.true;
expect(dayInfo.workingHours).to.be.eql([]);
});
it('should be vacation', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-08-05');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.true;
expect(dayInfo.isWeekend).to.be.false;
});
it('should be exceptional working day', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-08-13');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.true;
expect(dayInfo.isVacation).to.be.false;
expect(dayInfo.isWeekend).to.be.false;
expect(dayInfo.workingHours).to.be.eql(timerConfig.exceptionalWorkingHours['2019-08-13']);
});
it('should extend buffered calendar on sbumit very old date', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2017-03-22');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.false;
expect(dayInfo.isWeekend).to.be.false;
expect(dayInfo.workingHours).to.be.eql(timerConfig.normalWorkingHours[3]);
});
it('should extend buffered calendar on sbumit far future date', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2022-05-22');
let dayInfo = timerInstance.getDayInfo(day);
expect(dayInfo.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.false;
expect(dayInfo.isWeekend).to.be.false;
expect(dayInfo.workingHours).to.be.eql(timerConfig.normalWorkingHours[0]);
});
it('should be vacation on submit date included as vacation wildcard', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-09-05');
let dayInfo = timerInstance.getDayInfo(day);
let dayInfo2 = timerInstance.getDayInfo(new Date('2021-09-05'));
expect(dayInfo.isExceptional).to.be.eql(dayInfo2.isExceptional).to.be.false;
expect(dayInfo.isVacation).to.be.eql(dayInfo2.isVacation).to.be.true;
expect(dayInfo.isWeekend).to.be.eql(dayInfo2.isWeekend).to.be.false;
});
it('should be exceptionale on submit date included as exceptional wildcard', function() {
const timerInstance = timer.setConfig(timerConfig);
let day = new Date('2019-08-16');
let dayInfo = timerInstance.getDayInfo(day);
let dayInfo2 = timerInstance.getDayInfo(new Date('2021-08-16'));
let dayInfo3 = timerInstance.getDayInfo(new Date('2001-08-16'));
expect(dayInfo.isExceptional).to.be.eql(dayInfo2.isExceptional).to.be.eql(dayInfo3.isExceptional).to.be.true;
expect(dayInfo.workingHours).to.be.eql(dayInfo2.workingHours).to.be.eql(dayInfo3.workingHours).to.be.eql(timerConfig.exceptionalWorkingHours['*-08-16']);
});
});
| 32.863946 | 157 | 0.703374 | 3.25 |
7531574ddee2b20a358f920cbb64b09119cd233e
| 1,624 |
c
|
C
|
worksheet3/computeCellValues.c
|
nasay/cfdlab
|
6fae95b8f926609b0c8643d31d5f2a2858ee3f71
|
[
"MIT"
] | 1 |
2020-01-11T17:50:18.000Z
|
2020-01-11T17:50:18.000Z
|
worksheet3/computeCellValues.c
|
nasay/cfdlab
|
6fae95b8f926609b0c8643d31d5f2a2858ee3f71
|
[
"MIT"
] | null | null | null |
worksheet3/computeCellValues.c
|
nasay/cfdlab
|
6fae95b8f926609b0c8643d31d5f2a2858ee3f71
|
[
"MIT"
] | null | null | null |
#include "LBDefinitions.h"
#include "computeCellValues.h"
#include <stdio.h>
void computeDensity(const double *const currentCell, double *density){
/*
* Computes the macroscopic density within currentCell
* rho(x,t) = sum(f_i, i=0:Q-1)
*/
int i;
*density = 0;
for (i=0; i<Q; i++) {
*density += currentCell[i];
}
}
void computeVelocity(const double * const currentCell, const double * const density, double *velocity){
/*
* Computes the velocity within currentCell
* u(x,t) = sum(f[i] * c[i] for i in [0:Q-1]) / rho
*/
int i,j;
for (j=0; j<3; j++) {
velocity[j] = 0;
for (i=0; i<Q; i++) {
velocity[j] += LATTICEVELOCITIES[i][j] * currentCell[i];
}
velocity[j] /= *density;
}
}
void computeFeq(const double * const density, const double * const velocity, double *feq){
/*
* feq[i] = w[i] * rho * (1 + c_i*u / (c_s^2) + ...
*/
int i;
double ci_dot_u, u_dot_u;
double ci0, ci1, ci2, u0, u1, u2;
double cs2 = C_S * C_S;
for (i=0; i<Q; i++) {
ci0 = LATTICEVELOCITIES[i][0];
ci1 = LATTICEVELOCITIES[i][1];
ci2 = LATTICEVELOCITIES[i][2];
u0 = velocity[0];
u1 = velocity[1];
u2 = velocity[2];
ci_dot_u = ci0*u0 + ci1*u1 + ci2*u2;
u_dot_u = u0*u0 + u1*u1 + u2*u2;
feq[i] = 1;
feq[i] += ci_dot_u/cs2;
feq[i] += (ci_dot_u * ci_dot_u) / (2 * cs2 * cs2);
feq[i] -= u_dot_u / (2 * cs2);
feq[i] *= *density;
feq[i] *= LATTICEWEIGHTS[i];
}
}
| 24.238806 | 103 | 0.514163 | 3.28125 |
171237bded32aeb45d6da7a971e0e05715d5a6f1
| 1,754 |
c
|
C
|
server/command/command_time.c
|
Adam-/bedrock
|
428b91d7dfded30dc5eaec8b1d29d10a49da34b8
|
[
"BSD-2-Clause"
] | 13 |
2015-01-11T04:39:21.000Z
|
2021-03-08T13:00:48.000Z
|
server/command/command_time.c
|
Adam-/bedrock
|
428b91d7dfded30dc5eaec8b1d29d10a49da34b8
|
[
"BSD-2-Clause"
] | null | null | null |
server/command/command_time.c
|
Adam-/bedrock
|
428b91d7dfded30dc5eaec8b1d29d10a49da34b8
|
[
"BSD-2-Clause"
] | 4 |
2015-04-06T12:55:05.000Z
|
2021-06-25T03:40:19.000Z
|
#include "server/command.h"
#include "command/command_time.h"
#include "server/packets.h"
#include <errno.h>
static void update_time(struct command_source *source, struct world *world, long time)
{
bedrock_node *node;
command_reply(source, "Time in %s changed to %ld", world->name, time);
world->time = time;
LIST_FOREACH(&client_list, node)
{
struct client *c = node->data;
if (c->world == world)
packet_send_time(c);
}
}
void command_time(struct command_source *source, int argc, const char **argv)
{
struct world *world;
if (source->user != NULL)
world = source->user->world;
else
{
if (world_list.count == 0)
{
command_reply(source, "There are no laoded worlds");
return;
}
world = world_list.head->data;
}
if (argc == 3)
{
if (!strcasecmp(argv[1], "set"))
{
char *errptr = NULL;
long time;
errno = 0;
time = strtol(argv[2], &errptr, 10);
if (errno || *errptr)
{
command_reply(source, "Invalid time");
return;
}
else
{
time %= 24000;
update_time(source, world, time);
}
}
}
else if (argc == 2)
{
if (!strcasecmp(argv[1], "day") || !strcasecmp(argv[1], "noon"))
update_time(source, world, 6000);
else if (!strcasecmp(argv[1], "night") || !strcasecmp(argv[1], "midnight"))
update_time(source, world, 18000);
else if (!strcasecmp(argv[1], "dawn") || !strcasecmp(argv[1], "morning"))
update_time(source, world, 24000);
else if (!strcasecmp(argv[1], "dusk") || !strcasecmp(argv[1], "evening"))
update_time(source, world, 12000);
}
else
{
bedrock_node *node;
LIST_FOREACH(&world_list, node)
{
struct world *world = node->data;
command_reply(source, "Current time in %s is %ld", world->name, world->time);
}
}
}
| 20.880952 | 86 | 0.631129 | 3.015625 |
d7dba33ba10b446f4eb0c26a1aa11ab7edd60b3a
| 1,378 |
swift
|
Swift
|
src/Day6Part2/Sources/Day6Part2/main.swift
|
nickygerritsen/AdventOfCode2018
|
4a69d4acf8c55e3118e1428fb949afda52ff6b83
|
[
"MIT"
] | null | null | null |
src/Day6Part2/Sources/Day6Part2/main.swift
|
nickygerritsen/AdventOfCode2018
|
4a69d4acf8c55e3118e1428fb949afda52ff6b83
|
[
"MIT"
] | null | null | null |
src/Day6Part2/Sources/Day6Part2/main.swift
|
nickygerritsen/AdventOfCode2018
|
4a69d4acf8c55e3118e1428fb949afda52ff6b83
|
[
"MIT"
] | null | null | null |
import Shared
import Foundation
struct Point {
let x: Int
let y: Int
static func distance(_ p1: Point, _ p2: Point) -> Int {
return abs(p1.x - p2.x) + abs(p1.y - p2.y)
}
}
extension Point: Input {
static func convert(contents: String) -> Point? {
let parts = contents.split(separator: ",")
if let x = Int(parts[0]), let y = Int(parts[1].trimmingCharacters(in: .whitespacesAndNewlines)) {
return Point(x: x, y: y)
}
return nil
}
}
if let input: [Point] = readInput(day: 6) {
var points: [Int: Point] = [:]
for idx in 0..<input.count {
points[idx] = input[idx]
}
let maxDistance = 10000
// Determine the max distance we should check: this is maxDistance / #points
let maxCheck = maxDistance / points.count
var answer = 0
if let maxXP = input.min(by: { $0.x > $1.x }),
let maxYP = input.min(by: { $0.y > $1.y }) {
let maxX = maxXP.x
let maxY = maxYP.y
for x in -maxCheck...maxX + maxCheck {
for y in -maxCheck...maxY + maxCheck {
let p = Point(x: x, y: y)
let totalDistance = points.map({ Point.distance(p, $0.value) }).reduce(0, +)
if totalDistance < maxDistance {
answer += 1
}
}
}
}
print(answer)
}
| 26.5 | 105 | 0.528302 | 3.59375 |
16cff0463d3ab978f1231c8b963e4d217edbfac3
| 2,667 |
ts
|
TypeScript
|
sources/components/Program.ts
|
cedric-demongivert/gl-tool-shader
|
1556b71840070bceca573bd25be0a211ddd07b85
|
[
"MIT"
] | null | null | null |
sources/components/Program.ts
|
cedric-demongivert/gl-tool-shader
|
1556b71840070bceca573bd25be0a211ddd07b85
|
[
"MIT"
] | null | null | null |
sources/components/Program.ts
|
cedric-demongivert/gl-tool-shader
|
1556b71840070bceca573bd25be0a211ddd07b85
|
[
"MIT"
] | null | null | null |
import { Component } from '@cedric-demongivert/gl-tool-ecs'
import { ProgramIdentifier } from '../ProgramIdentifier'
import { ShaderIdentifier } from '../ShaderIdentifier'
import { Shader } from './Shader'
export class Program {
/**
* Identifier of this program.
*/
public identifier : ProgramIdentifier
/**
* Vertex shader associated to this program.
*/
public vertex : Component<Shader>
/**
* Fragment shader associated to this program.
*/
public fragment : Component<Shader>
/**
* Create a new program.
*/
public constructor (
identifier : ProgramIdentifier = ProgramIdentifier.UNDEFINED
) {
this.identifier = identifier
this.vertex = null
this.fragment = null
}
public getVertexShaderIdentifier () : ShaderIdentifier {
if (this.vertex) {
return this.vertex.data.identifier
} else {
return ShaderIdentifier.UNDEFINED
}
}
public getFragmentShaderIdentifier () : ShaderIdentifier {
if (this.fragment) {
return this.fragment.data.identifier
} else {
return ShaderIdentifier.UNDEFINED
}
}
/**
* Copy the state of the given component.
*
* @param toCopy - A component instance to copy.
*/
public copy (toCopy : Program) : void {
this.identifier = toCopy.identifier
this.vertex = toCopy.vertex
this.fragment = toCopy.fragment
}
/**
* Reset the state of this component to it's default state.
*/
public clear () : void {
this.identifier = ProgramIdentifier.UNDEFINED
this.vertex = null
this.fragment = null
}
/**
* @return An instance of shader equals to this one.
*/
public clone () : Program {
const clone : Program = new Program()
clone.copy(this)
return clone
}
/**
* @see Object.equals
*/
public equals (other : any) : boolean {
if (other == null) return false
if (other === this) return true
if (other instanceof Program) {
return other.identifier === this.identifier &&
Component.equals(other.vertex, this.vertex) &&
Component.equals(other.fragment, this.fragment)
}
return false
}
}
export namespace Program {
export function copy (toCopy : undefined) : undefined
export function copy (toCopy : null) : null
export function copy (toCopy : Program) : Program
/**
* Return an instance of program that is equal to the given one.
*
* @param toCopy - A program instance to copy.
* @return An instance of program that is equal to the given one.
*/
export function copy (toCopy : Program | undefined | null) : Program | undefined | null {
return toCopy == null ? toCopy : toCopy.clone()
}
}
| 24.027027 | 91 | 0.656918 | 3.125 |
70cef7bce1dc0f24d6f1a975a9896ddb0c6e70f0
| 3,409 |
h
|
C
|
kirke/include/kirke/error.h
|
this-kirke/kirke
|
5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c
|
[
"MIT"
] | null | null | null |
kirke/include/kirke/error.h
|
this-kirke/kirke
|
5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c
|
[
"MIT"
] | null | null | null |
kirke/include/kirke/error.h
|
this-kirke/kirke
|
5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c
|
[
"MIT"
] | null | null | null |
/**
* \file kirke/error.h
*/
#ifndef KIRKE__ERROR__H
#define KIRKE__ERROR__H
// System Includes
#include <stdbool.h>
// Internal Includes
#include "kirke/macros.h"
BEGIN_DECLARATIONS
/**
* \defgroup error Error
* @{
*/
/**
* Generally, we consider three types of errors: Machine errors, Programming errors, and User errors
*
* Machine errors occur when the hardware is incapable of handling some operation. The most common
* example of this is out of memory errors. A typical response to these is to panic and exit, but we leave
* the decision of how to handle this situation to the user. For example, the user is notfieid of an out of
* memory error by allocator->out_of_memory().
*
* Programming errors should notify the developer that something is incorrect. We handle these with log
* messages, as in log__warning() or log__error().
*
* User errors are only detectable at runtime, and include issues such as improper input - file not found,
* or invalid formatting, for example. The proper way to handle these is to notify the user, and gracefully
* exit the program.
*
* Handling user errors is the purpose of the Error structure.
*
* The type field is the broad category of error which was encountered. This is generally the name of the
* class which defines and throws the error.
*
* The code field is an integral identifier for the specific error encountered
*
* The message field allows the developer to provide a detailed message describing the error and relevant
* conditions of the error when encountered
*/
/**
* \brief A structure which represents a recoverable runtime error which was encountered.
*/
typedef struct Error{
/**
* A null-terminated C-style string of characters describing the error's broad type
*/
char type[ 32 ];
/**
* An identifier for this error, unique within its type.
*/
unsigned long long code;
/**
* A null-terminated C-style string of characters which describes the specific error condition
*/
char message[ 256 ];
} Error;
/**
* /def ERROR_CODE__NONE
* The error code stored in a default-initialized error. Denotes that no error has occurred, and the contents of
* fields type and message are not defined.
*/
#define Error__None 0
/**
* \brief This method sets the type, code and message of an Error structure.
* \param error A pointer to an Error structure. Upon completion, this will store the specified type,
* code and message.
* \param type A null-terminated C-style string which describes the general type of the message, such
* as the class in which the error originated.
* \param code An identifier for this particular error, unique within its type.
* \param format A format specifier with string replacement tokens, in the style of printf, which are
* used for creating the message
* field.
*/
void error__set( Error *error, const char* type, unsigned long long code, const char* format, ... );
/**
* \brief This method compares two Error structures for equality.
* \param first A pointer to the first error to be compared.
* \param second A pointer to the second error to be compared.
* \returns 1 if the two Error structures contain the same type and code, and 0 otherwise.
*/
bool error__equals( Error* first, Error* second );
/**
* @} group error
*/
END_DECLARATIONS
#endif // KIRKE__ERROR__H
| 34.09 | 113 | 0.722499 | 3 |
0ef345883507dc5d0e46b51d815417031b8b0ad7
| 777 |
tsx
|
TypeScript
|
examples/a.tsx
|
MisterLuffy/ts-document
|
c7a8b7c206f79297045a7b58125c193a3bbda646
|
[
"MIT"
] | null | null | null |
examples/a.tsx
|
MisterLuffy/ts-document
|
c7a8b7c206f79297045a7b58125c193a3bbda646
|
[
"MIT"
] | null | null | null |
examples/a.tsx
|
MisterLuffy/ts-document
|
c7a8b7c206f79297045a7b58125c193a3bbda646
|
[
"MIT"
] | null | null | null |
/**
* @title Plus
* @zh 两数相乘
* @en Multiply two numbers
* @returns Product of two numbers
*/
type Plus = (
/**
* @en First number
* @zh 被乘数
*/
a: number,
/**
* @en Second number
* @zh 乘数
* @defaultValue 1
*/
b: number
) => number;
/**
* @title Add
* @en Add two numbers
* @zh 两数相加
* @returns Sum of two numbers
* @version 1.0.0
*/
function Add(
/**
* @zh 被加数
* @en First number
*/
a: number,
/**
* @zh 加数
* @en Second number
*/
b = 5
) {
return a + b;
}
/**
* @title Button
* @zh 按钮
* @en Button
*/
type ButtonType = {
/**
* @zh 尺寸
* @en Size
* @defaultValue default
*/
size?: 'mini' | 'large' | 'default';
/**
* @zh 颜色
* @en Color
* @version 1.2.0
*/
color?: string;
};
| 12.532258 | 38 | 0.490347 | 3.25 |
d7b33c9bcedc14cbcac68e9880c4a5585e01159d
| 27,692 |
lua
|
Lua
|
Toribio/deviceloaders/dynamixel/motor.lua
|
Yatay/1.0
|
a553fbb0fd148b613e2bb6b2397c6f5a550236db
|
[
"MIT"
] | null | null | null |
Toribio/deviceloaders/dynamixel/motor.lua
|
Yatay/1.0
|
a553fbb0fd148b613e2bb6b2397c6f5a550236db
|
[
"MIT"
] | null | null | null |
Toribio/deviceloaders/dynamixel/motor.lua
|
Yatay/1.0
|
a553fbb0fd148b613e2bb6b2397c6f5a550236db
|
[
"MIT"
] | null | null | null |
--- Library for Dynamixel motors.
-- This library allows to manipulate devices that use Dynamixel
-- protocol, such as AX-12 robotic servo motors.
-- For basic manipulation, it is enough to use the @{rotate_to_angle} and @{spin} functions,
-- and perhaps set the @{set.torque_enable}. For more sophisticated tasks, the full
-- Dynamixel functionality is available trough getter and setter functions.
-- When available, each connected motor will be published
-- as a device in torobio.devices table, named
-- (for example) 'ax12:1', labeled as module 'ax'. Aditionally, an 'ax:all'
-- device will represent the broadcast wide motor. Also, 'ax:sync' motors can be used to
-- control several motors at the same time. Notice you can not read from broadcast nor sync
-- motors, only send commands to them.
-- Some of the setable parameters set are located on the motors EEPROM (marked "persist"),
-- and others are on RAM (marked "volatile"). The attributes stored in RAM are reset when the
-- motor is powered down.
-- For defaut values, check the Dynamixel documentation.
-- @module dynamixel-motor
-- @usage local toribio = require 'toribio'
--local motor = toribio.wait_for_device('ax12:1')
--motor.set.led(true)
-- @alias Motor
--local my_path = debug.getinfo(1, "S").source:match[[^@?(.*[\/])[^\/]-$]]
local log = require 'log'
local M = {}
local function getunsigned_2bytes(s)
return s:byte(1) + 256*s:byte(2)
end
local function get2bytes_unsigned(n)
if n<0 then n=0
elseif n>1023 then n=1023 end
local lowb, highb = n%256, math.floor(n/256)
return lowb, highb
end
local function get2bytes_signed(n)
if n<-1023 then n=-1023
elseif n>1023 then n=1023 end
if n < 0 then n = 1024 - n end
local lowb, highb = n%256, math.floor(n/256)
return lowb, highb
end
local function log2( x )
return math.log( x ) / math.log( 2 )
end
M.get_motor= function (busdevice, motor_id)
local read_data = busdevice.read_data
local write_method
local idb
local motor_mode -- 'joint' or 'wheel'
local motor_type -- 'single', 'sync' or 'broadcast'
local status_return_level
if type(motor_id) == 'table' then
motor_type = 'sync'
elseif motor_id == 0xFE then
motor_type = 'broadcast'
else
motor_type = 'single'
end
if motor_type~='sync' then
idb = string.char(motor_id)
write_method='write_data'
else
idb = {}
for i, anid in ipairs(motor_id) do
idb[i] = string.char(anid)
end
write_method='sync_write'
end
--Check wether the motor with id actually exists. If not, return nil.
if motor_type == 'single' then
if not busdevice.ping(idb) then
return nil
end
end
-- It exists, let's start building the object.
local Motor = {
--- Device file of the bus.
-- Filename of the bus to which the motor is connected.
-- For example, _'/dev/ttyUSB0'_
filename = busdevice.filename,
--- Bus device.
-- The dynamixel bus Device to which the motor is connected
busdevice = busdevice,
--- Dynamixel ID number.
motor_id = motor_id,
}
if motor_type == 'single' then
--- Ping the motor.
-- Only available for single motors, not sync nor broadcast.
-- @return a dynamixel error code
Motor.ping = function()
return busdevice.ping(idb)
end
end
-- calls that are only avalable on proper motors (not 'syncs motors')
if motor_type ~= 'sync' then
--- Reset configuration to factory default.
-- Use with care, as it also resets the ID number and baud rate.
-- For factory defaults, check Dynamixal documentation.
-- This command only works for single motors (not sync nor broadcast).
-- For defaut values, check the Dynamixel documentation.
-- @return a dynamixel error code
Motor.reset_factory_default = function()
return busdevice.reset(idb, status_return_level)
end
--- Starts a register write mode.
-- In reg_write mode changes in configuration to devices
-- are not applied until a @{reg_write_action} call.
-- This command only works for single motors (not sync nor broadcast).
Motor.reg_write_start = function()
write_method='reg_write_data'
end
--- Finishes a register write mode.
-- All changes in configuration applied after a previous
-- @{reg_write_start} are commited.
-- This command only works for single motors (not sync nor broadcast).
Motor.reg_write_action = function()
busdevice.action(idb,status_return_level)
write_method='write_data'
end
end -- /calls that are only avalable on proper motors (not 'syncs motors')
local control_getters = {
rotation_mode = function()
local ret, err = read_data(idb,0x06,4,status_return_level)
if ret==string.char(0x00,0x00,0x00,0x00) then
motor_mode = 'wheel'
else
motor_mode = 'joint'
end
return motor_mode, err
end,
model_number = function()
local ret, err = read_data(idb,0x00,2, status_return_level)
if ret then return getunsigned_2bytes(ret), err end
end,
firmware_version = function()
return read_data(idb,0x02,1, status_return_level)
end,
id = function()
return read_data(idb,0x03,1, status_return_level)
end,
baud_rate = function()
local ret, err = read_data(idb,0x04,1, status_return_level)
if ret then return math.floor(2000000/(ret+1)), err end --baud
end,
return_delay_time = function()
local ret, err = read_data(idb,0x05,1, status_return_level)
if ret then return (ret*2)/1000000, err end --sec
end,
angle_limit = function()
local ret, err = read_data(idb,0x06,4, status_return_level)
if ret then
local cw = 0.29*(ret:byte(1) + 256*ret:byte(2))
local ccw = 0.29*(ret:byte(3) + 256*ret:byte(4))
return cw, ccw, err
end -- deg
end,
limit_temperature = function()
return read_data(idb,0x0B,1, status_return_level)
end,
limit_voltage = function()
local ret, err = read_data(idb,0x0C,2, status_return_level)
if ret then return ret:byte(1)/10, ret:byte(2)/10, err end
end,
max_torque = function()
local ret, err = read_data(idb,0x0E,2, status_return_level)
if ret then return getunsigned_2bytes(ret) / 10.23, err end--% of max torque
end,
status_return_level = function()
local ret, err = read_data(idb,0x10,1, status_return_level or 2)
local return_levels = {
[0] = 'ONLY_PING',
[1] = 'ONLY_READ',
[2]= 'ALL'
}
if ret then
local code = ret:byte()
status_return_level = code
return return_levels[code], err
end
end,
alarm_led = function()
local ret, err = read_data(idb,0x11,1, status_return_level)
if ret then
return busdevice.has_errors(ret), err
end
end,
alarm_shutdown = function()
local ret, err = read_data(idb,0x12,1, status_return_level)
if ret then
local _, errorset = busdevice.has_errors(ret)
return errorset, err
end
end,
torque_enable = function()
local ret, err = read_data(idb,0x18,1, status_return_level)
if ret then return ret:byte()==0x01, err end
end,
led = function()
local ret, err = read_data(idb,0x19,1, status_return_level)
if ret then return ret:byte()==0x01, err end
end,
compliance_margin = function()
local ret, err = read_data(idb,0x1A,2, status_return_level)
if ret then return 0.29*ret:byte(1), 0.29*ret:byte(2), err end --deg
end,
compliance_slope = function()
local ret, err = read_data(idb,0x1C,2, status_return_level)
if ret then
return log2(ret:byte(1)), log2(ret:byte(2)), err
end
end,
goal_position = function()
local ret, err = read_data(idb,0x1E,2, status_return_level)
if ret then
local ang=0.29*getunsigned_2bytes(ret)
return ang, err -- deg
end
end,
moving_speed = function()
local ret, err = read_data(idb,0x20,2, status_return_level)
if ret then
local vel = getunsigned_2bytes(ret)
if motor_mode=='joint' then
return vel / 1.496, err --deg/sec
elseif motor_mode=='wheel' then
return vel / 10.23, err --% of max torque
end
end
end,
torque_limit = function()
local ret, err = read_data(idb,0x22,2, status_return_level)
if ret then
local ang=getunsigned_2bytes(ret) / 10.23
return ang, err -- % max torque
end
end,
present_position = function()
local ret, err = read_data(idb,0x24,2, status_return_level)
if ret then
local ang=0.29*getunsigned_2bytes(ret)
return ang, err -- deg
end
end,
present_speed = function()
local ret, err = read_data(idb,0x26,2, status_return_level)
local vel = getunsigned_2bytes(ret)
if vel > 1023 then vel =1024-vel end
if motor_mode=='joint' then
return vel / 1.496, err --deg/sec
elseif motor_mode=='wheel' then
return vel / 10.23, err --% of max torque
end
end,
present_load = function()
local ret, err = read_data(idb,0x28,2, status_return_level)
if ret then
local load = ret:byte(1) + 256*ret:byte(2)
if load > 1023 then load = 1024-load end
return load/10.23, err -- % of torque max
end
end,
present_voltage = function()
local ret, err = read_data(idb,0x2A,1, status_return_level)
if ret then return ret:byte()/10, err end
end,
present_temperature = function()
local ret, err = read_data(idb,0x2B,1, status_return_level)
if ret then return ret:byte(), err end
end,
registered = function()
local ret, err = read_data(idb,0x2C,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
moving = function()
local ret, err = read_data(idb,0x2E,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
lock = function()
local ret, err = read_data(idb,0x2F,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
punch = function()
local ret, err = read_data(idb,0x30,2, status_return_level)
if ret then
local load = ret:byte(1) + 256*ret:byte(2)
return load/10.23, err -- % of torque max
end
end
}
local control_setters = {
rotation_mode = function (mode)
local ret
if mode == 'wheel' then
ret = busdevice[write_method](idb,0x06,string.char(0, 0, 0, 0),status_return_level)
else
local max=1023
local maxlowb, maxhighb = get2bytes_unsigned(max)
ret = busdevice[write_method](idb,0x06,string.char(0, 0, maxlowb, maxhighb),status_return_level)
end
motor_mode = mode
return ret
end,
id = function(newid)
assert(newid>=0 and newid<=0xFD, 'Invalid ID: '.. tostring(newid))
motor_id, idb = newid, string.char(newid)
return busdevice[write_method](idb,0x3,string.char(newid),status_return_level)
end,
baud_rate = function(baud)
local n = math.floor(2000000/baud)-1
assert(n>=1 and n<=207, "Attempt to set serial speed: "..n)
return busdevice[write_method](idb,0x04,n,status_return_level)
end,
return_delay_time = function(sec)
local parameter = math.floor(sec * 1000000 / 2)
return busdevice[write_method](idb,0x05,string.char(parameter),status_return_level)
end,
angle_limit = function(cw, ccw)
if cw then cw=math.floor(cw/0.29)
else cw=0 end
if ccw then ccw=math.floor(ccw/0.29)
else ccw=1023 end
local minlowb, maxhighb = get2bytes_unsigned(cw)
local maxlowb, maxnhighb = get2bytes_unsigned(ccw)
local ret = busdevice[write_method](idb,0x06,string.char(minlowb, maxhighb, maxlowb, maxnhighb),status_return_level)
if cw==0 and ccw==0 then
motor_mode='wheel'
else
motor_mode='joint'
end
return ret
end,
limit_temperature = function(deg)
return busdevice[write_method](idb,0x0B,deg,status_return_level)
end,
limit_voltage = function(min, max)
local min, max = min*10, max*10
if min<=255 and min>0 and max<=255 and max>0 then
return busdevice[write_method](idb,0x0C,string.char(min, max),status_return_level)
end
end,
max_torque = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x0E,string.char(lowb,highb),status_return_level)
end,
status_return_level = function(level)
local level_codes= {
ONLY_PING = 0,
ONLY_READ = 1,
ALL = 2
}
local code = level_codes[level or 'ALL']
status_return_level = code
return busdevice[write_method](idb,0x10,string.char(code),status_return_level or 2)
end,
alarm_led = function(errors)
local code = 0
for _, err in ipairs(errors) do
code = code + (busdevice.ax_errors[err] or 0)
end
return busdevice[write_method](idb,0x11,string.char(code),status_return_level)
end,
alarm_shutdown = function(errors)
local code = 0
for _, err in ipairs(errors) do
code = code + (busdevice.ax_errors[err] or 0)
end
return busdevice[write_method](idb,0x12,string.char(code),status_return_level)
end,
torque_enable = function (value)
--boolean
local parameter
if value then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
return busdevice[write_method](idb,0x18,parameter,status_return_level)
end,
led = function (value)
local parameter
if value then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
assert(status_return_level, debug.traceback())
return busdevice[write_method](idb,0x19,parameter,status_return_level)
end,
compliance_margin = function(angle)
local ang=math.floor(angle/0.29)
local lowb, highb = get2bytes_unsigned(ang)
return busdevice[write_method](idb,0x1A,string.char(lowb,highb),status_return_level)
end,
compliance_slope = function(cw, ccw)
cw, ccw = math.floor(2^cw), math.floor(2^ccw)
return busdevice[write_method](idb,0x1C,string.char(cw,ccw),status_return_level)
end,
goal_position = function(angle)
local ang=math.floor(angle/0.29)
local lowb, highb = get2bytes_unsigned(ang)
return busdevice[write_method](idb,0x1E,string.char(lowb,highb),status_return_level)
end,
moving_speed = function(value)
if motor_mode=='joint' then
-- 0 .. 684 deg/sec
local vel=math.floor(value * 1.496)
local lowb, highb = get2bytes_unsigned(vel)
return busdevice[write_method](idb,0x20,string.char(lowb,highb),status_return_level)
elseif motor_mode=='wheel' then
-- -100% .. +100% max torque
local vel=math.floor(value * 10.23)
local lowb, highb = get2bytes_signed(vel)
return busdevice[write_method](idb,0x20,string.char(lowb,highb),status_return_level)
end
end,
torque_limit = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x22,string.char(lowb,highb),status_return_level)
end,
lock = function(enable)
local parameter
if enable then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
return busdevice[write_method](idb,0x2F,parameter,status_return_level)
end,
punch = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x30,string.char(lowb,highb),status_return_level)
end
}
local last_speed
--- Rotate to the indicated angle.
-- @param angle Position in degrees in the 0-300 range.
-- @param speed optional rotational speed, in deg/sec in the 1 .. 684 range.
-- Defaults to max unregulated speed.
Motor.rotate_to_angle = function (angle, speed)
if motor_mode ~= 'joint' then
control_setters.rotation_mode('joint')
end
if speed ~= last_speed then
control_setters.moving_speed(speed or 0)
end
return control_setters.goal_position(angle)
end
--- Spin at the indicated torque.
-- @param power % of max torque, in the -100% .. 100% range.
Motor.spin = function (power)
if motor_mode ~= 'joint' then
control_setters.rotation_mode('wheel')
end
return control_setters.moving_speed(power)
end
Motor.set = control_setters
--- Name of the device.
-- Of the form _'ax12:5'_, _ax:all_ for a broadcast motor, or ax:sync (sync motor set).
--- Module name (_'ax'_, ax-all or _'ax-sync'_ in this case)
-- _'ax'_ is for actuators, _'ax-sync'_ is for sync-motor objects
if motor_type=='sync' then
--initialize local state
status_return_level = 0
Motor.module = 'ax-sync'
Motor.name = 'ax-sync:'..tostring(math.random(2^30))
elseif motor_type=='broadcast' then
--initialize local state
status_return_level = 0
Motor.module = 'ax-all'
Motor.name = 'ax:all'
elseif motor_type=='single' then
Motor.get = control_getters
--initialize local state
_, _ = control_getters.status_return_level()
_, _ = control_getters.rotation_mode()
Motor.module = 'ax'
Motor.name = 'ax'..((control_getters.model_number()) or '??')..':'..motor_id
end
log('AXMOTOR', 'INFO', 'device object created: %s', Motor.name)
--toribio.add_device(busdevice)
return Motor
end
return M
--- Atribute getters.
-- Functions used to get values from the Dynamixel control table. These functions
-- are not available for broadcast nor sync motors.
-- @section getters
--- Get the dynamixel model number.
-- For an AX-12 this will return 12.
-- @function get.model_number
-- @return a model number, followed by a dynamixel error code.
--- Get the version of the actuator's firmware.
-- For an AX-12 this will return 12.
-- @function get.firmware_version
-- @return a version number, followed by a dynamixel error code.
--- Get the ID number of the actuator.
-- @function get.id
-- @return a ID number, followed by a dynamixel error code.
--- Get the baud rate.
-- @function get.baud_rate
-- @return a serial bus speed in bps, followed by a dynamixel error code.
--- Get the response delay.
-- The time in secs an actuator waits before answering a call.
-- @function get.return_delay_time
-- @return the edlay time in secs, followed by a dynamixel error code.
--- Get the rotation mode.
-- Wheel mode is equivalent to having limits cw=0, ccw=0, and mode joint is equivalent to cw=0, ccw=300
-- @function get.rotation_mode
-- @return Either 'wheel' or 'joint', followed by a dynamixel error code.
--- Get the angle limit.
-- The extreme positions possible for the Joint mode.
-- @function get.angle_limit
-- @return the cw limit, then the ccw limit, followed by a dynamixel error code.
--- Get the temperature limit.
-- @function get.limit_temperature
-- @return The maximum allowed temperature in degrees Celsius, followed by a dynamixel error code.
--- Get the voltage limit.
-- @function get.limit_voltage
-- @return The minumum and maximum allowed voltage in Volts, followed by a dynamixel error code.
--- Get the torque limit.
-- This is also the default value for `torque_limit`.
-- @function get.max_torque
-- @return the maximum producible torque, as percentage of maximum possible (in the 0% - 100% range),
-- followed by a dynamixel error code.
--- Get the Return Level.
-- Control what commands must generate a status response
-- from the actuator. Possible values are 'ONLY\_PING', 'ONLY\_READ' and 'ALL' (default)
-- @function get.status_return_level
-- @return the return level, followed by a dynamixel error code.
--- Get the LED alarm setup.
-- A list of error conditions that cause the LED to blink.
-- @function get.alarm_led
-- @return A double indexed set, by entry number and error code, followed by a dynamixel error code. The possible
-- error codes in the list are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- 'ERROR\_RANGE', 'ERROR\_CHECKSUM', 'ERROR\_OVERLOAD' and 'ERROR\_INSTRUCTION'.
--- Get the alarm shutdown setup.
-- A list of error conditions that cause the `torque_limit` attribute to
-- be set to 0, halting the motor.
-- @function get.alarm_shutodown
-- @return A double indexed set, by entry number and error code, followed by a dynamixel error code. The possible
-- error codes in the list are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- 'ERROR\_RANGE', 'ERROR\_CHECKSUM', 'ERROR\_OVERLOAD' and 'ERROR\_INSTRUCTION'.
--- Get the Torque Enable status.
-- Control the power supply to the motor.
-- @function get.torque_enable
-- @return Boolean
--- Get the Compliance Margin.
-- See Dynamiel reference.
-- @function get.compliance_margin
-- @return cw margin, ccw margin (both in degrees), followed by a Dynamiel error code.
--- Get the Compliance Slope.
-- See Dynamiel reference.
-- @function get.compliance_slope
-- @return the step value, followed by a Dynamiel error code.
--- Get the Punch value.
-- See Dynamiel reference.
-- @function get.punch
-- @return punch as % of max torque (in the 0..100 range)
--- Get the goal angle.
-- The target position for the actuator is going to. Only works in joint mode.
-- @function get.goal_position
-- @return the target angle in degrees, followed by a Dynamiel error code.
--- Get rotation speed.
-- @function get.moving_speed
-- @return If motor in joint mode, speed in deg/sec (0 means max unregulated speed), if in wheel
-- mode, as a % of max torque, followed by a Dynamiel error code.
--- Get the torque limit.
-- Controls the 'ERROR\_OVERLOAD' error triggering.
-- @function get.torque_limit
-- @return The torque limit as percentage of maximum possible.
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range)
-- , followed by a Dynamiel error code.
--- Get the axle position.
-- @function get.present_position
-- @return The current position of the motor axle, in degrees (only valid in the
-- 0 .. 300 range), followed by a Dynamiel error code.
--- Get the actual rotation speed.
-- Only valid in the 0..300 deg position.
-- @function get.present_speed
-- @return If motor in joint mode, speed in deg/sec, if in wheel
-- mode, as a % of max torque, followed by a Dynamiel error code.
--- Get the motor load.
-- Only valid in the 0..300 deg position, and aproximate.
-- @function get.present_load
-- @return Percentage of max torque (positive is clockwise, negative is
-- counterclockwise), followed by a Dynamiel error code.
--- Get the supplied voltage.
-- @function get.present_voltage
-- @return The supplied voltage in Volts, followed by a Dynamiel error code.
--- Get the internal temperature.
-- @function get.present_temperature
-- @return The Internal temperature in degrees Celsius, followed by a Dynamiel error code.
--- Get registered commands status.
-- Wether there are registerd commands (see @{reg_write_start} and @{reg_write_action})
-- @function get.registered
-- @return A boolean, followed by a Dynamiel error code.
--- Get the moving status.
-- Wether the motor has reached @{get.goal_position}.
-- @function get.present_temperature
-- @return A boolean, followed by a Dynamiel error code.
--- Get the lock status.
-- Whether the EEPROM (persistent) attributes are blocked for writing.
-- @function get.lock
-- @return boolean, followed by a Dynamiel error code.
--- Atribute setters.
-- Functions used to set values for the Dynamixel control table.
-- Some of the setable parameters set are located on the motors EEPROM (marked "persist"),
-- and others are on RAM (marked "volatile"). The attributes stored in RAM are reset when the
-- motor is powered down.
-- @section setters
--- Set the ID number of the actuator (persist).
--- @function set.id
-- @param ID number, must be in the 0 .. 253 range.
-- @return A dynamixel error code.
--- Set the baud rate (persist).
-- @function set.baud_rate
-- @param bps bus rate in bps, in the 9600 to 1000000 range. Check the Dynamixel docs for supported values.
-- @return A dynamixel error code.
--- Set the response delay (persist).
-- The time in secs an actuator waits before answering a call.
-- @function set.return_delay_time
-- @param sec a time in sec.
-- @return A dynamixel error code.
--- Set the rotation mode (persist).
-- Wheel mode is for continuous rotation, Joint is for servo. Setting this attribute resets the
-- `angle_limit` parameter. Wheel mode is equivalent to having limits cw=0, ccw=0, and mode joint is equivalent to cw=0, ccw=300
-- @function set.rotation_mode
-- @param mode Either 'wheel' or 'joint'.
-- @return A dynamixel error code.
--- Set the angle limit (persist).
-- The extreme positions possible for the Joint mode. The angles are given in degrees, and must be in the 0<=cw<=ccw<=300 range.
-- @function set.angle_limit
-- @param cw the clockwise limit.
-- @param ccw the clockwise limit.
-- @return A dynamixel error code.
--- Set the temperature limit (persist).
-- @function set.limit_temperature
-- @param deg the temperature in degrees Celsius.
-- @return A dynamixel error code.
--- Set the voltage limit (persist).
-- @function set.limit_voltage
-- @param min the minimum allowed voltage in Volts.
-- @param max the maximum allowed voltage in Volts.
-- @return A dynamixel error code.
--- Set the torque limit (persist).
-- This is also the default value for `torque_limit`.
-- @function set.max_torque
-- @param torque the maximum producible torque, as percentage of maximum possible (in the 0% - 100% range)
-- @return A dynamixel error code.
--- Set the Return Level (persist).
-- Control what commands must generate a status response
-- from the actuator.
-- @function set.status_return_level
-- @param return_level Possible values are 'ONLY\_PING', 'ONLY\_READ' and 'ALL' (default)
-- @return A dynamixel error code.
--- Set LED alarm (persist).
-- A list of error conditions that cause the LED to blink.
-- @function set.alarm_led
-- @param errors A list of error codes. The possible
-- error codes are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- @return A dynamixel error code.
--- Set alarm shutdown (persist).
-- A list of error conditions that cause the `torque_limit` attribute to
-- be set to 0, halting the motor.
-- @function set.alarm_shutodown
-- @param errors A list of error codes. The possible
-- error codes are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- @return A dynamixel error code.
--- Set the Torque Enable status (volatile).
-- Control the power supply to the motor.
-- @function set.torque_enable
-- @param status Boolean
-- @return A dynamixel error code.
--- Set the Compliance Margin (volatile).
-- See Dynamiel reference.
-- @function set.compliance_margin
-- @param cw clockwise margin, in deg.
-- @param ccw counterclockwise margin, in deg.
-- @return A dynamixel error code.
--- Set the Compliance Slope (volatile).
-- See Dynamiel reference.
-- @function set.compliance_slope
-- @param step the step value.
-- @return A dynamixel error code.
--- Set the Punch value (volatile).
-- See Dynamiel reference.
-- @function set.punch
-- @param punch as % of max torque (in the 0..100 range)
-- @return A dynamixel error code.
--- Set the goal angle (volatile).
-- The target position for the actuator to go, in degrees. Only works in joint mode.
-- @function set.goal_position
-- @param angle the target angle in degrees
-- @return A dynamixel error code.
--- Set the rotation speed (volatile).
-- @function set.moving_speed
-- @param speed If motor in joint mode, speed in deg/sec in the 0 .. 684 range
-- (0 means max unregulated speed).
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range).
-- @return A dynamixel error code.
--- Set the torque limit (volatile).
-- Controls the 'ERROR\_OVERLOAD' error triggering.
-- @function set.torque_limit
-- @param torque The torque limit as percentage of maximum possible.
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range).
-- @return A dynamixel error code.
--- Set the lock status (volatile).
-- @function set.lock
-- @param lock once set to true, can be unlocked only powering down the motor.
-- @return A dynamixel error code.
| 34.788945 | 129 | 0.710711 | 3.28125 |
0ba8bac551a05bebe5ab8cdbe7162fe74234100b
| 1,019 |
py
|
Python
|
1306_Jump_Game_III.py
|
imguozr/LC-Solutions
|
5e5e7098d2310c972314c9c9895aafd048047fe6
|
[
"WTFPL"
] | null | null | null |
1306_Jump_Game_III.py
|
imguozr/LC-Solutions
|
5e5e7098d2310c972314c9c9895aafd048047fe6
|
[
"WTFPL"
] | null | null | null |
1306_Jump_Game_III.py
|
imguozr/LC-Solutions
|
5e5e7098d2310c972314c9c9895aafd048047fe6
|
[
"WTFPL"
] | null | null | null |
from typing import List
class Solution:
"""
BFS
"""
def canReach_1(self, arr: List[int], start: int) -> bool:
"""
Recursively.
"""
seen = set()
def helper(pos):
if not 0 <= pos < len(arr) or pos in seen:
return False
if not arr[pos]:
return True
seen.add(pos)
return helper(pos + arr[pos]) or helper(pos - arr[pos])
return helper(start)
def canReach_2(self, arr: List[int], start: int) -> bool:
"""
Iteratively
"""
from collections import deque
queue, seen = deque([start]), {start}
while queue:
curr = queue.popleft()
if not arr[curr]:
return True
for nxt in [curr + arr[curr], curr - arr[curr]]:
if 0 <= nxt < len(arr) and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return False
| 24.261905 | 67 | 0.459274 | 3.3125 |
bdae281ab6c4cc0b1f1376f241baa06cc6a92587
| 1,413 |
rs
|
Rust
|
src/udp/packet.rs
|
akitsu-sanae/microps-rs
|
e217d2110e402a8a49909f08ea26725e2a9350cf
|
[
"MIT"
] | 4 |
2020-01-13T01:43:45.000Z
|
2022-03-06T09:16:34.000Z
|
src/udp/packet.rs
|
akitsu-sanae/microps-rs
|
e217d2110e402a8a49909f08ea26725e2a9350cf
|
[
"MIT"
] | null | null | null |
src/udp/packet.rs
|
akitsu-sanae/microps-rs
|
e217d2110e402a8a49909f08ea26725e2a9350cf
|
[
"MIT"
] | 1 |
2022-02-03T14:24:42.000Z
|
2022-02-03T14:24:42.000Z
|
use crate::{buffer::Buffer, packet, util};
use std::error::Error;
pub struct Packet {
pub src_port: u16,
pub dst_port: u16,
pub sum: u16,
pub payload: Buffer,
}
const HEADER_LEN: usize = 8;
impl Packet {
pub fn dump(&self) {
eprintln!("src port: {}", self.src_port);
eprintln!("dst port: {}", self.dst_port);
eprintln!("sum: {}", self.sum);
eprintln!("{}", self.payload);
}
pub fn write_checksum(buf: &mut Buffer, sum: u16) {
buf.write_u16(4, sum);
}
}
impl packet::Packet<Packet> for Packet {
fn from_buffer(mut buf: Buffer) -> Result<Self, Box<dyn Error>> {
let src_port = buf.pop_u16("src port")?;
let dst_port = buf.pop_u16("dst port")?;
let len = buf.pop_u16("len")?;
let sum = buf.pop_u16("sum")?;
if len as usize != HEADER_LEN + buf.0.len() {
return Err(util::RuntimeError::new(format!("invalid len: {}", len)));
}
Ok(Packet {
src_port: src_port,
dst_port: dst_port,
sum: sum,
payload: buf,
})
}
fn to_buffer(self) -> Buffer {
let mut buf = Buffer::empty();
buf.push_u16(self.src_port);
buf.push_u16(self.dst_port);
buf.push_u16((HEADER_LEN + self.payload.0.len()) as u16);
buf.push_u16(self.sum);
buf.append(self.payload);
buf
}
}
| 26.660377 | 81 | 0.547771 | 3 |
76ad6f9ca8d8afdc8ae8c40bab14b26d2400137e
| 2,364 |
swift
|
Swift
|
Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift
|
htaiwan/LeetCode-Solutions-in-Swift
|
df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2
|
[
"MIT"
] | null | null | null |
Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift
|
htaiwan/LeetCode-Solutions-in-Swift
|
df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2
|
[
"MIT"
] | null | null | null |
Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift
|
htaiwan/LeetCode-Solutions-in-Swift
|
df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2
|
[
"MIT"
] | 1 |
2019-06-10T18:26:47.000Z
|
2019-06-10T18:26:47.000Z
|
//
// Easy_088_Merge_Sorted_Array_Test.swift
// Solutions
//
// Created by Di Wu on 10/15/15.
// Copyright © 2015 diwu. All rights reserved.
//
import XCTest
class Easy_088_Merge_Sorted_Array_Test: XCTestCase {
private static let ProblemName: String = "Easy_088_Merge_Sorted_Array"
private static let TimeOutName = ProblemName + Default_Timeout_Suffix
private static let TimeOut = Default_Timeout_Value
func test_001() {
var input0: [Int] = [0]
let input1: [Int] = [1]
let m: Int = 0
let n: Int = 1
let expected: [Int] = [1]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
func test_002() {
var input0: [Int] = [1]
let input1: [Int] = [0]
let m: Int = 1
let n: Int = 0
let expected: [Int] = [1]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
func test_003() {
var input0: [Int] = [1, 3, 5, 7, 9, 0, 0, 0, 0, 0]
let input1: [Int] = [2, 4, 6, 8, 10]
let m: Int = 5
let n: Int = 5
let expected: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
private func asyncHelper(input0: inout [Int], input1: [Int], m: Int, n: Int, expected: [Int]) {
weak var expectation: XCTestExpectation? = self.expectation(description: Easy_088_Merge_Sorted_Array_Test.TimeOutName)
var localInput0 = input0
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in
Easy_088_Merge_Sorted_Array.merge(nums1: &localInput0, m: m, nums2: input1, n: n)
assertHelper(localInput0 == expected, problemName: Easy_088_Merge_Sorted_Array_Test.ProblemName, input: localInput0, resultValue: localInput0, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout: Easy_088_Merge_Sorted_Array_Test.TimeOut) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName: Easy_088_Merge_Sorted_Array_Test.ProblemName, input: localInput0, resultValue: Easy_088_Merge_Sorted_Array_Test.TimeOutName, expectedValue: expected)
}
}
}
}
| 42.214286 | 198 | 0.623942 | 3.078125 |
0cb5558fd712cd9664d2840e0dfa1433d69b0ae5
| 7,491 |
py
|
Python
|
CameraCalibration.py
|
lsmanoel/StereoVision
|
22e9a422a217290e6fb2b71afc663db87e530842
|
[
"MIT"
] | null | null | null |
CameraCalibration.py
|
lsmanoel/StereoVision
|
22e9a422a217290e6fb2b71afc663db87e530842
|
[
"MIT"
] | null | null | null |
CameraCalibration.py
|
lsmanoel/StereoVision
|
22e9a422a217290e6fb2b71afc663db87e530842
|
[
"MIT"
] | null | null | null |
import numpy as np
import cv2
import glob
from matplotlib import pyplot as plt
class CameraCalibration():
def __init__(self):
pass
# ===========================================================
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def find_chess(frame_input, chess_size=(6, 6)):
status = None
print("chess...")
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((chess_size[0]*chess_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:chess_size[0], 0:chess_size[1]].T.reshape(-1, 2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(frame_gray, (chess_size[0], chess_size[1]), None)
# If found, add object points, image points (after refining them)
frame_output = None
if ret == True:
status = "checkmate!"
print(status)
objpoints.append(objp)
corners2 = cv2.cornerSubPix(frame_gray,
corners,
(11, 11),
(-1, -1),
criteria)
imgpoints.append(corners2)
# Draw and display the corners
frame_output = cv2.drawChessboardCorners(frame_input, (chess_size[0], chess_size[1]), corners2, ret)
plt.imshow(frame_output)
plt.show()
if frame_output is None:
frame_output = frame_input
return frame_output, objpoints, imgpoints, status
# ===========================================================
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def calibrateCoefficients(frame_input, objpoints, imgpoints):
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints,
imgpoints,
frame_input.shape[::-1],
None,
None)
tot_error = 0
mean_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
tot_error += error
print("total error: ", mean_error/len(objpoints))
return ret, mtx, dist, rvecs, tvecs
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def testbench(video_source=2):
capture = cv2.VideoCapture(video_source)
count_frame = 0
while 1:
# ++++++++++++++++++++++++++++++++++++++++++++++++
print('calibrate state...')
status = None
while status is None:
status = None
ret, frame_input = capture.read()
print(count_frame)
count_frame += 1
frame_chess, objpoints, imgpoints, status = CameraCalibration.find_chess(frame_input)
plt.imshow(frame_chess)
plt.show()
# ++++++++++++++++++++++++++++++++++++++++++++++++
frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY)
plt.imshow(frame_gray)
plt.show()
ret, mtx, dist, rvecs, tvecs = CameraCalibration.calibrateCoefficients(frame_gray, objpoints, imgpoints)
h, w = frame_gray.shape[:2]
newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
# ++++++++++++++++++++++++++++++++++++++++++++++++
print('test state...')
while 1:
ret, frame_input = capture.read()
frame_gray = cv2.cvtColor(frame_input,cv2.COLOR_BGR2GRAY)
h, w = frame_gray.shape[:2]
newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
frame_undist = cv2.undistort(frame_input, mtx, dist, None, newcameramtx)
x,y,w,h = roi
print(x,y,w,h)
# frame_undist = frame_undist[y:y+h, x:x+w]
frame_concat = np.concatenate((frame_undist, frame_input), axis=1)
plt.imshow(frame_concat)
plt.show()
# ----------------------------------------------------------
# Esc -> EXIT while
# while 1:
# k = cv2.waitKey(1) & 0xff
# if k ==13 or k==27:
# break
# if k == 27:
# break
# ----------------------------------------------------------
capture.release()
cv2.destroyAllWindows()
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def getPhoto(video_source=0):
capture = cv2.VideoCapture(video_source)
while 1:
ret, frame_input = capture.read()
frame_line = frame_input
frame_output = cv2.line(frame_line,
(0, frame_line.shape[0]//2),
(frame_line.shape[1], frame_line.shape[0]//2),
(255,0,0),
1)
frame_output = cv2.line(frame_line,
(frame_line.shape[1]//2, 0),
(frame_line.shape[1]//2, frame_line.shape[0]),
(255,0,0),
1)
cv2.imshow("Video", frame_line)
# ------------------------------------------------------------------------------------------------------------------
# Esc -> EXIT while
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# ------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
ret, frame_input = capture.read()
frame_input = cv2.cvtColor(frame_input, cv2.COLOR_BGR2RGB)
plt.imshow(frame_input)
plt.xticks([])
plt.yticks([])
plt.show()
# ----------------------------------------------------------------------------------------------------------------------
capture.release()
cv2.destroyAllWindows()
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# CameraCalibration.testbench(video_source=2)
| 39.015625 | 128 | 0.394206 | 3.203125 |
c3a7c86be06eaa6d4287fd7885743754fe92afb9
| 4,217 |
swift
|
Swift
|
Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift
|
dpassage/advent2018
|
c22d892a37b532667e5c50a4e16b49c70e38ad51
|
[
"BSD-2-Clause"
] | null | null | null |
Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift
|
dpassage/advent2018
|
c22d892a37b532667e5c50a4e16b49c70e38ad51
|
[
"BSD-2-Clause"
] | null | null | null |
Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift
|
dpassage/advent2018
|
c22d892a37b532667e5c50a4e16b49c70e38ad51
|
[
"BSD-2-Clause"
] | null | null | null |
//: [Previous](@previous)
import Foundation
import AdventLib
let testInput = """
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
""".components(separatedBy: "\n")
struct Sleep {
var start: Int
var end: Int
var length: Int { return end - start }
}
struct Guard {
var sleeps: [Sleep] = []
mutating func startSleeping(at: Int) {
let newSleep = Sleep(start: at, end: Int.max)
sleeps.append(newSleep)
}
mutating func stopSleeping(at: Int) {
sleeps[sleeps.count - 1].end = at
}
var totalSleeps: Int { return sleeps.reduce(0, { return $0 + $1.length }) }
func sleepiestMinute() -> (minute: Int, sleeps: Int) {
var minutes: [Int: Int] = [:]
for sleep in sleeps {
for minute in sleep.start ..< sleep.end {
minutes[minute, default: 0] += 1
}
}
let keyValue = minutes.sorted { $0.value > $1.value }.first!
return (minute: keyValue.key, sleeps: keyValue.value)
}
}
struct GuardSet {
var guards: [Int: Guard] = [:]
subscript(id: Int) -> Guard {
get { return guards[id] ?? Guard() }
set { guards[id] = newValue }
}
init(lines: [Line]) {
var currentGuard = -1
for line in lines {
switch line {
case let .newGuard(id: id): currentGuard = id
case let .startSleep(at: minute): guards[currentGuard, default: Guard()].startSleeping(at: minute)
case let .endSleep(at: minute): guards[currentGuard, default: Guard()].stopSleeping(at: minute)
}
}
}
}
enum Line {
case newGuard(id: Int)
case startSleep(at: Int)
case endSleep(at: Int)
private static let newGuardRegex = try! Regex(pattern: ".* Guard #(\\d+) begins shift")
private static let startSleepRegex = try! Regex(pattern: "\\[.*:(\\d\\d)] falls asleep")
private static let endSleepRegex = try! Regex(pattern: "\\[.*:(\\d\\d)] wakes up")
init?(text: String) {
if let matches = Line.newGuardRegex.match(input: text),
let id = Int(matches[0]) {
self = .newGuard(id: id)
} else if let matches = Line.startSleepRegex.match(input: text),
let minute = Int(matches[0]) {
self = .startSleep(at: minute)
} else if let matches = Line.endSleepRegex.match(input: text),
let minute = Int(matches[0]) {
self = .endSleep(at: minute)
} else {
return nil
}
}
}
let testLines = testInput.compactMap { Line(text: $0) }
print(testLines)
func strategyOne(lines: [Line]) -> Int {
let guardSet = GuardSet(lines: lines)
let sleepiestGuard = guardSet.guards.sorted { $0.value.totalSleeps > $1.value.totalSleeps }.first!
let sleepiestGuardId = sleepiestGuard.key
let sleepiestMinute = sleepiestGuard.value.sleepiestMinute()
return sleepiestGuardId * sleepiestMinute.minute
}
print(strategyOne(lines: testLines))
let url = Bundle.main.url(forResource: "day4.input", withExtension: "txt")!
let day4Input = try! String(contentsOf: url).components(separatedBy: "\n").sorted()
let day4Lines = day4Input.compactMap { Line(text: $0) }
print(strategyOne(lines: day4Lines))
func strategyTwo(lines: [Line]) -> Int {
let guardSet = GuardSet(lines: lines)
let guardSleepiestMinutes = guardSet.guards.mapValues { $0.sleepiestMinute() }
let guardWithSleepiestMinute = guardSleepiestMinutes.sorted { $0.value.sleeps > $1.value.sleeps }.first!
return guardWithSleepiestMinute.key * guardWithSleepiestMinute.value.minute
}
print(strategyTwo(lines: testLines))
print(strategyTwo(lines: day4Lines))
//: [Next](@next)
| 29.907801 | 110 | 0.631729 | 3.09375 |
97483d9a31b41331fa6d66095899aa2924c3a154
| 3,348 |
swift
|
Swift
|
PeertalkSimple/PTSimpleiOS/SimpleViewController.swift
|
kokluch/peertalk-simple
|
fa9ba809ae218a95d9378b3d54a2bb43f21d3161
|
[
"MIT"
] | null | null | null |
PeertalkSimple/PTSimpleiOS/SimpleViewController.swift
|
kokluch/peertalk-simple
|
fa9ba809ae218a95d9378b3d54a2bb43f21d3161
|
[
"MIT"
] | null | null | null |
PeertalkSimple/PTSimpleiOS/SimpleViewController.swift
|
kokluch/peertalk-simple
|
fa9ba809ae218a95d9378b3d54a2bb43f21d3161
|
[
"MIT"
] | null | null | null |
import PeertalkManager
import UIKit
class SimpleViewController: UIViewController {
// Outlets
@IBOutlet var label: UILabel!
@IBOutlet var addButton: UIButton!
@IBOutlet var imageButton: UIButton!
@IBOutlet var imageView: UIImageView!
@IBOutlet var statusLabel: UILabel!
// Properties
let ptManager = PTManager.shared
let imagePicker = UIImagePickerController()
// UI Setup
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
addButton.layer.cornerRadius = addButton.frame.height / 2
imageButton.layer.cornerRadius = imageButton.frame.height / 2
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup the PTManager
ptManager.delegate = self
ptManager.connect(portNumber: PORT_NUMBER)
// Setup imagge picker
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
}
@IBAction func addButtonTapped(_: UIButton) {
if ptManager.isConnected {
var num = Int(label.text!)! + 1
label.text = "\(num)"
let data = Data(bytes: &num, count: MemoryLayout<Int>.size)
ptManager.send(data: data, type: PTType.number.rawValue)
} else {
showAlert()
}
}
@IBAction func imageButtonTapped(_: UIButton) {
if ptManager.isConnected {
present(imagePicker, animated: true, completion: nil)
} else {
showAlert()
}
}
func showAlert() {
let alert = UIAlertController(title: "Disconnected", message: "Please connect to a device first", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
extension SimpleViewController: PTManagerDelegate {
func peertalk(shouldAcceptDataOfType _: UInt32) -> Bool {
return true
}
func peertalk(didReceiveData data: Data?, ofType type: UInt32) {
guard let data = data else { return }
if type == PTType.number.rawValue {
let count = data.withUnsafeBytes { $0.load(as: Int.self) }
label.text = "\(count)"
} else if type == PTType.image.rawValue {
let image = UIImage(data: data)
imageView.image = image
}
}
func peertalk(didChangeConnection connected: Bool) {
print("Connection: \(connected)")
statusLabel.text = connected ? "Connected" : "Disconnected"
}
}
extension SimpleViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
DispatchQueue.global(qos: .background).async {
let data = UIImageJPEGRepresentation(image, 1.0)!
self.ptManager.send(data: data, type: PTType.image.rawValue, completion: nil)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
| 32.823529 | 151 | 0.651135 | 3.171875 |
de1197048195c1836a9c1fef3880fe926efd02f2
| 1,599 |
rs
|
Rust
|
parsemath/src/parsemath/tokenizer.rs
|
ValeryPiashchynski/rust_playground
|
24b471710f1ccd191c91ba5d41450a426e3974c8
|
[
"MIT"
] | null | null | null |
parsemath/src/parsemath/tokenizer.rs
|
ValeryPiashchynski/rust_playground
|
24b471710f1ccd191c91ba5d41450a426e3974c8
|
[
"MIT"
] | 1 |
2020-12-06T20:53:50.000Z
|
2020-12-13T16:31:07.000Z
|
parsemath/src/parsemath/tokenizer.rs
|
rustatian/rust_playground
|
6168d9caf1bbfbf3cfebf907a633ddd8f2886056
|
[
"MIT"
] | null | null | null |
use crate::parsemath::token::Token;
use std::iter::Peekable;
use std::str::Chars;
pub struct Tokenizer<'a> {
// peekable iterator over the string
expr: Peekable<Chars<'a>>,
}
impl<'a> Tokenizer<'a> {
// creates a new tokenizer using the arithmetic expression provided by the user
pub fn new(new_expr: &'a str) -> Self {
Tokenizer {
expr: new_expr.chars().peekable(),
}
}
}
impl<'a> Iterator for Tokenizer<'a> {
type Item = Token;
fn next(&mut self) -> Option<Token> {
let next_char = self.expr.next();
match next_char {
Some('0'..='9') => {
let mut number = next_char?.to_string();
while let Some(next_char) = self.expr.peek() {
if next_char.is_numeric() || next_char == &'.' {
number.push(self.expr.next()?);
} else if next_char == &'(' {
return None;
} else {
break;
}
}
Some(Token::Num(number.parse::<f64>().unwrap()))
}
Some('+') => Some(Token::Add),
Some('-') => Some(Token::Subtract),
Some('*') => Some(Token::Multiply),
Some('/') => Some(Token::Divide),
Some('^') => Some(Token::Caret),
Some('(') => Some(Token::LeftParen),
Some(')') => Some(Token::RightParen),
None => Some(Token::EOF),
Some('_') => None,
_ => panic!("unknown token"),
}
}
}
| 30.75 | 83 | 0.459037 | 3.09375 |
ad0d325c40ce3de59da2bed4b487fdfbb807a0d1
| 5,327 |
rs
|
Rust
|
examples/vendored/complicated_cargo_library/cargo/vendor/syn-0.11.11/src/constant.rs
|
tommilligan/cargo-raze
|
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
|
[
"Apache-2.0"
] | 5 |
2019-12-04T11:29:04.000Z
|
2021-11-18T14:23:55.000Z
|
examples/vendored/complicated_cargo_library/cargo/vendor/syn-0.11.11/src/constant.rs
|
tommilligan/cargo-raze
|
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
|
[
"Apache-2.0"
] | 6 |
2017-09-13T00:53:42.000Z
|
2019-05-01T01:00:52.000Z
|
examples/vendored/complicated_cargo_library/cargo/vendor/syn-0.11.11/src/constant.rs
|
tommilligan/cargo-raze
|
b20c29f8f6a0902a7aadf5424dd830cd045ac92d
|
[
"Apache-2.0"
] | 18 |
2019-07-15T23:10:12.000Z
|
2021-07-26T02:28:55.000Z
|
use super::*;
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum ConstExpr {
/// A function call
///
/// The first field resolves to the function itself,
/// and the second field is the list of arguments
Call(Box<ConstExpr>, Vec<ConstExpr>),
/// A binary operation (For example: `a + b`, `a * b`)
Binary(BinOp, Box<ConstExpr>, Box<ConstExpr>),
/// A unary operation (For example: `!x`, `*x`)
Unary(UnOp, Box<ConstExpr>),
/// A literal (For example: `1`, `"foo"`)
Lit(Lit),
/// A cast (`foo as f64`)
Cast(Box<ConstExpr>, Box<Ty>),
/// Variable reference, possibly containing `::` and/or type
/// parameters, e.g. foo::bar::<baz>.
Path(Path),
/// An indexing operation (`foo[2]`)
Index(Box<ConstExpr>, Box<ConstExpr>),
/// No-op: used solely so we can pretty-print faithfully
Paren(Box<ConstExpr>),
/// If compiling with full support for expression syntax, any expression is
/// allowed
Other(Other),
}
#[cfg(not(feature = "full"))]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Other {
_private: (),
}
#[cfg(feature = "full")]
pub type Other = Expr;
#[cfg(feature = "parsing")]
pub mod parsing {
use super::*;
use {BinOp, Ty};
use lit::parsing::lit;
use op::parsing::{binop, unop};
use ty::parsing::{path, ty};
named!(pub const_expr -> ConstExpr, do_parse!(
mut e: alt!(
expr_unary
|
expr_lit
|
expr_path
|
expr_paren
// Cannot handle ConstExpr::Other here because for example
// `[u32; n!()]` would end up successfully parsing `n` as
// ConstExpr::Path and then fail to parse `!()`. Instead, callers
// are required to handle Other. See ty::parsing::array_len and
// data::parsing::discriminant.
) >>
many0!(alt!(
tap!(args: and_call => {
e = ConstExpr::Call(Box::new(e), args);
})
|
tap!(more: and_binary => {
let (op, other) = more;
e = ConstExpr::Binary(op, Box::new(e), Box::new(other));
})
|
tap!(ty: and_cast => {
e = ConstExpr::Cast(Box::new(e), Box::new(ty));
})
|
tap!(i: and_index => {
e = ConstExpr::Index(Box::new(e), Box::new(i));
})
)) >>
(e)
));
named!(and_call -> Vec<ConstExpr>, do_parse!(
punct!("(") >>
args: terminated_list!(punct!(","), const_expr) >>
punct!(")") >>
(args)
));
named!(and_binary -> (BinOp, ConstExpr), tuple!(binop, const_expr));
named!(expr_unary -> ConstExpr, do_parse!(
operator: unop >>
operand: const_expr >>
(ConstExpr::Unary(operator, Box::new(operand)))
));
named!(expr_lit -> ConstExpr, map!(lit, ConstExpr::Lit));
named!(expr_path -> ConstExpr, map!(path, ConstExpr::Path));
named!(and_index -> ConstExpr, delimited!(punct!("["), const_expr, punct!("]")));
named!(expr_paren -> ConstExpr, do_parse!(
punct!("(") >>
e: const_expr >>
punct!(")") >>
(ConstExpr::Paren(Box::new(e)))
));
named!(and_cast -> Ty, do_parse!(
keyword!("as") >>
ty: ty >>
(ty)
));
}
#[cfg(feature = "printing")]
mod printing {
use super::*;
use quote::{Tokens, ToTokens};
impl ToTokens for ConstExpr {
fn to_tokens(&self, tokens: &mut Tokens) {
match *self {
ConstExpr::Call(ref func, ref args) => {
func.to_tokens(tokens);
tokens.append("(");
tokens.append_separated(args, ",");
tokens.append(")");
}
ConstExpr::Binary(op, ref left, ref right) => {
left.to_tokens(tokens);
op.to_tokens(tokens);
right.to_tokens(tokens);
}
ConstExpr::Unary(op, ref expr) => {
op.to_tokens(tokens);
expr.to_tokens(tokens);
}
ConstExpr::Lit(ref lit) => lit.to_tokens(tokens),
ConstExpr::Cast(ref expr, ref ty) => {
expr.to_tokens(tokens);
tokens.append("as");
ty.to_tokens(tokens);
}
ConstExpr::Path(ref path) => path.to_tokens(tokens),
ConstExpr::Index(ref expr, ref index) => {
expr.to_tokens(tokens);
tokens.append("[");
index.to_tokens(tokens);
tokens.append("]");
}
ConstExpr::Paren(ref expr) => {
tokens.append("(");
expr.to_tokens(tokens);
tokens.append(")");
}
ConstExpr::Other(ref other) => {
other.to_tokens(tokens);
}
}
}
}
#[cfg(not(feature = "full"))]
impl ToTokens for Other {
fn to_tokens(&self, _tokens: &mut Tokens) {
unreachable!()
}
}
}
| 29.430939 | 85 | 0.479632 | 3.109375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.