file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
app_2_wl.py | ovid19](http://www.prevcovid19.com/#/teste)")
st.sidebar.markdown("[Tweetru ministre gui eub walu wergu yaram ](https://twitter.com/MinisteredelaS1)")
st.sidebar.markdown("[Booleb xéeti mbir ak màndargaay jumtukaayu ](https://github.com/maelfabien/COVID-19-Senegal)")
st.sidebar.markdown("---")
st.sidebar.header("... | ['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 | ovid19](http://www.prevcovid19.com/#/teste)")
st.sidebar.markdown("[Tweetru ministre gui eub walu wergu yaram ](https://twitter.com/MinisteredelaS1)")
st.sidebar.markdown("[Booleb xéeti mbir ak màndargaay jumtukaayu ](https://github.com/maelfabien/COVID-19-Senegal)")
st.sidebar.markdown("---")
st.sidebar.header("... | 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 |
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 | < 64:
# for d in self.domains:
# self.Jobs.append(Job(d, [x,y,z], 250))
self.Jobs.sort()
self.uniq_total_cpus = list(utc)
self.uniq_total_cpus.sort()
def GenerateJobsTotalCPU(self, totalCPU, max_x=2**10, max_y=2**10, max_z=2**10):
utc = set()
cpu_configs = []
totalCPU_divisors = divisors(... |
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 | < 64:
# for d in self.domains:
# self.Jobs.append(Job(d, [x,y,z], 250))
self.Jobs.sort()
self.uniq_total_cpus = list(utc)
self.uniq_total_cpus.sort()
def GenerateJobsTotalCPU(self, totalCPU, max_x=2**10, max_y=2**10, max_z=2**10):
utc = set()
cpu_configs = []
totalCPU_divisors = divisors(... | (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 | < 64:
# for d in self.domains:
# self.Jobs.append(Job(d, [x,y,z], 250))
self.Jobs.sort()
self.uniq_total_cpus = list(utc)
self.uniq_total_cpus.sort()
def GenerateJobsTotalCPU(self, totalCPU, max_x=2**10, max_y=2**10, max_z=2**10):
utc = set()
cpu_configs = []
totalCPU_divisors = divisors(... | 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 | _t4 = -1
servo_handle_x_t3 = -1
servo_handle_y_t3 = -1
servo_handle_x_t2 = -1
servo_handle_y_t2 = -1
servo_handle_x_t1 = -1
servo_handle_y_t1 = -1
handle_list = {}
try:
with open('ball_details.json') as file:
ball_details = json.load(file)
except ImportError:
print('\n[ERROR] ball_details.json fil... |
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 | blue_upper = np.array([140,255 ,255], np.uint8)
blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper)
kernal = np.ones((5, 5))
blue_mask = cv2.dilate(blue_mask, kernal)
blue_gray=cv2.threshold(blue_mask, 245,225, cv2.THRESH_TRUNC)[1]
gray_blur_blue= cv2.Canny(blue_gray,100,255)
#Create a ma... | complete_all_mapping_path | identifier_name | |
task_5.py | _t4 = -1
servo_handle_x_t3 = -1
servo_handle_y_t3 = -1
servo_handle_x_t2 = -1
servo_handle_y_t2 = -1
servo_handle_x_t1 = -1
servo_handle_y_t1 = -1
handle_list = {}
try:
with open('ball_details.json') as file:
ball_details = json.load(file)
except ImportError:
print('\n[ERROR] ball_details.json fil... |
################# 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 | _t4 = -1
servo_handle_x_t3 = -1
servo_handle_y_t3 = -1
servo_handle_x_t2 = -1
servo_handle_y_t2 = -1
servo_handle_x_t1 = -1
servo_handle_y_t1 = -1
handle_list = {}
try:
with open('ball_details.json') as file:
ball_details = json.load(file)
except ImportError:
print('\n[ERROR] ball_details.json fil... | "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 | /pkg/admission"
"k8s.io/apiserver/pkg/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/finisher"
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/reg... | }
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 | /pkg/admission"
"k8s.io/apiserver/pkg/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/finisher"
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/reg... | return
}
listOptions := metainternalversion.ListOptions{}
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, &listOptions); err != nil {
err = errors.NewBadRequest(err.Error())
scope.err(err, w, req)
return
}
metainternalversion.SetListOp... | {
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 | /pkg/admission"
"k8s.io/apiserver/pkg/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/finisher"
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/reg... | (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 | /pkg/admission"
"k8s.io/apiserver/pkg/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/finisher"
requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/reg... | objGV := gvk.GroupVersion()
audit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, metainternalversionscheme.Codecs)
span.AddEvent("Recorded the audit event")
}
else {
if err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVe... | {
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 | elif(node['x']-rad<30):
startx=30+rad+20#aggiungo un margine
if(node['y']+rad>1000):
starty=1000-rad-20#tolgo un margine
elif(node['y']-rad<30):
starty=30+rad+20#aggiungo un margine
#radial base approach, mi muovo su una circonferenza: fa pochi spostamenti buoni
"""angle=2*Math.pi*uniform(0,1)#senz... | simo=n['x']
di | conditional_block | |
oldDH.py | tky=k['t']['y']
#print(l['s'])
slx=l['s']['x']
sly=l['s']['y']
tlx=l['t']['x']
tly=l['t']['y']
except:
print(k)
print("-----")
print(l)
exit()
if(intersects... | 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 | ['id']==k['source']):
sourceK=m
if(m['id']==k['target']):
targetK=m
if(m['id']==l['source']):
sourceL=m
if(m['id']==l['target']):
targetL=m"""
#print(k['s'])
try:
... | 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 | '] - 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'ideale è somma len archi ^2 bassa (ma non troppo); somma distanze tra coppie di nodi ... | lyn(i | identifier_name | |
textContent-es.js | as o procedimientos almacenados (SQL) y en la lógica de negocio en C#.",
"Escribí documentación funcional para nuevos clientes y capacité a nuevos usuarios."
],
"image": "aggity"
},
"luxtripper": {
"id": 4,
"ref": "luxtripper",
"slickitem":"#slick-slide05",
"company":... | "tasks": [],
"image": "wivi" | random_line_split | |
dwarfdebuginfo.rs | 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 Lice... |
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 | 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 Lice... |
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 | 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 Lice... | (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 | 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 ... | 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 | bb.llx, bb.lly, bb.urx, bb.lly, bb.urx, bb.ury, bb.llx, bb.ury,
)
// Draw trim marks
if !*longTrimMarks {
stream += fmt.Sprintf(` q
0 0 0 rg %f w
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f ... | {
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 | () 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 | %f m %f %f l S
%f %f m %f %f l S
Q `,
trimMarkLineWidth,
mb.llx-1, tb.lly, mb.urx+1, tb.lly, // bottom trim line
mb.llx-1, tb.ury, mb.urx+1, tb.ury, // top trim line
tb.llx, mb.lly-1, tb.llx, mb.ury+1, // left trim line
tb.urx, mb.lly-1, tb.urx, mb.ury+1, // right trim line
)
}
// Draw t... | {
return err
} | conditional_block | |
main.go | S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
%f %f m %f %f l S
Q `,
trimMarkLineWidth,
mb.llx-1, tb.lly, bb.llx, tb.lly,
mb.llx-1, tb.ury, bb.llx, tb.ury,
tb.llx, mb.ury+1, tb.llx, bb.ury,... | if !*debugMode { | random_line_split | |
app.py |
socketio.emit('patientInfo',res)
@socketio.on('startTest')
def startTest(index):
print('start Test')
info = datas[index]
#print(info)
socketio.emit('startTest',{'testType':info['type'],'narration':info['narration']})
@socketio.on('testFinished')
def testFinished():
socketio.emit('testFinishe... | random_line_split | ||
app.py | 1. 미어캣 82. 코요테
83. 라마 84. 딱따구리
85. 기러기 86. 비둘기
87. 스컹크 88. 아르마딜로
89. 돌고래 90. 까마귀
91. 매 92. 낙타
93. 여우 94. 사슴
95. 늑대 96. 재규어
97. 알파카 98. 양
99. 다람쥐 100. 담비
'''.split()[1::2]
anilist = list(map(lambda x : x.strip(),anilist))
@app.route("/")
def main():
return ' '
@socketio.on('connect')
def on_connect(clie... | 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 | 81. 미어캣 82. 코요테
83. 라마 84. 딱따구리
85. 기러기 86. 비둘기
87. 스컹크 88. 아르마딜로
89. 돌고래 90. 까마귀
91. 매 92. 낙타
93. 여우 94. 사슴
95. 늑대 96. 재규어
97. 알파카 98. 양
99. 다람쥐 100. 담비
'''.split()[1::2]
anilist = list(map(lambda x : x.strip(),anilist))
@app.route("/")
def main():
return ' '
@socketio.on('connect')
def on_connect(cli... | 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 | 81. 미어캣 82. 코요테
83. 라마 84. 딱따구리
85. 기러기 86. 비둘기
87. 스컹크 88. 아르마딜로
89. 돌고래 90. 까마귀
91. 매 92. 낙타
93. 여우 94. 사슴
95. 늑대 96. 재규어
97. 알파카 98. 양
99. 다람쥐 100. 담비
'''.split()[1::2]
anilist = list(map(lambda x : x.strip(),anilist))
@app.route("/")
def main():
return ' '
@socketio.on('connect')
def on_connect(cli... | 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 | input: I
}
export type RunParams<I extends BaseInput> = GameStateRecalculateWithInput<I> | { time: number; dt: number }
interface InputQueueItem<I extends BaseInput> {
input: I
stateId: number
ts: number
}
interface SetInputParams<I extends BaseInput> {
input: I
stateId?: number
ts?: numb... |
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 | input: I
}
export type RunParams<I extends BaseInput> = GameStateRecalculateWithInput<I> | { time: number; dt: number }
interface InputQueueItem<I extends BaseInput> {
input: I
stateId: number
ts: number
}
interface SetInputParams<I extends BaseInput> {
input: I
stateId?: number
ts?: numb... | (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 | input: I
}
export type RunParams<I extends BaseInput> = GameStateRecalculateWithInput<I> | { time: number; dt: number }
interface InputQueueItem<I extends BaseInput> {
input: I
stateId: number
ts: number
}
interface SetInputParams<I extends BaseInput> {
input: I
stateId?: number
ts?: numb... | } else {
// replace with more up to date information
this.inputQueue[existingIdx] = { input, stateId, ts }
console.log("replaced queue item", stateId, JSON.stringify(iii.axis))
}
}
}
startGameLoop = (params: StartGameLoopParams<I,... | {
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 | Input> {
input: I
stateId?: number
ts?: number
}
interface StartGameLoopParams<I extends BaseInput, G extends BaseGameState<I>> {
fps: number
startTime?: number
gameTime?: number
onStateUpdate?: (g: G) => any
}
export class GameEngine<I extends BaseInput, G extends BaseGameState<I>> {
... | }
stopGameLoop = () => {
if (this.exitGameLoopFn) {
this.exitGameLoopFn() | random_line_split | |
3d_LJ_nList.py | ')
nMax = x.size
fout_xyz.write("{}\n".format(nMax))
fout_xyz.write("comment\n")
for i in range(nMax):
fout_xyz.write("1 {} {} {}\n".format(x[i], y[i], z[i]))
fout_xyz.close()
return
@jit
def computeForces(x,y,z,natoms,sigma,epsilon):
fx[:] = 0.0
fy[:] = 0.0
fz[:] = 0.0
PE = 0.0
... | (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 | 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 | ')
nMax = x.size
fout_xyz.write("{}\n".format(nMax))
fout_xyz.write("comment\n")
for i in range(nMax):
fout_xyz.write("1 {} {} {}\n".format(x[i], y[i], z[i]))
fout_xyz.close()
return
@jit
def computeForces(x,y,z,natoms,sigma,epsilon):
fx[:] = 0.0
fy[:] = 0.0
fz[:] = 0.0
PE = 0.0
... | dy = dy - np.round(dy/ly)*ly
dz = dz - np.round(dz/lz)*lz
rij = np.sqrt(dx**2.0 + dy**2.0 + dz**2.0)
rij2 = rij**2.0
rcut2 = rcut**2.0
if(rij2 < rcut2):
# need to calculate the force.
rinv = 1.0/rij
rinv2 = rinv**2.0
sr6 = (sigma/rij)**6.0
src6 = (s... | 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 | ')
nMax = x.size
fout_xyz.write("{}\n".format(nMax))
fout_xyz.write("comment\n")
for i in range(nMax):
fout_xyz.write("1 {} {} {}\n".format(x[i], y[i], z[i]))
fout_xyz.close()
return
@jit
def computeForces(x,y,z,natoms,sigma,epsilon):
fx[:] = 0.0
fy[:] = 0.0
fz[:] = 0.0
PE = 0.0
... |
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 | continue | conditional_block |
intcode.rs | pping forward 4 more positions arrives at opcode `99`, halting the
//! program.
//!
//! Here are the initial and final states of a few more small programs:
//!
//! - `1,0,0,0,99` becomes `2,0,0,0,99` (1 + 1 = 2).
//! - `2,3,0,3,99` becomes `2,3,0,6,99` (3 * 2 = 6).
//! - `2,4,4,5,99,0` becomes `2,4,4,5,99,9801` (99 * 9... | //! 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 | computer's memory. When you run an Intcode program,
//! make sure to start by initializing memory to the program's values. A position
//! in memory is called an address (for example, the first value in memory is at
//! "address 0").
//!
//! Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values
//... | from_pair | identifier_name | |
intcode.rs | - if
//! the parameter is 50, its value is simply 50.
//!
//! Parameter modes are stored in the same value as the instruction's opcode.
//! The opcode is a two-digit number based only on the ones and tens digit of the
//! value, that is, the opcode is the rightmost two digits of the first value in
//! an instruction. ... | {
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 | // Misc
TokenComma: {Description: ","},
TokenStar: {Kw: "*", Description: "*"},
TokenColon: {Kw: ":", Description: ":"},
TokenLeftBracket: {Kw: "[", Description: "["},
TokenRightBracket: {Kw: "]", Description: "]"},
TokenLeftBrace: {Kw: "{", Description: "{"},
TokenRightBrace: ... | {
return Token{T: tt, V: op}
} | conditional_block | |
token.go | ma: {Description: ","},
TokenStar: {Kw: "*", Description: "*"},
TokenColon: {Kw: ":", Description: ":"},
TokenLeftBracket: {Kw: "[", Description: "["},
TokenRightBracket: {Kw: "]", Description: "]"},
TokenLeftBrace: {Kw: "{", Description: "{"},
TokenRightBrace: {Kw: "}", Descript... | {
tt, ok := TokenToOp[op]
if ok {
return Token{T: tt, V: op}
}
return Token{T: TokenNil}
} | identifier_body | |
token.go | 07 // values
TokenInto TokenType = 308 // into
TokenLimit TokenType = 309 // limit
TokenOrderBy TokenType = 310 // order by
TokenInner TokenType = 311 // inner , ie of join
TokenCross TokenType = 312 // cross
TokenOuter TokenType = 313 // outer
TokenLeft TokenType = 314 // left
TokenRight ... | TokenSubscribe: {Description: "subscribe"},
TokenFilter: {Description: "filter"},
TokenShow: {Description: "show"}, | random_line_split | |
token.go | Kw: "*", Description: "*"},
TokenColon: {Kw: ":", Description: ":"},
TokenLeftBracket: {Kw: "[", Description: "["},
TokenRightBracket: {Kw: "]", Description: "]"},
TokenLeftBrace: {Kw: "{", Description: "{"},
TokenRightBrace: {Kw: "}", Description: "}"},
// Logic, Expressions, Operators etc
... | String | identifier_name | |
begot.go | , v))
}
yaml_copy(mv, &dep)
if dep.Import_path != "" {
parts := strings.Split(dep.Import_path, "/")
if repo_parts, ok := KNOWN_GIT_SERVERS[parts[0]]; !ok {
panic(fmt.Errorf("Unknown git server %r for %r", parts[0], name))
} else {
repo_path := strings.Join(parts[:repo_parts+1], "/")
dep.Git_url = bf... | () (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 |
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 | writes *map[string]bool) string {
if rewrite, ok := (*sub_dep_map)[imp]; ok {
imp = rewrite
(*used_rewrites)[rewrite] = true
} else {
parts := strings.Split(imp, "/")
if _, ok := KNOWN_GIT_SERVERS[parts[0]]; ok {
imp = b._lookup_dep_name(src_url, imp)
}
}
return imp
}
func (b *Builder) _lookup_dep_nam... | {
panic(fmt.Errorf("Can't lock %r", env.BegotCache))
} | conditional_block | |
begot.go | _bg.deps() {
b._record_repo_dep(url, sub_dep.Git_url)
our_dep := b._lookup_dep_by_git_url_and_path(sub_dep.Git_url, sub_dep.Subpath)
if our_dep != nil {
if sub_dep.Ref != our_dep.Ref {
panic(fmt.Sprintf("Conflict: %s depends on %s at %s, we depend on it at %s",
url, sub_dep.Git_url, sub_dep.Ref,... | }
}
delete(old_links, path)
} | random_line_split | |
com.rs | {
/// Creates a new instance.
pub fn new(id: u32) -> Self { Id(CoreId::new(id), marker::PhantomData) }
/// Creates an empty instance.
pub fn empty() -> Self { Self::new(std::u32::MAX - 2) }
/// Returns whether the corresponding list is empty.
pub fn is_empty(&self) -> bool { *self == Self::em... | /// Shifts range to specified offset.
pub fn shift_to(self, offset: usize) -> Range {
Range { offset: offset as u32, ..self } | random_line_split | |
com.rs | (&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 | Iterator for IdIterator<T> {
fn len(&self) -> usize {
self.end.saturating_sub(self.start) as usize
}
}
impl<T: ?Sized> cmp::Ord for IdIterator<T> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
(self.start, self.end).cmp(&(other.start, other.end))
}
}
impl<T: ?Sized> cmp::PartialEq fo... | {
let result = Range::new(3, 4).extend(Range::new(5, 2));
assert_eq!(result, Range::new(3, 4));
} | identifier_body | |
com.rs | fmt::Formatter) -> Result<(), fmt::Error> {
const MODULE_OFFSET: usize = 1usize << 30;
const REPOSITORY_OFFSET: usize = 1usize << 31;
// More compact representation for `{:#?}`.
//
// FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()`
// once it stab... | {
self
} | conditional_block | |
circuit.go | to this configuration are not reflected by the circuit.
// In other words, this creates a copy.
func (c *Circuit) Config() Config {
c.notThreadSafeConfigMu.Lock()
defer c.notThreadSafeConfigMu.Unlock()
return c.notThreadSafeConfig
}
// SetConfigNotThreadSafe is only useful during construction before a circuit is b... | }
// 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 | this configuration are not reflected by the circuit.
// In other words, this creates a copy.
func (c *Circuit) Config() Config {
c.notThreadSafeConfigMu.Lock()
defer c.notThreadSafeConfigMu.Unlock()
return c.notThreadSafeConfig
}
// SetConfigNotThreadSafe is only useful during construction before a circuit is bein... |
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 | expvarToVal(c.FallbackMetricCollector.Var()),
}
return ret
})
}
// Name of this circuit
func (c *Circuit) Name() string {
if c == nil {
return ""
}
return c.name
}
// IsOpen returns true if the circuit should be considered 'open' (ie not allowing runFunc calls)
func (c *Circuit) IsOpen() bool {
if c =... | {
// 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 | () {
// Don't open circuits that are forced closed
return
}
if c.IsOpen() {
// Don't bother opening a circuit that is already open
return
}
c.CircuitMetricsCollector.Opened(now)
c.isOpen.Set(true)
}
// Go executes `Execute`, but uses spawned goroutines to end early if the context is canceled. Use this if... | fallback | identifier_name | |
aku-utils.go | clientPolicy := aerospike.NewClientPolicy()
tlsConfig := initTLSConfig()
if securityEnabled == "true" {
clientPolicy.User = username
clientPolicy.Password = password
if authMode == "external" |
}
// 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 | clientPolicy := aerospike.NewClientPolicy()
tlsConfig := initTLSConfig()
if securityEnabled == "true" {
clientPolicy.User = username
clientPolicy.Password = password
if authMode == "external" {
clientPolicy.AuthMode = aerospike.AuthModeExternal
}
}
// only one connection
clientPolicy.ConnectionQueue... | serverPool.AppendCertsFromPEM(caCert)
}
var clientPool []tls.Certificate
if len(serviceCertFile) > 0 || len(serviceKeyFile) > 0 {
certPath, err := getCertFilePath(aerospikeConfigVolumePath, serviceCertFile, serviceTLSName+"-service-cert.pem")
if err != nil {
zap.S().Fatal("Unable to get certificate ... | {
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 | clientPolicy := aerospike.NewClientPolicy()
tlsConfig := initTLSConfig()
if securityEnabled == "true" {
clientPolicy.User = username
clientPolicy.Password = password
if authMode == "external" {
clientPolicy.AuthMode = aerospike.AuthModeExternal
}
}
// only one connection
clientPolicy.ConnectionQueue... | // 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 | clientPolicy := aerospike.NewClientPolicy()
tlsConfig := initTLSConfig()
if securityEnabled == "true" {
clientPolicy.User = username
clientPolicy.Password = password
if authMode == "external" {
clientPolicy.AuthMode = aerospike.AuthModeExternal
}
}
// only one connection
clientPolicy.ConnectionQueue... | (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 | handle of the first body involved in the potential collision.
pub rigid_body1: Option<RigidBodyHandle>,
/// The handle of the first body involved in the potential collision.
pub rigid_body2: Option<RigidBodyHandle>,
}
/// Context given to custom contact modifiers to modify the contacts seen by the constra... | /// 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 | of the first body involved in the potential collision.
pub rigid_body1: Option<RigidBodyHandle>,
/// The handle of the first body involved in the potential collision.
pub rigid_body2: Option<RigidBodyHandle>,
}
/// Context given to custom contact modifiers to modify the contacts seen by the constraints so... | self.solver_contacts.clear();
// NOTE: in some very rare cases `local_n1` will be
// zero if the objects are exactly touching at one point.
// So in this case we can't really conclude.
// If the norm is non-zero, then w... | {
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 | of the first body involved in the potential collision.
pub rigid_body1: Option<RigidBodyHandle>,
/// The handle of the first body involved in the potential collision.
pub rigid_body2: Option<RigidBodyHandle>,
}
/// Context given to custom contact modifiers to modify the contacts seen by the constraints so... |
}
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 | `self` to emulate a oneway-platform.
///
/// The "oneway" behavior will only allow contacts between two colliders
/// if the local contact normal of the first collider involved in the contact
/// is almost aligned with the provided `allowed_local_n1` direction.
///
/// To make this method work ... | filter_intersection_pair | identifier_name | |
envmon_sensor_info.pb.go | ) 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 *EnvmonSensorInfo_KEYS) GetName_7... |
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 | :"zigzag32,62,opt,name=average,proto3" json:"average,omitempty"`
Minimum int32 `protobuf:"zigzag32,63,opt,name=minimum,proto3" json:"minimum,omitempty"`
Maximum int32 `protobuf:"zigzag32,64,opt,name=maximum,proto3" json:"maximum,omitempty"`
Interval int32 `protobuf:"zig... | 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 | (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 |
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 | # 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 | miss
for i in range(len(ships)):
if shot in ships[i]:
ships[i].remove(shot)
if len(ships[i]) > 0:
hit.append(shot)
cond = 1 # hit
else:
comp.append(shot)
cond = 2 # comp
sinked_boat... | (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 | # miss
for i in range(len(ships)):
if shot in ships[i]:
ships[i].remove(shot)
if len(ships[i]) > 0:
hit.append(shot)
cond = 1 # hit
else:
comp.append(shot)
cond = 2 # comp
sinked_bo... |
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 | miss
for i in range(len(ships)):
if shot in ships[i]:
ships[i].remove(shot)
if len(ships[i]) > 0:
hit.append(shot)
cond = 1 # hit
else:
comp.append(shot)
cond = 2 # comp
sinked_boat... |
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 | (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 | _maestro = function(id_ef, fila)
{
if (this._esclavos[id_ef]) {
this.evt__cascadas_inicio(this.ef(id_ef));
//--Se recorren los esclavos del master modificado
for (var i=0; i < this._esclavos[id_ef].length; i++) {
this.cascadas_preparar_esclavo(this._esclavos[id_ef][i], fila);
}
}
};
/**
* Esqu... | random_line_split | ||
ei_formulario.js | de todos los objetos asociados
ei_formulario.prototype.puede_submit = function() {
if(this._evento) //Si hay un evento seteado...
{
//- 1 - Hay que realizar las validaciones
if(! this.validar() ) {
this.reset_evento();
return false;
}
if (! ei.prototype.puede_submit.call(this)) {
return f... | 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 |
/**
* @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 | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This launcher simply starts Webots."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from launch.actions import ExecuteProcess
from launch_ros.... | # 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 | import Node
from launch.launch_context import LaunchContext
from launch.substitution import Substitution
from launch.substitutions import TextSubstitution
from launch.substitutions.path_join_substitution import PathJoinSubstitution
from ament_index_python.packages import get_package_share_directory, get_package_prefix... | os.unlink(file_path) | conditional_block | |
webots_launcher.py | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This launcher simply starts Webots."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from launch.actions import ExecuteProcess
from launch_ros.... | (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 | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This launcher simply starts Webots."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from launch.actions import ExecuteProcess
from launch_ros.... |
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 | 3 = "Which month - January, February, March, April, May, or June?\n"
question_4 = "Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\n"
def handle_invalid_inputs(question,my_list):
"""
Gets, tests if the input of a question(question) belongs to a list(my_list) that we attend
... | # 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 | 3 = "Which month - January, February, March, April, May, or June?\n"
question_4 = "Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\n"
def handle_invalid_inputs(question,my_list):
"""
Gets, tests if the input of a question(question) belongs to a list(my_list) that we attend
... |
# 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 | ()
"""
return get_month(), get_day()
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter_choosed by, or "all" to apply no month filter_choosed
(str) day ... | """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 | 3 = "Which month - January, February, March, April, May, or June?\n"
question_4 = "Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?\n"
def handle_invalid_inputs(question,my_list):
"""
Gets, tests if the input of a question(question) belongs to a list(my_list) that we attend
... | (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 | _path(&path)?;
shared::chmod(&invitation_file, 0o600)?;
invitation_file
.write_all(toml::to_string(self).unwrap().as_bytes())
.with_path(path)?;
Ok(())
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let path = path.as_ref();
... | {
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 | _cidr_prefix: u8,
}
impl ConfigFile {
pub fn write_to_path<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> |
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 | : 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_secs(10));
loop {
interval.tick().await;
... | #[tokio::test]
async fn test_unparseable_public_key() -> Result<(), Error> {
let server = test::Server::new()?;
| random_line_split | |
main.rs | (&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 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
u... |
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 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
u... | (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 | ([]iprocessor.V1, len(conf.Processors))
for j, procConf := range conf.Processors {
var err error
pMgr := mgr.IntoPath("processors", strconv.Itoa(j))
processors[j], err = processor.New(procConf, pMgr)
if err != nil |
}
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 | 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 | make([]iprocessor.V1, len(conf.Processors))
for j, procConf := range conf.Processors {
var err error
pMgr := mgr.IntoPath("processors", strconv.Itoa(j))
processors[j], err = processor.New(procConf, pMgr)
if err != nil {
return nil, err
}
}
return pipeline.NewProcessor(processors...), ... | (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 | "retry"
TypeSFTP = "sftp"
TypeSTDOUT = "stdout"
TypeSubprocess = "subprocess"
TypeSwitch = "switch"
TypeSyncResponse = "sync_response"
TypeSocket = "socket"
TypeWebsocket = "websocket"
)
//-------------------------------------------------... | {
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 | document).on("keyup", "#searchAssistantInput", function ()
{
$(".assistant-list-thumb").addClass("d-none").removeClass("d-flex");
$(".assistant-list-thumb:contains('" + $(this).val() + "')").removeClass("d-none").addClass("d-flex");
});
});
var openAssistanFormModal = function (assistant = fal... | + "<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 | Enhance
import torchvision.transforms as T
import numpy as np
import torch
from torch.utils.data import DataLoader
import datasets
import util.misc as utils
from util import box_ops
import datasets.samplers as samplers
from datasets import build_dataset, get_coco_api_from_dataset
from engine import evaluate, train_one... | 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 | type=int)
parser.add_argument('--lr_drop_epochs', default=None, type=int, nargs='+')
parser.add_argument('--clip_max_norm', default=0.1, type=float,
help='gradient clipping max norm')
parser.add_argument('--sgd', action='store_true')
# Variants of Deformable DETR
parser.a... | 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 | Enhance
import torchvision.transforms as T
import numpy as np
import torch
from torch.utils.data import DataLoader
import datasets
import util.misc as utils
from util import box_ops
import datasets.samplers as samplers
from datasets import build_dataset, get_coco_api_from_dataset
from engine import evaluate, train_one... |
# Model parameters
parser.add_argument('--frozen_weights', type=str, default=None,
help="Path to the pretrained model. If set, only the mask head will be trained")
# * Backbone
parser.add_argument('--backbone', default='resnet50', type=str,
help="Name of... | 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.