file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
app_2_wl.py | import streamlit as st
# Base packages
import pandas as pd
import numpy as np
import datetime
import altair as alt
import matplotlib.pyplot as plt
# Find coordinates
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="myapp2")
import time
# Plot static maps
import cartopy.crs as c... | ['Ville'] == x]['Latitude'])
except TypeError:
return None
def find_long(x):
try:
return float(cities[cities['Ville'] == x]['Longitude'])
except TypeError:
return None
summary = df[['Positif', 'Ville']].groupby("Ville").sum().reset_index()
summary['latitude'] = summary['... | s[cities | identifier_name |
app_2_wl.py | import streamlit as st
# Base packages
import pandas as pd
import numpy as np
import datetime
import altair as alt
import matplotlib.pyplot as plt
# Find coordinates
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="myapp2")
import time
# Plot static maps
import cartopy.crs as c... | lle").sum().reset_index()
summary['latitude'] = summary['Ville'].apply(lambda x: find_lat(x))
summary['longitude'] = summary['Ville'].apply(lambda x: find_long(x))
geosource = GeoJSONDataSource(geojson = grid)
pointsource = ColumnDataSource(summary)
hover = HoverTool(
tooltips = [('Ville', '@Ville'), ('Li... | == x]['Longitude'])
except TypeError:
return None
summary = df[['Positif', 'Ville']].groupby("Vi | identifier_body |
PerformanceTester.py | import numpy
import subprocess
import sys
import os.path
from PerformanceTesterJob import Job, printc, run
import types
from tabulate081 import tabulate
enable_scipy = True
try:
from scipy import stats
except:
enable_scipy = False
enable_plotting = True
try:
import matplotlib as mpl
mpl.use('Agg')
import matplotl... |
def GenerateJobs(self):
utc = set()
for exec in self.executable:
for x in self.cx:
for y in self.cy:
for z in self.cz:
utc.add(numpy.prod([x,y,z]))
for iteration in self.iterations:
if numpy.prod([x,y,z]) > iteration[0] and numpy.prod([x,y,z]) <= iteration[1]:
for d in sel... | self.iterations.append([cpu_from, cpu_to, iterations]) | identifier_body |
PerformanceTester.py | import numpy
import subprocess
import sys
import os.path
from PerformanceTesterJob import Job, printc, run
import types
from tabulate081 import tabulate
enable_scipy = True
try:
from scipy import stats
except:
enable_scipy = False
enable_plotting = True
try:
import matplotlib as mpl
mpl.use('Agg')
import matplotl... |
self.Jobs.sort()
self.uniq_total_cpus = list(utc)
self.uniq_total_cpus.sort()
def MakeSubmits(self):
for J in self.Jobs:
J.MakeSubmit(self.template)
print('Prepared submit for job', J.job_name)
def MakeGroupSubmits(self):
utc = set()
for J in self.Jobs:
utc.add(J.total_cpu)
utc = list(utc)
... | if numpy.prod([x,y,z]) > iteration[0] and numpy.prod([x,y,z]) <= iteration[1]:
for d in self.domains:
self.Jobs.append(Job(d, [x,y,z], iteration[2], output_suffix=self.output_suffix, executable=exec, job_exec=exec.replace("./","").replace(".out",""))) | conditional_block |
PerformanceTester.py | import numpy
import subprocess
import sys
import os.path
from PerformanceTesterJob import Job, printc, run
import types
from tabulate081 import tabulate
enable_scipy = True
try:
from scipy import stats
except:
enable_scipy = False
enable_plotting = True
try:
import matplotlib as mpl
mpl.use('Agg')
import matplotl... | (self):
for J in self.Jobs:
J.MakeSubmit(self.template)
print('Prepared submit for job', J.job_name)
def MakeGroupSubmits(self):
utc = set()
for J in self.Jobs:
utc.add(J.total_cpu)
utc = list(utc)
utc.sort()
print(utc)
for tc in utc:
first = True
for J in self.Jobs:
if J.total_cpu =... | MakeSubmits | identifier_name |
PerformanceTester.py | import numpy
import subprocess
import sys
import os.path
from PerformanceTesterJob import Job, printc, run
import types
from tabulate081 import tabulate
enable_scipy = True
try:
from scipy import stats
except:
enable_scipy = False
enable_plotting = True
try:
import matplotlib as mpl
mpl.use('Agg')
import matplotl... | utc = list(utc)
utc.sort()
# print(utc)
for tc in utc:
outfile = "E.group_{0:05d}.{1}".format(tc, self.output_suffix)
# files.add(outfile)
run('cat {0} | grep -E "^E\.|{1}" > {0}.clean'.format(outfile, self.timer), quiet=True)
files.add("{0}.clean".format(outfile))
with open("{0}.clean... | random_line_split | |
task_5.py | '''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 5 of Ni... |
elif len(cnts) == 3:
cnts = cnts[1]
if (len(cnts)):
return 'blue'
#Find red contours in the image
cnts= cv2.findContours(gray_blur_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if type(cnts[-1]) !=type(None) :
if len(cnts) == 2:
cnts = cnts[0]
elif len(cnts) == 3:
cnts = cnts[1... | cnts = cnts[0] | conditional_block |
task_5.py | '''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 5 of Ni... | (tablenum):
global map_start,map_end,maze_map,path_map,encoded_maze_t1,path_box_map
for i in range(3):
start_coord= map_start[tablenum][0]
end_coord= map_end[tablenum][i]
mazearray = maze_map[tablenum]
path = task_4a.find_path(mazearray, start_coord, end_coord)
path_box_map[tablenum].append(path)
... | complete_all_mapping_path | identifier_name |
task_5.py | '''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 5 of Ni... |
################# ADD UTILITY FUNCTIONS HERE #################
## You can define any utility functions for your code. ##
## Please add proper comments to ensure that your code is ##
## readable and easy to understand. ##
############################################################... | global client_id
color_and_cb = [ball_color + '::' + collection_box_name]
inputBuffer = bytearray()
return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id,'evaluation_screen_respondable_1',
sim.sim_scripttype_childscript,'color_and_cb_identification',[],[],color_a... | identifier_body |
task_5.py | '''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 5 of Ni... | "T4":[(0,5)],
"T3":[(4,9)],
"T2":[(0,4)],
"T1":[(5,0)]
} # do mapping of start and end point on the basis of color and json file.
map_end = {
"T4":[(5,9), (9,4), (4,0)],
"T3":[(9,5), (5,0), (0,4)],
"T2":[(4,9), (9,5), (5,0)],
"T1":[(0,4), (4,9), (9,5)]
}
t4_path = None #path to table req
aux... | print('Make sure ball_details.json is present in this current directory.\n')
map_start = {
| random_line_split |
delete.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | }
span.AddEvent("Object deleted from database")
status := http.StatusOK
// Return http.StatusAccepted if the resource was not deleted immediately and
// user requested cascading deletion by setting OrphanDependents=false.
// Note: We want to do this always if resource was not deleted immediately, but
// ... | return | random_line_split |
delete.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | {
return func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
ctx, span := tracing.Start(ctx, "Delete", traceFields(req)...)
defer span.End(500 * time.Millisecond)
namespace, err := scope.Namer.Namespace(req)
if err != nil {
scope.err(err, w, req)
return
}
// DELETECOLLECTION can... | identifier_body | |
delete.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (r rest.CollectionDeleter, checkBody bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
ctx, span := tracing.Start(ctx, "Delete", traceFields(req)...)
defer span.End(500 * time.Millisecond)
namespace, err := sco... | DeleteCollection | identifier_name |
delete.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | else {
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {
err = errors.NewBadRequest(err.Error())
scope.err(err, w, req)
return
}
}
}
if errs := validation.ValidateDeleteOptions(options); len(errs) > 0 {
e... | {
s, err := negotiation.NegotiateInputSerializer(req, false, metainternalversionscheme.Codecs)
if err != nil {
scope.err(err, w, req)
return
}
// For backwards compatibility, we need to allow existing clients to submit per group DeleteOptions
// It is also allowed to pass a body with meta.... | conditional_block |
oldDH.py | ###LIBRARIES
import networkx as nx
from networkx.readwrite import json_graph
from random import uniform,randint
import numpy
from numpy import linalg as LA
import math as Math
import json
import os
from pathlib import Path
import time
import shutil
##
start_time = time.time()
###CLEAN
folder = './html/'
for filename in... | ff=massimo-minimo
exit("diff: "+str(diff))
f= open('res.json',"w+")
f.write(json.dumps(data))
f.close()
print("--- %s seconds ---" % (time.time() - start_time))
print("fine") | simo=n['x']
di | conditional_block |
oldDH.py | ###LIBRARIES
import networkx as nx
from networkx.readwrite import json_graph
from random import uniform,randint
import numpy
from numpy import linalg as LA
import math as Math
import json
import os
from pathlib import Path
import time
import shutil
##
start_time = time.time()
###CLEAN
folder = './html/'
for filename in... |
def distance_to_line(p0, p1, p2):
x_diff = p2['x'] - p1['x']
y_diff = p2['y'] - p1['y']
num = abs(y_diff*p0['x'] - x_diff*p0['y'] + p2['x']*p1['y'] - p2['y']*p1['x'])
den = Math.sqrt(y_diff**2 + x_diff**2)
return num / den
#questa fase costa tanto 0.32 s circa con il grafo di prova di 52 nodi
# l'i... | res=0
for k in links:
#print("ciclo esterno")
for l in links:
#print("ciclo interno")
"""for m in nodes:
if(m['id']==k['source']):
sourceK=m
if(m['id']==k['target']):
targetK=m
if(m['id']=... | identifier_body |
oldDH.py | ###LIBRARIES
import networkx as nx
from networkx.readwrite import json_graph
from random import uniform,randint
import numpy
from numpy import linalg as LA
import math as Math
import json
import os
from pathlib import Path
import time
import shutil
##
start_time = time.time()
###CLEAN
folder = './html/'
for filename in... | return num / den
#questa fase costa tanto 0.32 s circa con il grafo di prova di 52 nodi
# l'ideale è somma len archi ^2 bassa (ma non troppo); somma distanze tra coppie di nodi alta (ma non troppo);
# num incroci bassa
#distanza dai bordi non rispettata, quindi posta come condizione nello spostamento lungo la circo... | num = abs(y_diff*p0['x'] - x_diff*p0['y'] + p2['x']*p1['y'] - p2['y']*p1['x'])
den = Math.sqrt(y_diff**2 + x_diff**2) | random_line_split |
oldDH.py | ###LIBRARIES
import networkx as nx
from networkx.readwrite import json_graph
from random import uniform,randint
import numpy
from numpy import linalg as LA
import math as Math
import json
import os
from pathlib import Path
import time
import shutil
##
start_time = time.time()
###CLEAN
folder = './html/'
for filename in... | nput):
return 25*input#meglio 30, ma troppo lento per grossi input
def simulatedAnnealing(data):
#exit(str(len(data['nodes'])))
#inizio con posizioni casuali dei nodes
nodes=data['nodes']
links=data['links']
valorizzato=False
if(not valorizzato):
nodes=getStartingPositions(nodes,links)... | lyn(i | identifier_name |
textContent-es.js | var textContent_ES = {
"intro": {
"paragraphs": [
"Mi nombre es Francisco pero todos me llaman Paco i me gano la vida como desarrolador de software.",
"He estado creando diversas soluciones de software para varios clientes desde 2009. Lo que más me gusta son los desafíos y resolver problemas, mejorand... | },
"planeta": {
"id": 9,
"ref": "planeta",
"slickitem":"#slick-slide00",
"company": "Grupo Planeta",
"city": "Barcelona",
"website": "https://www.planeta.es/en/learning",
"role": "Web Developer - Team Leader",
"dateStart": "Ago 2018",
"dateEnd": "Dic 2020",
... | "tasks": [],
"image": "wivi" | random_line_split |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... |
Some((name, uid)) => Some(FunctionParameter::new(
self.get_type(*uid).unwrap().1,
name.clone(),
None,
)),
_ => None,
})
.collect();
// TODO : ... | {
Some(FunctionParameter::new(Type::void(), name.clone(), None))
} | conditional_block |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... |
pub fn set_name(&mut self, die_uid: TypeUID, name: CString) {
assert!(self.names.insert(die_uid, name).is_none());
}
pub fn get_name<R: Reader<Offset = usize>>(
&self,
dwarf: &Dwarf<R>,
unit: &Unit<R>,
entry: &DebuggingInformationEntry<R>,
) -> Option<CString> ... | {
if let Some((_existing_name, existing_type_uid)) =
self.data_variables.insert(address, (name, type_uid))
{
let existing_type = self.get_type(existing_type_uid).unwrap().1;
let new_type = self.get_type(type_uid).unwrap().1;
if existing_type_uid != type_u... | identifier_body |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... | (view: &BinaryView) -> Self {
DebugInfoBuilder {
functions: vec![],
types: HashMap::new(),
data_variables: HashMap::new(),
names: HashMap::new(),
default_address_size: view.address_size(),
}
}
pub fn default_address_size(&self) -> usiz... | new | identifier_name |
dwarfdebuginfo.rs | // Copyright 2021-2023 Vector 35 Inc.
//
// 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... | raw_name: Option<CString>,
return_type: Option<TypeUID>,
address: Option<u64>,
parameters: Vec<Option<(CString, TypeUID)>>,
) {
if let Some(function) = self.functions.iter_mut().find(|func| {
(func.raw_name.is_some() && func.raw_name == raw_name)
|... | &mut self,
full_name: Option<CString>, | random_line_split |
main.go | package main
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/oxplot/papersizes"
"github.com/oxplot/pdftilecut/qpdf"
)
const (
ptsInInch = 72
mmInInch = 25.4
mmInCm = 10
bleedMargin = ptsInInch * 5 / 6 // ... |
// convertToQDF uses QPDF to convert an input PDF to a normalized
// format that is easy to parse and manipulate.
func convertToQDF(in string) (string, error) {
q, err := qpdf.New()
if err != nil {
return "", err
}
defer q.Close()
if !*debugMode {
q.SetSuppressWarnings(true)
}
if err := q.ReadFile(in); err... | {
q, err := qpdf.New()
if err != nil {
return err
}
defer q.Close()
if !*debugMode {
q.SetSuppressWarnings(true)
}
if err := q.ReadFile(in); err != nil {
return err
}
// TODO enable optimization flags
if err := q.InitFileWrite(out); err != nil {
return err
}
q.SetObjectStreamMode(qpdf.ObjectStreamGe... | identifier_body |
main.go | package main
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/oxplot/papersizes"
"github.com/oxplot/pdftilecut/qpdf"
)
const (
ptsInInch = 72
mmInInch = 25.4
mmInCm = 10
bleedMargin = ptsInInch * 5 / 6 // ... | () bool {
return r.llx <= r.urx && r.lly <= r.ury
}
type page struct {
id int
number int
tileX int
tileY int
mediaBox rect
cropBox rect
bleedBox rect
trimBox rect
contentIds []int
parentID int
raw string
}
var (
boxReTpl = `(?m)^\s+/%s\s*\[\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)\... | isValid | identifier_name |
main.go | package main
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/oxplot/papersizes"
"github.com/oxplot/pdftilecut/qpdf"
)
const (
ptsInInch = 72
mmInInch = 25.4
mmInCm = 10
bleedMargin = ptsInInch * 5 / 6 // ... |
if err := f.Close(); err != nil {
return err
}
*inputFile = f.Name()
if *tileTitle == "" {
*tileTitle = "stdin"
}
} else if *tileTitle == "" {
*tileTitle = filepath.Base(*inputFile)
}
*tileTitle = strings.ToUpper(*tileTitle)
var toStdout bool
if *outputFile == "-" {
f, err := ioutil.TempFile... | {
return err
} | conditional_block |
main.go | package main
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/oxplot/papersizes"
"github.com/oxplot/pdftilecut/qpdf"
)
const (
ptsInInch = 72
mmInInch = 25.4
mmInCm = 10
bleedMargin = ptsInInch * 5 / 6 // ... | q.SetSuppressWarnings(true)
}
if err := q.ReadFile(in); err != nil {
return "", err
}
f, err := ioutil.TempFile("", "pdftilecut-im-")
if err != nil {
return "", nil
}
f.Close()
if !*debugMode {
defer os.Remove(f.Name())
}
if err := q.InitFileWrite(f.Name()); err != nil {
return "", err
}
q.SetQDFM... | if !*debugMode { | random_line_split |
app.py | from flask import Flask,request
from flask_socketio import SocketIO
import logging
import pymysql
import json
import pygame
import threading
import json
import gspeech
import time
con = pymysql.connect(host='dementia.openlink.kr', user='admin', password='Opendb1234!@',
db='openlink', charset='... | seq = ['0 ~ 15 seconds', '16 ~ 30 seconds', '31 ~ 45 seconds', '46 ~ 60 seconds']
#print(anilist)
@socketio.on('stopwordFluency')
def stopwordFluency():
global stop
stop = True
while True:
if stop:
print('stop')
break
# 음성 인식 될때까지 대기 한다.
... | random_line_split | |
app.py | from flask import Flask,request
from flask_socketio import SocketIO
import logging
import pymysql
import json
import pygame
import threading
import json
import gspeech
import time
con = pymysql.connect(host='dementia.openlink.kr', user='admin', password='Opendb1234!@',
db='openlink', charset='... | ql = "SELECT patCd,NAME,BIRTH FROM TN_CM_TRGTER_INFO WHERE TEL_NO_1='{}' and TEL_NO_2='{}' and TEL_NO_3='{}'".format(phone[:3],phone[3:7],phone[7:])
cur.execute(sql)
# 데이타 Fetch
rows = cur.fetchone()
print(rows,request.sid)
if rows :
socketio.emit('patientJoin',True)
sql = "INSERT I... | sor)
s | identifier_body |
app.py | from flask import Flask,request
from flask_socketio import SocketIO
import logging
import pymysql
import json
import pygame
import threading
import json
import gspeech
import time
con = pymysql.connect(host='dementia.openlink.kr', user='admin', password='Opendb1234!@',
db='openlink', charset='... | Info')
cur = con.cursor(pymysql.cursors.DictCursor)
sql = "SELECT patCd,NAME,phoneNumber,BIRTH FROM TN_Scheduler"
cur.execute(sql)
# 데이타 Fetch
rows = cur.fetchall()
res = json.dumps(rows)
# 전체 rows
socketio.emit('patientInfo',res)
@socketio.on('startTest')
def startTest(index):
... | ta['id'])
cur.execute(sql)
# 데이타 Fetch
rows = cur.fetchone()
userid = rows['USER_ID']
#print(patients[data['phoneNumber']])
if rows:
socketio.emit('doctorJoin',True)
@socketio.on('patientInfo')
def getPatientInfo():
print('patient | conditional_block |
app.py | from flask import Flask,request
from flask_socketio import SocketIO
import logging
import pymysql
import json
import pygame
import threading
import json
import gspeech
import time
con = pymysql.connect(host='dementia.openlink.kr', user='admin', password='Opendb1234!@',
db='openlink', charset='... | socketio.emit('SingleWordsResult',wordsResult)
print('inc order')
order +=1
findwords.append(word.index(r))
finded.append(r)
break
for x in findwords:
word[x] = '!@'
if (not stt) or st... | identifier_name | |
GameEngine.ts | import Chance from "chance"
import { BaseGameState, BaseInput } from "shared"
import { cloneDeep, max, times } from "lodash"
export interface EngineRunHelpers {
chance: () => Chance.Chance
}
export type EngineRunFn<I extends BaseInput, G extends BaseGameState<I>> = (state: G, helpers: EngineRunHelpers) => G
expo... |
run = (params: RunParams<I>) => {
const { states } = this
if (!this.isGameStateWithRelac(params)) {
const { time, dt } = params
const state = cloneDeep(states[states.length - 1])
if (!state) {
throw new Error("GameEngine::run no state")
... | {
this.runFn = engineRunFn
this.states = [startingState]
} | identifier_body |
GameEngine.ts | import Chance from "chance"
import { BaseGameState, BaseInput } from "shared"
import { cloneDeep, max, times } from "lodash"
export interface EngineRunHelpers {
chance: () => Chance.Chance
}
export type EngineRunFn<I extends BaseInput, G extends BaseGameState<I>> = (state: G, helpers: EngineRunHelpers) => G
expo... | (engineRunFn: EngineRunFn<I, G>, startingState: G) {
this.runFn = engineRunFn
this.states = [startingState]
}
run = (params: RunParams<I>) => {
const { states } = this
if (!this.isGameStateWithRelac(params)) {
const { time, dt } = params
const state = clo... | constructor | identifier_name |
GameEngine.ts | import Chance from "chance"
import { BaseGameState, BaseInput } from "shared"
import { cloneDeep, max, times } from "lodash"
export interface EngineRunHelpers {
chance: () => Chance.Chance
}
export type EngineRunFn<I extends BaseInput, G extends BaseGameState<I>> = (state: G, helpers: EngineRunHelpers) => G
expo... |
}
startGameLoop = (params: StartGameLoopParams<I, G>) => {
const { fps, onStateUpdate } = params
let { gameTime, startTime } = params
if (!startTime) {
startTime = new Date().getTime()
}
if (!gameTime) {
gameTime = 0
}
// kill an... | {
if (!ts) {
ts = new Date().getTime()
}
// if state id is less than the very first state we have in the array,
// then this means we got this input too late. this means that the input packet
// took too long to get to us and we will be desync... | conditional_block |
GameEngine.ts | import Chance from "chance"
import { BaseGameState, BaseInput } from "shared"
import { cloneDeep, max, times } from "lodash"
export interface EngineRunHelpers {
chance: () => Chance.Chance
}
export type EngineRunFn<I extends BaseInput, G extends BaseGameState<I>> = (state: G, helpers: EngineRunHelpers) => G
expo... | this.exitGameLoopFn = undefined
}
}
loadFromState = (states: G[]) => {
console.log("loaded", states.length)
this.states = states
}
// getters
allStates = () => this.states
currentState = () => {
const { states } = this
return cloneDeep(states... | }
stopGameLoop = () => {
if (this.exitGameLoopFn) {
this.exitGameLoopFn() | random_line_split |
3d_LJ_nList.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 13:41:55 2021
@author: Archana P S
"""
# 3d lattice
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numba import jit
plt.rcParams['font.family']="Times New Roman"
plt.rcParams['xtick.labelsize']=18
plt.... | (natoms,x,y,z,nCount,nList,sigma,epsilon,lx,ly,lz,fx,fy,fz): # Siva, 19 Sept, 2021.
fx[:] = 0.0
fy[:] = 0.0
fz[:] = 0.0
PE = 0.0
virial = 0.0
for i in range(natoms):
#
for k in range(nCount[i]):
#starting = i*natoms
j = nList[i, k]
#
if(j != i):
#calculate the distance
dx... | compute_Forces_nbrList | identifier_name |
3d_LJ_nList.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 13:41:55 2021
@author: Archana P S
"""
# 3d lattice
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numba import jit
plt.rcParams['font.family']="Times New Roman"
plt.rcParams['xtick.labelsize']=18
plt.... | iz = 0
else:
iz = iz +1
else:
iy = iy + 1
else:
ix = ix + 1
x[i] = sigma/2.0 + ix*(dx + sigma)
y[i] = sigma/2.0 + iy*(dx + sigma)
z[i] = sigma/2.0 + iz*(dx + sigma)
return [x,y,z,lx,ly,lz]
def write_xyz_file(filename,x,y,z):
fout_xyz = open(filename, 'w+')
... | if (i % (nx)**2 == 0):
iy = 0
if (i % (nx)**3 == 0):
| random_line_split |
3d_LJ_nList.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 13:41:55 2021
@author: Archana P S
"""
# 3d lattice
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numba import jit
plt.rcParams['font.family']="Times New Roman"
plt.rcParams['xtick.labelsize']=18
plt.... |
@jit
def applyPBC(N,x,y,z,lx,ly,lz):
x = x - np.round(x/lx)*lx
y = y - np.round(y/ly)*ly
z = z - np.round(z/lz)*lz
return [x,y,z]
#======== main program ================================================#
#======== main program ================================================#
#======== main pro... | fx[:] = 0.0
fy[:] = 0.0
fz[:] = 0.0
PE = 0.0
virial = 0.0
for i in range(natoms):
#
for k in range(nCount[i]):
#starting = i*natoms
j = nList[i, k]
#
if(j != i):
#calculate the distance
dx = x[i]-x[j]
dy = y[i]-y[j]
dz = z[i]-z[j]
#minimum image.
dx = d... | identifier_body |
3d_LJ_nList.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 13:41:55 2021
@author: Archana P S
"""
# 3d lattice
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numba import jit
plt.rcParams['font.family']="Times New Roman"
plt.rcParams['xtick.labelsize']=18
plt.... |
PE = PE*0.5
virial = virial*0.5
#
return [fx,fy,fz,PE,virial]
@jit
def applyPBC(N,x,y,z,lx,ly,lz):
x = x - np.round(x/lx)*lx
y = y - np.round(y/ly)*ly
z = z - np.round(z/lz)*lz
return [x,y,z]
#======== main program ================================================#
#======== main program... | continue | conditional_block |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... | //! other words, don't reuse memory from a previous attempt.
//!
//! Find the input noun and verb that cause the program to produce the output
//! 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2,
//! the answer would be 1202.)
//!
//! # Day 5: Sunny with a Chance of Asteroids
//!
//! ## Part 1
... | //! like before. Each time you try a pair of inputs, make sure you first reset
//! the computer's memory to the values in the program (your puzzle input) - in | random_line_split |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... | ((mode, value): (usize, i32)) -> Self {
match mode {
0 => Param::Position(value as usize),
1 => Param::Immediate(value),
_ => unreachable!(),
}
}
}
#[derive(Debug)]
enum Op {
Add { a: Param, b: Param, out: usize },
Multiply { a: Param, b: Param, out: usiz... | from_pair | identifier_name |
intcode.rs | //! # Day 2 1202 Program Alarm
//!
//! ## Part 1
//!
//! On the way to your gravity assist around the Moon, your ship computer beeps
//! angrily about a "1202 program alarm". On the radio, an Elf is already
//! explaining how to handle the situation: "Don't worry, that's perfectly norma--"
//!
//! The ship computer bur... |
/// Attempt to identify the noun and verb (injected header values) which will
/// yield a certain target from a source intcode program by way of permutations.
pub fn solve(target: i32, data: &[i32]) -> Result<(i32, i32), ()> {
for (noun, verb) in (0..=99).flat_map(|i| (0..=99).map(move |j| (i, j))) {
let ... | {
let mut i = 0;
loop {
// FIXME: make read_instruction an iterator so it can manage the increment internally
match read_instruction(i, &data) {
Op::Add { a, b, out } => {
let a = read_value(a, data).unwrap();
let b = read_value(b, data).unwrap();
... | identifier_body |
token.go | package lex
import (
"fmt"
"strings"
)
// TokenType identifies the type of lexical tokens.
type TokenType uint16
// TokenInfo provides metadata about tokens
type TokenInfo struct {
T TokenType
Kw string
firstWord string // in event multi-word (Group By) the first word for match
HasSpaces ... |
return Token{T: TokenNil}
}
// String convert to human readable string
func (typ TokenType) String() string {
s, ok := TokenNameMap[typ]
if ok {
return s.Kw
}
return "not implemented"
}
// MatchString which keyword should we look for, either full keyword
// OR in case of spaces such as "group by" look for gro... | {
return Token{T: tt, V: op}
} | conditional_block |
token.go | package lex
import (
"fmt"
"strings"
)
// TokenType identifies the type of lexical tokens.
type TokenType uint16
// TokenInfo provides metadata about tokens
type TokenInfo struct {
T TokenType
Kw string
firstWord string // in event multi-word (Group By) the first word for match
HasSpaces ... |
// String convert to human readable string
func (typ TokenType) String() string {
s, ok := TokenNameMap[typ]
if ok {
return s.Kw
}
return "not implemented"
}
// MatchString which keyword should we look for, either full keyword
// OR in case of spaces such as "group by" look for group
func (typ TokenType) Match... | {
tt, ok := TokenToOp[op]
if ok {
return Token{T: tt, V: op}
}
return Token{T: TokenNil}
} | identifier_body |
token.go | package lex
import (
"fmt"
"strings"
)
// TokenType identifies the type of lexical tokens.
type TokenType uint16
// TokenInfo provides metadata about tokens
type TokenInfo struct {
T TokenType
Kw string
firstWord string // in event multi-word (Group By) the first word for match
HasSpaces ... | TokenDescribe: {Description: "describe"},
TokenExplain: {Description: "explain"},
TokenReplace: {Description: "replace"},
TokenRollback: {Description: "rollback"},
TokenCommit: {Description: "commit"},
// Top Level dml ql clause keywords
TokenInto: {Description: "into"},
TokenBy: {Desc... | TokenSubscribe: {Description: "subscribe"},
TokenFilter: {Description: "filter"},
TokenShow: {Description: "show"}, | random_line_split |
token.go | package lex
import (
"fmt"
"strings"
)
// TokenType identifies the type of lexical tokens.
type TokenType uint16
// TokenInfo provides metadata about tokens
type TokenInfo struct {
T TokenType
Kw string
firstWord string // in event multi-word (Group By) the first word for match
HasSpaces ... | () string {
s, ok := TokenNameMap[typ]
if ok {
return s.Kw
}
return "not implemented"
}
// MatchString which keyword should we look for, either full keyword
// OR in case of spaces such as "group by" look for group
func (typ TokenType) MatchString() string {
tokInfo, ok := TokenNameMap[typ]
//u.Debugf("matchst... | String | identifier_name |
begot.go | // Copyright (c) 2014-2015 Solano Labs Inc. All Rights Reserved.
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"gopkg.in/yaml.v2"
)
const (
BEGOTTEN = "Begotten"
BEGOTTEN_L... | () (out map[string]string) {
out = make(map[string]string)
for _, dep := range b.deps {
out[dep.Git_url] = dep.Ref
}
return
}
func (b *Builder) get_locked_refs_for_update(limits []string) (out map[string]string) {
out = make(map[string]string)
if len(limits) == 0 {
return
}
defer func() {
if err := reco... | _all_repos | identifier_name |
begot.go | // Copyright (c) 2014-2015 Solano Labs Inc. All Rights Reserved.
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"gopkg.in/yaml.v2"
)
const (
BEGOTTEN = "Begotten"
BEGOTTEN_L... |
type SortedStringMap yaml.MapSlice
func (sm SortedStringMap) Len() int {
return len(sm)
}
func (sm SortedStringMap) Less(i, j int) bool {
return sm[i].Key.(string) < sm[j].Key.(string)
}
func (sm SortedStringMap) Swap(i, j int) {
sm[i], sm[j] = sm[j], sm[i]
}
func (bf *BegottenFile) save(fn string) {
// We have... | {
bf = new(BegottenFile)
bf.data.Meta.File_version = -1
if data, err := ioutil.ReadFile(fn); err != nil {
panic(err)
} else if err := yaml.Unmarshal(data, &bf.data); err != nil {
panic(err)
}
ver := bf.data.Meta.File_version
if ver != -1 && ver != FILE_VERSION {
panic(fmt.Errorf("Incompatible file version ... | identifier_body |
begot.go | // Copyright (c) 2014-2015 Solano Labs Inc. All Rights Reserved.
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"gopkg.in/yaml.v2"
)
const (
BEGOTTEN = "Begotten"
BEGOTTEN_L... |
// Leave file open for lifetime of this process and anything exec'd by this
// process.
}
func print_help(ret int) {
fmt.Fprintln(os.Stderr, "FIXME")
os.Exit(ret)
}
func main() {
env := EnvNew()
defer func() {
if err := recover(); err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
}()
lock_... | {
panic(fmt.Errorf("Can't lock %r", env.BegotCache))
} | conditional_block |
begot.go | // Copyright (c) 2014-2015 Solano Labs Inc. All Rights Reserved.
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"syscall"
"gopkg.in/yaml.v2"
)
const (
BEGOTTEN = "Begotten"
BEGOTTEN_L... |
// Remove unexpected links.
for old_link := range old_links {
os.RemoveAll(old_link)
}
// Try to remove all directories; ignore ENOTEMPTY errors.
var dirs []string
filepath.Walk(depsrc, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if fi.IsDir() {
dirs = append(... | }
}
delete(old_links, path)
} | random_line_split |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... | }
/// Skips n from the left.
pub fn skip_left(self, n: usize) -> Range {
Range {
offset: self.offset + (n as u32),
length: self.length - (n as u32),
}
}
/// Skips n from the right.
pub fn skip_right(self, n: usize) -> Range {
Range {
... | /// Shifts range to specified offset.
pub fn shift_to(self, offset: usize) -> Range {
Range { offset: offset as u32, ..self } | random_line_split |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... | (&self) -> u32 { self.0.get() - 1 }
}
impl fmt::Debug for CoreId {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.raw())
}
}
impl Default for CoreId {
fn default() -> CoreId {
unsafe { CoreId(num::NonZeroU32::new_unchecked(std::u32::MAX)) }
}
}
... | raw | identifier_name |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... |
#[test]
fn range_extend_reversed() {
let result = Range::new(5, 3).extend(Range::new(3, 4));
assert_eq!(result, Range::new(3, 5));
}
}
| {
let result = Range::new(3, 4).extend(Range::new(5, 2));
assert_eq!(result, Range::new(3, 4));
} | identifier_body |
com.rs | //! Common utilities
//!
//! A standard vocabulary used throughout the code.
use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync};
use crate::basic::sea::TableIndex;
/// A fragment of source code.
#[derive(Clone)]
pub struct CodeFragment(sync::Arc<Vec<u8>>);
impl CodeFragment {
/// Creates a n... | else {
Range {
offset: self.offset,
length: (other.end_offset() - self.offset()) as u32
}
}
}
}
impl fmt::Debug for Range {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}@{}", self.length, self.offset)
... | {
self
} | conditional_block |
circuit.go | package circuit
import (
"context"
"expvar"
"sync"
"time"
"github.com/cep21/circuit/v3/faststats"
)
// Circuit is a circuit breaker pattern implementation that can accept commands and open/close on failures
type Circuit struct {
// circuitStats
CmdMetricCollector RunMetricsCollection
FallbackMetricColle... | }
// isEmptyOrNil returns true if the circuit is nil or if the circuit was created from an empty circuit. The empty
// circuit setup is mostly a guess (checking OpenToClose). This allows us to give circuits reasonable behavior
// in the nil/empty case.
func (c *Circuit) isEmptyOrNil() bool {
return c == nil || c.Op... | }
return nil | random_line_split |
circuit.go | package circuit
import (
"context"
"expvar"
"sync"
"time"
"github.com/cep21/circuit/v3/faststats"
)
// Circuit is a circuit breaker pattern implementation that can accept commands and open/close on failures
type Circuit struct {
// circuitStats
CmdMetricCollector RunMetricsCollection
FallbackMetricColle... |
currentCommandCount := c.concurrentCommands.Add(1)
defer c.concurrentCommands.Add(-1)
if err := c.throttleConcurrentCommands(currentCommandCount); err != nil {
c.CmdMetricCollector.ErrConcurrencyLimitReject(startTime)
return err
}
// Set timeout on the command if we have one
if c.threadSafeConfig.Execution... | {
return errCircuitOpen
} | conditional_block |
circuit.go | package circuit
import (
"context"
"expvar"
"sync"
"time"
"github.com/cep21/circuit/v3/faststats"
)
// Circuit is a circuit breaker pattern implementation that can accept commands and open/close on failures
type Circuit struct {
// circuitStats
CmdMetricCollector RunMetricsCollection
FallbackMetricColle... |
func (c *Circuit) checkErrBadRequest(ret error, runFuncDoneTime time.Time, totalCmdTime time.Duration) bool {
if IsBadRequest(ret) {
c.CmdMetricCollector.ErrBadRequest(runFuncDoneTime, totalCmdTime)
return true
}
return false
}
func (c *Circuit) checkErrFailure(ret error, runFuncDoneTime time.Time, totalCmdTi... | {
// We need to see an error in both the original context and the return value to consider this an "interrupt" caused
// error.
if ret == nil || originalContext.Err() == nil {
return false
}
isErrInterrupt := c.notThreadSafeConfig.Execution.IsErrInterrupt
if isErrInterrupt == nil {
isErrInterrupt = func(_ er... | identifier_body |
circuit.go | package circuit
import (
"context"
"expvar"
"sync"
"time"
"github.com/cep21/circuit/v3/faststats"
)
// Circuit is a circuit breaker pattern implementation that can accept commands and open/close on failures
type Circuit struct {
// circuitStats
CmdMetricCollector RunMetricsCollection
FallbackMetricColle... | (ctx context.Context, err error, fallbackFunc func(context.Context, error) error) error {
// Use the fallback command if available
if fallbackFunc == nil || c.threadSafeConfig.Fallback.Disabled.Get() {
return err
}
// Throttle concurrent fallback calls
currentFallbackCount := c.concurrentFallbacks.Add(1)
defer... | fallback | identifier_name |
aku-utils.go | package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
aerospike "github.com/aerospike/aerospike-client-go"
"go.uber.org/zap"
)
// Read certificate file and abort if any errors
// Returns file content as byte array
func readCertFil... |
}
// only one connection
clientPolicy.ConnectionQueueSize = 1
clientPolicy.Timeout = 5 * time.Second
clientPolicy.TlsConfig = tlsConfig
port := servicePlainPort
tlsName := ""
if clientPolicy.TlsConfig != nil {
port = serviceTLSPort
tlsName = serviceTLSName
}
portInt, _ := strconv.Atoi(port)
server :=... | {
clientPolicy.AuthMode = aerospike.AuthModeExternal
} | conditional_block |
aku-utils.go | package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
aerospike "github.com/aerospike/aerospike-client-go"
"go.uber.org/zap"
)
// Read certificate file and abort if any errors
// Returns file content as byte array
func readCertFil... |
// Get certificate file path
func getCertFilePath(configMountPoint string, certFile string, fileName string) (string, error) {
if certFile == "" {
return "", fmt.Errorf("certificate file name empty")
}
parsedCertFile := strings.Split(certFile, ":")
switch len(parsedCertFile) {
case 1:
return certFile, nil
... | {
var tlsConfig *tls.Config
if serviceTLSEnabled == "true" {
serverPool, err := x509.SystemCertPool()
if serverPool == nil || err != nil {
zap.S().Debugf("Adding system certificates to the cert pool failed: %s.", err)
serverPool = x509.NewCertPool()
}
if len(serviceCAFile) > 0 {
path, err := getCer... | identifier_body |
aku-utils.go | package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
aerospike "github.com/aerospike/aerospike-client-go"
"go.uber.org/zap"
)
// Read certificate file and abort if any errors
// Returns file content as byte array
func readCertFil... | // Update global variables from ENV variable inputs
func initVars() {
zap.S().Info("Initializing variables.")
podIP, ok := os.LookupEnv("MY_POD_IP")
if ok {
myPodIP = podIP
}
secEnabled, ok := os.LookupEnv("SECURITY_ENABLED")
if ok {
securityEnabled = secEnabled
}
helmusr, ok := os.LookupEnv("HELM_USERNA... | return "", fmt.Errorf("Unable to parse cert file: %s", certFile)
}
| random_line_split |
aku-utils.go | package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
aerospike "github.com/aerospike/aerospike-client-go"
"go.uber.org/zap"
)
// Read certificate file and abort if any errors
// Returns file content as byte array
func readCertFil... | (configMountPoint string, certFile string, fileName string) (string, error) {
if certFile == "" {
return "", fmt.Errorf("certificate file name empty")
}
parsedCertFile := strings.Split(certFile, ":")
switch len(parsedCertFile) {
case 1:
return certFile, nil
case 2:
switch parsedCertFile[0] {
case "file"... | getCertFilePath | identifier_name |
physics_hooks.rs | use crate::dynamics::{RigidBodyHandle, RigidBodySet};
use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags};
use crate::math::{Real, Vector};
use na::ComplexField;
/// Context given to custom collision filters to filter-out collisions.
pub struct PairFilterContext<'a> {
//... | /// This can be used to apply custom logic in order to decide whether two colliders
/// should have their intersection computed by the narrow-phase.
///
/// Note that using an intersection pair filter will replace the default intersection filtering
/// which consists of preventing intersection compu... | /// | random_line_split |
physics_hooks.rs | use crate::dynamics::{RigidBodyHandle, RigidBodySet};
use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags};
use crate::math::{Real, Vector};
use na::ComplexField;
/// Context given to custom collision filters to filter-out collisions.
pub struct PairFilterContext<'a> {
//... |
}
bitflags::bitflags! {
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
/// Flags affecting the behavior of the constraints solver for a given contact manifold.
pub struct ActiveHooks: u32 {
/// If set, Rapier will call `PhysicsHooks::filter_contact_pair` whenever relevant... | {
const CONTACT_CONFIGURATION_UNKNOWN: u32 = 0;
const CONTACT_CURRENTLY_ALLOWED: u32 = 1;
const CONTACT_CURRENTLY_FORBIDDEN: u32 = 2;
let cang = ComplexField::cos(allowed_angle);
// Test the allowed normal with the local-space contact normal that
// points towards the e... | identifier_body |
physics_hooks.rs | use crate::dynamics::{RigidBodyHandle, RigidBodySet};
use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags};
use crate::math::{Real, Vector};
use na::ComplexField;
/// Context given to custom collision filters to filter-out collisions.
pub struct PairFilterContext<'a> {
//... |
}
CONTACT_CURRENTLY_ALLOWED => {
// We allow all the contacts right now. The configuration becomes
// uncertain again when the contact manifold no longer contains any contact.
if self.solver_contacts.is_empty() {
*self.user_dat... | {
// Discard all the contacts.
self.solver_contacts.clear();
} | conditional_block |
physics_hooks.rs | use crate::dynamics::{RigidBodyHandle, RigidBodySet};
use crate::geometry::{ColliderHandle, ColliderSet, ContactManifold, SolverContact, SolverFlags};
use crate::math::{Real, Vector};
use na::ComplexField;
/// Context given to custom collision filters to filter-out collisions.
pub struct PairFilterContext<'a> {
//... | (&self, _: &PairFilterContext) -> bool {
true
}
fn modify_solver_contacts(&self, _: &mut ContactModificationContext) {}
}
| filter_intersection_pair | identifier_name |
envmon_sensor_info.pb.go | /*
Copyright 2019 Cisco Systems
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
d... |
return ""
}
type EnvmonSensorInfo struct {
FieldValidityBitmap string `protobuf:"bytes,50,opt,name=field_validity_bitmap,json=fieldValidityBitmap,proto3" json:"field_validity_bitmap,omitempty"`
DeviceDescription string `protobuf:"bytes,51,opt,name=device_description,json=deviceDescription,proto3" json:"dev... | {
return m.Name_7
} | conditional_block |
envmon_sensor_info.pb.go | /*
Copyright 2019 Cisco Systems
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
d... | 0x88, 0x9c, 0x59, 0x37, 0x84, 0x3e, 0x46, 0xdb, 0xfe, 0x7b, 0xbd, 0x93, 0x5f, 0x91, 0xb8, 0x7f,
0xf3, 0xd6, 0xfa, 0xeb, 0xe7, 0xef, 0x17, 0x52, 0x8a, 0x5d, 0x0b, 0x25, 0xaa, 0xe8, 0x38, 0x3a,
0x9d, 0xad, 0x78, 0x96, 0x47, 0x62, 0x1a, 0x7e, 0xf5, 0x99, 0xfa, 0x8f, 0xe9, 0x24, 0xb4, 0xb3,
0x01, 0x27, 0x6a, 0x67, 0xc4... | 0xe4, 0xcf, 0x28, 0x33, 0x3e, 0xab, 0xb4, 0xa9, 0xbc, 0xbe, 0x0e, 0xa6, 0x2d, 0x37, 0x4e, 0x57,
0x35, 0xba, 0xd8, 0xd8, 0x16, 0x2d, 0x55, 0x6e, 0x1b, 0x3b, 0xc8, 0x7e, 0x78, 0xce, 0x18, 0x2d,
0x19, 0xda, 0xc6, 0xbe, 0xa8, 0x28, 0x26, 0x6f, 0xce, 0x3c, 0x67, 0x88, 0x84, 0xc7, 0x24, 0x44,
0xca, 0x63, 0x1a, 0x62, 0xce... | random_line_split |
envmon_sensor_info.pb.go | /*
Copyright 2019 Cisco Systems
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
d... | (src proto.Message) {
xxx_messageInfo_EnvmonSensorInfo_KEYS.Merge(m, src)
}
func (m *EnvmonSensorInfo_KEYS) XXX_Size() int {
return xxx_messageInfo_EnvmonSensorInfo_KEYS.Size(m)
}
func (m *EnvmonSensorInfo_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_EnvmonSensorInfo_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_Env... | XXX_Merge | identifier_name |
envmon_sensor_info.pb.go | /*
Copyright 2019 Cisco Systems
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
d... |
func (m *EnvmonSensorInfo_KEYS) GetName_4() string {
if m != nil {
return m.Name_4
}
return ""
}
func (m *EnvmonSensorInfo_KEYS) GetName_5() string {
if m != nil {
return m.Name_5
}
return ""
}
func (m *EnvmonSensorInfo_KEYS) GetName_6() string {
if m != nil {
return m.Name_6
}
return ""
}
func (m *... | {
if m != nil {
return m.Name_3
}
return ""
} | identifier_body |
battleship-final.py | from random import randrange
import random
| # input: boat, taken_positions
# this func checks if the boat outside the playground or the position of the boat is already in taken_position
# return: boat. boat will returned as [-1] or its specific position
boat.sort()
for i in range(len(boat)):
if boat[i] in taken_positions:
#this con... |
"""
both user and computer funcs:
"""
def check_ok(boat, taken_positions):
| random_line_split |
battleship-final.py | from random import randrange
import random
"""
both user and computer funcs:
"""
def check_ok(boat, taken_positions):
# input: boat, taken_positions
# this func checks if the boat outside the playground or the position of the boat is already in taken_position
# return: boat. boat will returned as [-1] or its... | (guesses):
# input: guesses is the combined list of hit, miss, comp
# this funcs asks the user to enter the shot, then checks the validity of the shot
# return: the valid shot
while True:
try:
shot = int(input("Enter your shot: "))
if shot < 0 or shot > 99:
s... | get_shot_user | identifier_name |
battleship-final.py | from random import randrange
import random
"""
both user and computer funcs:
"""
def check_ok(boat, taken_positions):
# input: boat, taken_positions
# this func checks if the boat outside the playground or the position of the boat is already in taken_position
# return: boat. boat will returned as [-1] or its... |
def create_boat(len_of_boat, boat_start, boat_direction, taken_positions):
# input: len_of_boat, boat_start, boat_direction, taken_positions
# this func initializes boat = []
# with len_of_boat, boat_start, boat_direction, this func create the position of the boat
# calls check_ok(boat, taken_positions) to se... | ships = [] #this is a 2D list contains the positions of all boats
for len_of_boat in num_boats:
boat_position = [-1] #create the initial position of every boat is [-1]
while -1 in boat_position:
boat_start = randrange(99) #boat starting point
boat_direction = randrange(1... | identifier_body |
battleship-final.py | from random import randrange
import random
"""
both user and computer funcs:
"""
def check_ok(boat, taken_positions):
# input: boat, taken_positions
# this func checks if the boat outside the playground or the position of the boat is already in taken_position
# return: boat. boat will returned as [-1] or its... |
return boat
def get_shot_comp(guesses, tactics):
# input: guesses (all moves), tactics(which is the list of all valid possible moves for the shot)
# in the first mơve, tactics = []
# this func checks if len(tactics) > 0
# if yes, pick shot = tactics[0]
# if no, pick shot = randrange(99)
# this func che... | for i in range(len_of_boat):
boat.append(boat_start - i)
boat = check_ok(boat, taken_positions) | conditional_block |
ei_formulario.js |
ei_formulario.prototype = new ei();
ei_formulario.prototype.constructor = ei_formulario;
/**
* @class Un formulario simple presenta una grilla de campos editables.
* A cada uno de estos campos se los denomina Elementos de Formulario (efs).
* @see ef
* @constructor
* @phpdoc classes/toba_ei_formulario.html toba... | (id, instancia, rango_tabs, input_submit, maestros, esclavos, invalidos) {
this._id = id;
this._instancia = instancia; //Nombre de la instancia del objeto, permite asociar al objeto con el arbol DOM
this._rango_tabs = rango_tabs;
this._input_submit = input_submit; //Campo que se setea en el submit del form
t... | ei_formulario | identifier_name |
ei_formulario.js | ei_formulario.prototype = new ei();
ei_formulario.prototype.constructor = ei_formulario;
/**
* @class Un formulario simple presenta una grilla de campos editables.
* A cada uno de estos campos se los denomina Elementos de Formulario (efs).
* @see ef
* @constructor
* @phpdoc classes/toba_ei_formulario.html toba_e... | }
};
/**
* Esquema de Cascadas:<br>
* Ventana de ejecución anterior al pedido de respuesta de la cascada
* Extender para agregar un comportamiento anterior a la respuesta
* @param {ef} ef_maestro Instancia del ef maestro que inicia la cascada
* @ventana
*/
ei_formulario.prototype.evt__cascadas_inicio ... | random_line_split | |
ei_formulario.js |
ei_formulario.prototype = new ei();
ei_formulario.prototype.constructor = ei_formulario;
/**
* @class Un formulario simple presenta una grilla de campos editables.
* A cada uno de estos campos se los denomina Elementos de Formulario (efs).
* @see ef
* @constructor
* @phpdoc classes/toba_ei_formulario.html toba... | {
datos_asociativo = datos_rs;
this.ef(respuesta.argument).set_opciones(datos_asociativo);
}
if(this.ef(respuesta.argument).mantiene_valor_cascada() && isset(this._tmp_valores_esclavos[respuesta.argument])) {
var valor_viejo = this._tmp_valores_esclavos[respuesta.argument];
if (isset(datos_a... | datos_asociativo = [];
for (var ind = 0; ind < datos_rs.length ; ind++) {
datos_asociativo[datos_rs[ind][0]] = datos_rs[ind][1];
}
//Se le pasa el formato RS para que no se rompa el ordenamiento, para el resto se usa el asociativo por BC
this.ef(respuesta.argument).set_opciones_rs(datos_rs);
... | conditional_block |
ei_formulario.js |
ei_formulario.prototype = new ei();
ei_formulario.prototype.constructor = ei_formulario;
/**
* @class Un formulario simple presenta una grilla de campos editables.
* A cada uno de estos campos se los denomina Elementos de Formulario (efs).
* @see ef
* @constructor
* @phpdoc classes/toba_ei_formulario.html toba... |
/**
* @private
* @param {ef} ef objeto que representa al ef
* @param {string} identificador Id. del ef
*/
ei_formulario.prototype.agregar_ef = function (ef, identificador) {
if (ef) {
this._efs[identificador] = ef;
}
};
/**
*@private
*@param {ef} objeto_ef Objeto que representa al ef
*/
ei_fo... | {
this._id = id;
this._instancia = instancia; //Nombre de la instancia del objeto, permite asociar al objeto con el arbol DOM
this._rango_tabs = rango_tabs;
this._input_submit = input_submit; //Campo que se setea en el submit del form
this.controlador = null; //Referencia al CI contenedor
this._efs =... | identifier_body |
webots_launcher.py | #!/usr/bin/env python
# Copyright 1996-2023 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Add the Ros2Supervisor
if self.__is_supervisor:
indent = ' '
world_file = open(self.__world_copy.name, 'a')
world_file.write('Robot {\n')
world_file.write(indent + 'name "Ros2Supervisor"\n')
world_file.write(indent + 'controller "<extern>"\n... | random_line_split | |
webots_launcher.py | #!/usr/bin/env python
# Copyright 1996-2023 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as error:
print(f'Failed to delete {file_path}. Reason: {error}.')
return super()._shutdown_process(context, send_sigint=send_sigint)
class Ros2SupervisorL... | os.unlink(file_path) | conditional_block |
webots_launcher.py | #!/usr/bin/env python
# Copyright 1996-2023 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self, *, condition, false_value='', true_value=''):
self.__condition = condition if isinstance(condition, Substitution) else TextSubstitution(text=str(condition))
self.__false_value = false_value if isinstance(false_value, Substitution) else TextSubstitution(text=false_value)
self.__true_value ... | __init__ | identifier_name |
webots_launcher.py | #!/usr/bin/env python
# Copyright 1996-2023 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
class WebotsLauncher(ExecuteProcess):
def __init__(self, output='screen', world=None, gui=True, mode='realtime', stream=False, ros2_supervisor=False,
port='1234', **kwargs):
if sys.platform == 'win32':
print('WARNING: Native webots_ros2 compatibility with Windows is deprecate... | def __init__(self, *, condition, false_value='', true_value=''):
self.__condition = condition if isinstance(condition, Substitution) else TextSubstitution(text=str(condition))
self.__false_value = false_value if isinstance(false_value, Substitution) else TextSubstitution(text=false_value)
self._... | identifier_body |
bikeshare_2.py | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
# my_list
cities = ["chicago", "new york", "washington"]
filters = ["month", "day", "both", "none"]
months = ["all", "january", "f... | # load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month, day of week and hour from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of... | (str) day - name of the day of week to filter_choosed by, or "all" to apply no day filter_choosed
Returns:
df - Pandas DataFrame containing city data filter_chooseded by month and day
"""
| random_line_split |
bikeshare_2.py | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
# my_list
cities = ["chicago", "new york", "washington"]
filters = ["month", "day", "both", "none"]
months = ["all", "january", "f... |
# if filter_choosed == "both"
if filter_choosed == "both":
# get user input for day of week and month
month, day = get_both()
# if filter_choosed == none
if filter_choosed == "none":
month = "all"
day = "all"
print('-'*40)
return city, month, day, ... | day = get_day()
month = "all" | conditional_block |
bikeshare_2.py | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
# my_list
cities = ["chicago", "new york", "washington"]
filters = ["month", "day", "both", "none"]
months = ["all", "january", "f... |
def main():
while True:
city, month, day, filter_choosed = get_filters()
df = load_data(city, month, day)
time_stats(df, filter_choosed)
station_stats(df, filter_choosed)
trip_duration_stats(df, filter_choosed)
user_stats(df, city, fi... | """Displays individual trip data of each user."""
data = df.to_dict('records')
i = 0
j = 5
length = len(data)
while True:
see_trip = input('\nWould you like to individual trip data? Type yes or no.\n')
if see_trip.lower() != 'yes':
break
else:
if i < ... | identifier_body |
bikeshare_2.py | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
# my_list
cities = ["chicago", "new york", "washington"]
filters = ["month", "day", "both", "none"]
months = ["all", "january", "f... | (column):
"""
calculate statistics(popular entry of that column and his occurrence) on the most frequent times of travel.
Args:
(pd.Series) column - column of a DataFrame
Returns:
popular_anything - string containing the popular entry
counts_anything - int containi... | popular_counts_column | identifier_name |
main.rs | use colored::*;
use dialoguer::Confirm;
use hyper::{http, server::conn::AddrStream, Body, Request, Response};
use indoc::printdoc;
use ipnetwork::IpNetwork;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use shared::{
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, IoErro... |
Ok(())
}
fn spawn_endpoint_refresher(interface: InterfaceName, network: NetworkOpt) -> Endpoints {
let endpoints = Arc::new(RwLock::new(HashMap::new()));
tokio::task::spawn({
let endpoints = endpoints.clone();
async move {
let mut interval = tokio::time::interval(Duration::from... | {
println!("{} bringing down interface (if up).", "[*]".dimmed());
wg::down(interface, network.backend).ok();
let config = conf.config_path(interface);
let data = conf.database_path(interface);
std::fs::remove_file(&config)
.with_path(&config)
.map_err(|e|... | conditional_block |
main.rs | use colored::*;
use dialoguer::Confirm;
use hyper::{http, server::conn::AddrStream, Body, Request, Response};
use indoc::printdoc;
use ipnetwork::IpNetwork;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use shared::{
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, IoErro... |
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let path = path.as_ref();
let file = File::open(path).with_path(path)?;
if shared::chmod(&file, 0o600)? {
println!(
"{} updated permissions for {} to 0600.",
"[!]".yellow(),
... | {
let mut invitation_file = File::create(&path).with_path(&path)?;
shared::chmod(&invitation_file, 0o600)?;
invitation_file
.write_all(toml::to_string(self).unwrap().as_bytes())
.with_path(path)?;
Ok(())
} | identifier_body |
main.rs | use colored::*;
use dialoguer::Confirm;
use hyper::{http, server::conn::AddrStream, Body, Request, Response};
use indoc::printdoc;
use ipnetwork::IpNetwork;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use shared::{
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, IoErro... | let req = Request::builder()
.uri(format!("http://{}/v1/admin/peers", test::WG_MANAGE_PEER_IP))
.header(shared::INNERNET_PUBKEY_HEADER, "!!!")
.body(Body::empty())
.unwrap();
let res = server.raw_request("10.80.80.80", req).await;
// addr::remote(... | #[tokio::test]
async fn test_unparseable_public_key() -> Result<(), Error> {
let server = test::Server::new()?;
| random_line_split |
main.rs | use colored::*;
use dialoguer::Confirm;
use hyper::{http, server::conn::AddrStream, Body, Request, Response};
use indoc::printdoc;
use ipnetwork::IpNetwork;
use parking_lot::{Mutex, RwLock};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use shared::{
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, IoErro... | (&self) -> bool {
self.peer.is_admin && self.user_capable()
}
pub fn user_capable(&self) -> bool {
!self.peer.is_disabled && self.peer.is_redeemed
}
pub fn redeemable(&self) -> bool {
!self.peer.is_disabled && !self.peer.is_redeemed
}
}
#[derive(Deserialize, Serialize, Deb... | admin_capable | identifier_name |
population.rs | // Copyright (c) 2017 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... |
for _ in 0..n_processes {
let cvar_pair_clone = cvar_pair.clone();
let processed_stack_clone = processed_stack.clone();
let process_queue_clone = process_queue.clone();
scope.spawn(move || {
let &(ref lock, ref cvar) = &*c... | let process_queue = Arc::new(Mutex::new(rx));
let processed_stack = Arc::new(Mutex::new(Vec::new())); | random_line_split |
population.rs | // Copyright (c) 2017 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... | (init_pop: Vec<T>) -> Self {
Population {
units: init_pop,
seed: 1,
breed_factor: 0.5,
survival_factor: 0.5,
max_size: 100,
}
}
//--------------------------------------------------------------------------
/// Sets the random seed ... | new | identifier_name |
constructor.go | package output
import (
"fmt"
"strconv"
"gopkg.in/yaml.v3"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/component/output"
iprocessor "github.com/benthosdev/benthos/v4/internal/component/processor"... |
}
return pipeline.NewProcessor(processors...), nil
}}...)
}
return pipelines
}
func fromSimpleConstructor(fn func(Config, interop.Manager, log.Modular, metrics.Type) (output.Streamed, error)) ConstructorFunc {
return func(
conf Config,
mgr interop.Manager,
log log.Modular,
stats metrics.Type,
pip... | {
return nil, err
} | conditional_block |
constructor.go | package output
import (
"fmt"
"strconv"
"gopkg.in/yaml.v3"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/component/output"
iprocessor "github.com/benthosdev/benthos/v4/internal/component/processor"... | Summary string
Description string
Categories []string
Footnotes string
Config docs.FieldSpec
Examples []docs.AnnotatedExample
Version string
}
// AppendProcessorsFromConfig takes a variant arg of pipeline constructor
// functions and returns a new slice of them where the processors of the
// ... | Status docs.Status | random_line_split |
constructor.go | package output
import (
"fmt"
"strconv"
"gopkg.in/yaml.v3"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/component/output"
iprocessor "github.com/benthosdev/benthos/v4/internal/component/processor"... | (fn func(Config, interop.Manager, log.Modular, metrics.Type) (output.Streamed, error)) ConstructorFunc {
return func(
conf Config,
mgr interop.Manager,
log log.Modular,
stats metrics.Type,
pipelines ...iprocessor.PipelineConstructorFunc,
) (output.Streamed, error) {
output, err := fn(conf, mgr, log, stats... | fromSimpleConstructor | identifier_name |
constructor.go | package output
import (
"fmt"
"strconv"
"gopkg.in/yaml.v3"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/component/output"
iprocessor "github.com/benthosdev/benthos/v4/internal/component/processor"... | {
if mgrV2, ok := mgr.(interface {
NewOutput(Config, ...iprocessor.PipelineConstructorFunc) (output.Streamed, error)
}); ok {
return mgrV2.NewOutput(conf, pipelines...)
}
if c, ok := Constructors[conf.Type]; ok {
return c.constructor(conf, mgr, log, stats, pipelines...)
}
return nil, component.ErrInvalidTyp... | identifier_body | |
assistant.js |
var sexArray = [];
var docTypesArray = [];
var academicLevelsArray = [];
var cropper;
$(document).ready(function ()
{
$("#main-menu-assistant").addClass("text-primary");
formValidator.Validate("#create-assistant-form", createAssistant);
//formValidator.Validate("#edit-availability-form", editAvailabil... | + "<div class='overflow-auto'><table class='table table-sm table-striped'>"
+ "<tr><th>Dirección:</th><td>" + assistantAddress + "<td></tr>"
+ "<tr><th>Email:</th><td>" + assistant.personalDataEmailAddress + "<td></tr>"
... | + "</a>" | random_line_split |
infer_lst.py | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | parser.add_argument('--focal_alpha', default=0.25, type=float)
# dataset parameters
parser.add_argument('--dataset_file', default='ICDAR2013')
parser.add_argument('--coco_path', default='./data/coco', type=str)
parser.add_argument('--coco_panoptic_path', type=str)
parser.add_argument('--remove_... | parser.add_argument('--dice_loss_coef', default=1, type=float)
parser.add_argument('--cls_loss_coef', default=2, type=float)
parser.add_argument('--bbox_loss_coef', default=5, type=float)
parser.add_argument('--giou_loss_coef', default=2, type=float) | random_line_split |
infer_lst.py | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | parser = argparse.ArgumentParser('Deformable DETR training and evaluation script', parents=[get_args_parser()])
args = parser.parse_args()
if args.output_dir:
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
main(args) | conditional_block | |
infer_lst.py | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... |
# standard PyTorch mean-std input image normalization
transform = T.Compose([
T.Resize(800),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
label_names = ['table', 'figure', 'natural_image', 'logo', 'signature']
colors = ['red', 'blue', 'green', 'yellow', 'black']
def main(ar... | parser = argparse.ArgumentParser('Deformable DETR Detector', add_help=False)
parser.add_argument('--lr', default=2e-4, type=float)
parser.add_argument('--lr_backbone_names', default=["backbone.0"], type=str, nargs='+')
parser.add_argument('--lr_backbone', default=2e-5, type=float)
parser.add_argument('-... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.