code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function car_alt_hypoth
begin
return list 1 2 8
end function | def car_alt_hypoth():
return [1, 2, 8] | Python | nomic_cornstack_python_v1 |
import csv
import re
comment getting each row from the csv and each row is splitted acording to "|"
function get_data
begin
with open string Warriors_vs_Thunders.csv as stats_csv
begin
set csv_reader = reader stats_csv delimiter=string |
set play_by_play = list
for row in csv_reader
begin
append play_by_play row
end
e... | import csv
import re
# getting each row from the csv and each row is splitted acording to "|"
def get_data():
with open('Warriors_vs_Thunders.csv') as stats_csv:
csv_reader = csv.reader(stats_csv, delimiter='|')
play_by_play = []
for row in csv_reader:
play_by_play.append(row)
... | Python | zaydzuhri_stack_edu_python |
comment 前序遍历
function PreOrder self root
begin
string 打印二叉树(先序)
if root == none
begin
return
end
print val end=string
call PreOrder left
call PreOrder right
end function
comment 中序遍历
function InOrder self root
begin
string 中序打印
if root == none
begin
return
end
call InOrder left
print val end=string
call InOrder right
e... | # 前序遍历
def PreOrder(self, root):
'''打印二叉树(先序)'''
if root == None:
return
print(root.val, end=' ')
self.PreOrder(root.left)
self.PreOrder(root.right)
# 中序遍历
def InOrder(self, root):
'''中序打印'''
if root == None:
return
self.InOrder(root.left)
print(root.val, end=' ')
... | Python | zaydzuhri_stack_edu_python |
comment WAP to input a string and store ASCII values of all characters in a tuple.
set s1 = input string Enter a String:
set t = list
for i in range length s1
begin
append t ordinal s1 at i
end
set T = tuple t
print T | # WAP to input a string and store ASCII values of all characters in a tuple.
s1 = input('Enter a String: ')
t = []
for i in range(len(s1)):
t.append(ord(s1[i]))
T = tuple(t)
print(T)
| Python | zaydzuhri_stack_edu_python |
from logics import *
from tkinter import Frame , Label , CENTER , messagebox
from constants import *
set ai = call __import__ string 2048_ai
class game2048 extends Frame
begin
function __init__ self
begin
call __init__ self
set run = true
grid
title master string 2048
call bind string <Down> key_down
call bind string <... | from logics import *
from tkinter import Frame,Label,CENTER,messagebox
from constants import *
ai=__import__('2048_ai')
class game2048(Frame):
def __init__(self):
Frame.__init__(self)
self.run=True
self.grid()
self.master.title("2048")
self.master.bind("<Down>",self.key_dow... | Python | zaydzuhri_stack_edu_python |
comment https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms
string Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolu... | # https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms
"""
Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute val... | Python | zaydzuhri_stack_edu_python |
function get_articles self
begin
set articles_dir_path = join path current_path article_dir
set article_dirs = list comprehension path for f in call scandir articles_dir_path if call is_dir
print string Scanning components dir for files, found: + string article_dirs
set all_articles = list
for article_dir in article_d... | def get_articles(self):
articles_dir_path = os.path.join(self.current_path, self.article_dir)
article_dirs = [f.path for f in os.scandir(articles_dir_path) if f.is_dir()]
print("Scanning components dir for files, found: " + str(article_dirs))
all_articles = []
for article_dir in... | Python | nomic_cornstack_python_v1 |
import uuid
import Tkinter as tk
import ttk
import BaseGUIEvent
import PBFunction
import Task
import tkMessageBox
from Tkinter import * | import uuid
import Tkinter as tk
import ttk
import BaseGUIEvent
import PBFunction
import Task
import tkMessageBox
from Tkinter import *
| Python | zaydzuhri_stack_edu_python |
function greeting
begin
print string >>Welcome!<<
print string >>I was created to say wheter the typed number is odd or even<<
try
begin
call get_number
end
except any
begin
print string Sorry, I could not understand :(
call get_number
end
end function
function out_program
begin
print string Okay, thanks for using it! ... | def greeting ():
print('>>Welcome!<< \n')
print('>>I was created to say wheter the typed number is odd or even<< \n')
try:
get_number()
except:
print('Sorry, I could not understand :( \n')
get_number()
def out_program():
print('Okay, thanks for using it! See you next time.'... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ data_flows destinations resource_group_name data_collection_endpoint_id=none data_sources=none description=none identity=none kind=none location=none name=none stream_declarations=none tags=none
begin
set __self__ string data_flows data_flows
set __self__ string destinations destinations
set ... | def __init__(__self__, *,
data_flows: pulumi.Input[Sequence[pulumi.Input['DataCollectionRuleDataFlowArgs']]],
destinations: pulumi.Input['DataCollectionRuleDestinationsArgs'],
resource_group_name: pulumi.Input[str],
data_collection_endpoint_id: Optiona... | Python | nomic_cornstack_python_v1 |
function fasta_ids fasta_files verbose=false
begin
set all_ids = set list
for fasta_in in fasta_files
begin
for tuple label seq in call parse_fasta fasta_in
begin
set rid = split label at 0
if rid in all_ids
begin
raise call ValueError string Duplicate ID found in FASTA/qual file: %s % label
end
add all_ids rid
end
end... | def fasta_ids(fasta_files, verbose=False):
all_ids = set([])
for fasta_in in fasta_files:
for label, seq in parse_fasta(fasta_in):
rid = label.split()[0]
if rid in all_ids:
raise ValueError(
"Duplicate ID found in FASTA/qual file: %s" %
... | Python | nomic_cornstack_python_v1 |
function get_atoms ontology
begin
set pickled_file = string chemMAP/transformers/pcl_files/Atoms.pcl
if exists path pickled_file
begin
return load pickle open pickled_file string rb
end
set query = string PREFIX carcinogenesis: <http://dl-learner.org/carcinogenesis#> SELECT ?atom WHERE { ?atom rdfs:subClassOf carcinoge... | def get_atoms(ontology):
pickled_file = "chemMAP/transformers/pcl_files/Atoms.pcl"
if os.path.exists(pickled_file):
return pickle.load(open(pickled_file, "rb"))
query = """
PREFIX carcinogenesis: <http://dl-learner.org/carcinogenesis#>
SELECT ?atom
WHERE {
... | Python | nomic_cornstack_python_v1 |
function element_repr cls
begin
return element_repr
end function | def element_repr(cls) -> Literal["int", "poly", "power"]:
return super().element_repr | Python | nomic_cornstack_python_v1 |
function hyperplanes self
begin
return _hyperplanes
end function | def hyperplanes(self) -> np.ndarray:
return self._hyperplanes | Python | nomic_cornstack_python_v1 |
function _get_headers self is_json=false
begin
string Create headers dictionary for a request. :param boolean is_json: Whether the request body is a json. :return: The headers dictionary.
set headers = dict string Authorization string Bearer + call _get_token
if client_type is not none
begin
set headers at string Clien... | def _get_headers(self, is_json=False):
"""
Create headers dictionary for a request.
:param boolean is_json: Whether the request body is a json.
:return: The headers dictionary.
"""
headers = {"Authorization": "Bearer " + self._get_token()}
if self.client_type i... | Python | jtatman_500k |
comment https://drive.google.com/file/d/1XC2qfTSjUTaDIGcxi-dElxO0RXsbX8C5/view?usp=sharing
comment Задача:
comment Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
comment Числа и знак операции вводятся пользователем. После выполнения вычисления программа не завершается,
comment а ... | # https://drive.google.com/file/d/1XC2qfTSjUTaDIGcxi-dElxO0RXsbX8C5/view?usp=sharing
# Задача:
# Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем. После выполнения вычисления программа не завершается,
# а запрашивает новые данные д... | Python | zaydzuhri_stack_edu_python |
from agps.utils import action_prompt , take_words , move
import time
function wait_for_move inventory
begin
while true
begin
set action = call action_prompt inventory
if action at 0 is move
begin
return action at 1
end
end
end function
function enter name inventory
begin
if inventory at string §1234
begin
print string ... | from agps.utils import action_prompt, take_words, move
import time
def wait_for_move(inventory):
while True:
action = action_prompt(inventory)
if action[0] is move:
return action[1]
def enter(name, inventory):
if inventory['§1234']:
print("Bandits are running away from you ... | Python | zaydzuhri_stack_edu_python |
comment This is all you need for most Google Code Jam problems.
comment read a line with a single integer
set t = integer call raw_input
for i in call xrange 1 t + 1
begin
comment read a list of integers, 2 in this case
set n = list comprehension s for s in split call raw_input string
set n = n at 0
set val = integer n... | # This is all you need for most Google Code Jam problems.
t = int(raw_input()) # read a line with a single integer
for i in xrange(1, t + 1):
n = [s for s in raw_input().split(" ")] # read a list of integers, 2 in this case
n=n[0]
val=int(n)
flag=0
while(flag==0):
# print val
flag=1
NewN=list... | Python | zaydzuhri_stack_edu_python |
import datetime
import os
import time
import ntplib
from time import sleep
import time
from wrapt_timeout_decorator import *
import time
from functools import wraps
import db
function fn_timer function
begin
decorator wraps function
function function_timer *args **kwargs
begin
set t0 = time
set result = call function *... | import datetime
import os
import time
import ntplib
from time import sleep
import time
from wrapt_timeout_decorator import *
import time
from functools import wraps
import db
def fn_timer(function):
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = function(*... | Python | zaydzuhri_stack_edu_python |
class Stack
begin
function __init__ self
begin
set items = list
end function
function push self item
begin
append items item
end function
function pop self
begin
return pop items
end function
function is_empty self
begin
return items == list
end function
end class | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == [] | Python | jtatman_500k |
function update self indicator_properties=none
begin
try
begin
set _indicatorId = indicator_properties at string id
end
except any
begin
return string Indicator properties must include id of indicator
end
if indicator_properties is not none
begin
set _initiativedata at string indicators = list comprehension if expressi... | def update(self, indicator_properties=None):
try:
_indicatorId = indicator_properties['id']
except:
return 'Indicator properties must include id of indicator'
if indicator_properties is not None:
self._initiativedata['indicators'] = [dict(indicator_prope... | Python | nomic_cornstack_python_v1 |
import numpy as np
function load_data filename
begin
string 载入数据。
set xys = list
with open filename string r as f
begin
for line in f
begin
append xys map float split strip line
end
set tuple xs ys = zip *xys
return tuple call asarray xs call asarray ys
end
end function
class SigmoidActivator extends object
begin
func... | import numpy as np
def load_data(filename):
"""载入数据。"""
xys = []
with open(filename, 'r') as f:
for line in f:
xys.append(map(float, line.strip().split()))
xs, ys = zip(*xys)
return np.asarray(xs), np.asarray(ys)
class SigmoidActivator(object):
def forward (self,w... | Python | zaydzuhri_stack_edu_python |
comment This program uses an image (mapName), resizes it to its perfect size according to the gridValue, and turns it black
comment and white. It then generates a monochromatic brightness pattern, and a text file representing the values. The text
comment file is saved and used to generate the binary Top-Down image. (To... | ##This program uses an image (mapName), resizes it to its perfect size according to the gridValue, and turns it black
##and white. It then generates a monochromatic brightness pattern, and a text file representing the values. The text
##file is saved and used to generate the binary Top-Down image. (Top-down approach: I... | Python | zaydzuhri_stack_edu_python |
function set_text self text xpos=0 ypos=0
begin
call set_text text xpos ypos
call update_display
end function | def set_text(self, text, xpos=0, ypos=0):
self.state.set_text(text, xpos, ypos)
self.update_display() | Python | nomic_cornstack_python_v1 |
import numpy as np
from sklearn.metrics import roc_auc_score , average_precision_score , f1_score
from keras.callbacks import Callback
class RocAucEvaluation extends Callback
begin
string Calculate ROC AUC
function __init__ self validation_data interval=1
begin
string :param validation_data : tuple, validation data (X,... | import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score
from keras.callbacks import Callback
class RocAucEvaluation(Callback):
""" Calculate ROC AUC """
def __init__(self, validation_data, interval=1):
"""
:param validation_data : tuple, validation data ... | Python | zaydzuhri_stack_edu_python |
from PyCRC.CRC32 import CRC32
set soh = string 01111110
set eot = string 01111110
function encode
begin
string Packs data using the method of 'bits stuffing' from the input file, adds to the data CRC :return:None
set Z = open string Z string r
set W = open string W string w
set data = string read Z at slice : - 1 :
s... | from PyCRC.CRC32 import CRC32
soh = '01111110'
eot = '01111110'
def encode():
"""
Packs data using the method of 'bits stuffing' from the input file, adds to the data CRC
:return:None
"""
Z = open('Z','r')
W = open('W','w')
data = str(Z.read())[:-1]
crc = str(bin(CRC32().calculate(dat... | Python | zaydzuhri_stack_edu_python |
function sum_of_intervals intervals
begin
comment print('l: ',(intervals[1][1]))
for i in range length intervals
begin
if i < length intervals - 1 and intervals at i + 1 at 0 >= intervals at i at 1
begin
print intervals at i intervals at i + 1
end
print string { intervals at i } min: { min intervals at i at slice : :... | def sum_of_intervals(intervals):
# print('l: ',(intervals[1][1]))
for i in range(len(intervals)):
if i < (len(intervals)-1) and intervals[i + 1][0] >= intervals[i][1]:
print(intervals[i],intervals[i + 1])
print(f'{intervals[i]} min: {min(intervals[i][:])}, max: {max(intervals[i][:])}... | Python | zaydzuhri_stack_edu_python |
string OOI Data Team Import Module - Import Log Functions
import time
from common import *
comment Allowed columns
set columns = list string name string import_date string comment string created string modified
function find db name
begin
string Find an Import Log by name
set sql = string name="%s" % name
set result = ... | """ OOI Data Team Import Module - Import Log Functions """
import time
from .common import *
# Allowed columns
columns = ['name','import_date','comment','created','modified']
def find(db,name):
"""Find an Import Log by name"""
sql = 'name="%s"' % name
result = db.select('import_log',sql,'id')
if len(result) ... | Python | zaydzuhri_stack_edu_python |
function SetRemoveFaceMode self *args
begin
return call ShapeUpgrade_RemoveInternalWires_SetRemoveFaceMode self *args
end function | def SetRemoveFaceMode(self, *args):
return _ShapeUpgrade.ShapeUpgrade_RemoveInternalWires_SetRemoveFaceMode(self, *args) | Python | nomic_cornstack_python_v1 |
comment TODO: Licensing
string Provides infrastructure for generating and running Ace.OpenCL-accelerated simulations. What is a Simulation? ********************* A simulation in this context is a sequence of *elements*. The *state* of each element is updated every *timestep* according to a corresponding *model*. For ex... | # TODO: Licensing
"""Provides infrastructure for generating and running Ace.OpenCL-accelerated
simulations.
What is a Simulation?
*********************
A simulation in this context is a sequence of *elements*. The *state* of each
element is updated every *timestep* according to a corresponding *model*.
For example... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
set t = integer input
for _ in range t
begin
set s = strip input
set x = counter s
print length s - max x at string a x at string b
end | from collections import Counter
t = int(input())
for _ in range(t):
s = input().strip()
x = Counter(s)
print(len(s)-max(x['a'],x['b'])) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding=utf-8
comment Node ROS regulation
comment S'abonne aux commande demandées et extrait les données demandées pour les republier sous forme de float64
import rospy
import numpy as np
from std_msgs.msg import Float64 , Int16
import tf.transformations
function getprop obj string
b... | #!/usr/bin/env python
# coding=utf-8
# Node ROS regulation
# S'abonne aux commande demandées et extrait les données demandées pour les republier sous forme de float64
import rospy
import numpy as np
from std_msgs.msg import Float64, Int16
import tf.transformations
def getprop(obj, string):
"""
Par exemple ... | Python | zaydzuhri_stack_edu_python |
function _checkErrors self landPage
begin
set noLicenseTags = list string Purchase a Subscription string Purchase This Content string to gain access to this content string purchaseItem string Purchase Full Text string Purchase access string Purchase PDF string Pay Per Article string Purchase this article. string Online... | def _checkErrors(self, landPage):
noLicenseTags = ['Purchase a Subscription',
'Purchase This Content',
'to gain access to this content',
'purchaseItem',
'Purchase Full Text',
'Purchase access',
'Purchase PDF',
'Pay Per Article',
'Purchase t... | Python | nomic_cornstack_python_v1 |
function replace_macros tex_source macros
begin
string Replace macros in the TeX source with their content. Parameters ---------- tex_source : `str` TeX source content. macros : `dict` Keys are macro names (including leading ``\``) and values are the content (as `str`) of the macros. See `lsstprojectmeta.tex.scraper.ge... | def replace_macros(tex_source, macros):
r"""Replace macros in the TeX source with their content.
Parameters
----------
tex_source : `str`
TeX source content.
macros : `dict`
Keys are macro names (including leading ``\``) and values are the
content (as `str`) of the macros. S... | Python | jtatman_500k |
function setErrorCheck self errorCheck
begin
set _ecEnabled = errorCheck
end function | def setErrorCheck(self, errorCheck):
self._ecEnabled = errorCheck | Python | nomic_cornstack_python_v1 |
comment class Foo:
comment __x=1 #_Foo__x=1
comment def __init__(self,name):
comment self.__name=name #self._Foo__name=name
comment def __f1(self): #_Foo__f1
comment print('from f1')
comment def tell_name(self):
comment print(self.__name) #print(self._Foo__name)
comment obj=Foo('egon')
comment # print(obj.__dict__)
com... | # class Foo:
# __x=1 #_Foo__x=1
# def __init__(self,name):
# self.__name=name #self._Foo__name=name
#
# def __f1(self): #_Foo__f1
# print('from f1')
#
#
# def tell_name(self):
# print(self.__name) #print(self._Foo__name)
#
# obj=Foo('egon')
# # print(obj.__dict__)
# # print(Foo._... | Python | zaydzuhri_stack_edu_python |
comment ? Enumerate prints both the index and the value from the list
string Example: 0 Gabriel 1 Thais 2 Paulo
for name in names
begin
print name
end
comment ? Above is the vanilla code
comment * Best practice:
for tuple index name in enumerate names
begin
print index name
end
comment * It can be started at a chosen n... | #? Enumerate prints both the index and the value from the list
""" Example:
0 Gabriel
1 Thais
2 Paulo
"""
for name in names:
print(name)
#? Above is the vanilla code
#* Best practice:
for index, name in enumerate(names):
print(index, name)
#* It can be started at a chosen number by changing enumerate to
#? ... | Python | zaydzuhri_stack_edu_python |
function league_scores self
begin
set date = string format time datetime date string %Y%m%d
set url = string { base_url } { season } -regular/scoreboard.json?fordate= { date }
set scores = call api_request url
return scores at string scoreboard at string gameScore
end function | def league_scores(self):
date = datetime.datetime.strftime(self.date, "%Y%m%d")
url = f"{self.base_url}{self.season}-regular/scoreboard.json?fordate={date}"
scores = self.api_request(url)
return scores['scoreboard']['gameScore'] | Python | nomic_cornstack_python_v1 |
function dial_individual_pri self pri_channel_id port
begin
if integer port not in list lower_port upper_port
begin
raise exception string Invalid port number %d while dialing list of Individual PRI %d pri::CheckPRIs::getRunningPRI % integer port pri_channel_id
end
try
begin
set kombu_dialer_command = string {ignore_ea... | def dial_individual_pri(self,
pri_channel_id,
port):
if int(port) not in [self.lower_port, self.upper_port]:
raise Exception("Invalid port number %d while dialing list of\
Individual PRI %d pri::CheckPRIs::getRunningPRI"
... | Python | nomic_cornstack_python_v1 |
function encrypt
begin
set string = get args string string string
set param = decode call encrypt encode string
return call render_template string index.html string=param res=string Encrypt
end function | def encrypt():
string = request.args.get('string', '')
param = f.encrypt(string.encode()).decode()
return render_template('index.html', string=param, res='Encrypt') | Python | nomic_cornstack_python_v1 |
function get_algorithm_config self *args **kwargs
begin
if is instance _algorithm_mapping_func Callable
begin
set name = call _algorithm_mapping_func *args keyword kwargs
return algorithm_candidates at name
end
else
if _algorithm_mapping_func is none
begin
return list values algorithm_candidates at 0
end
else
begin
rai... | def get_algorithm_config(self, *args, **kwargs) -> Dict[str, Any]:
if isinstance(self._algorithm_mapping_func, Callable):
name = self._algorithm_mapping_func(*args, **kwargs)
return self.algorithm_candidates[name]
elif self._algorithm_mapping_func is None:
return lis... | Python | nomic_cornstack_python_v1 |
function _lower self mapping
begin
set _mapping = dict
for tuple k v in sorted items mapping
begin
set k = lower k
if k not in _mapping
begin
set _mapping at k = v
end
end
return _mapping
end function | def _lower(self, mapping):
_mapping = {}
for k, v in sorted(mapping.items()):
k = k.lower()
if k not in _mapping:
_mapping[k] = v
return _mapping | Python | nomic_cornstack_python_v1 |
function snake_case_split string_list
begin
set result = list
for string in string_list
begin
extend result list comprehension lower x for x in split string string _ if x
end
return result
end function | def snake_case_split(string_list):
result = []
for string in string_list:
result.extend([x.lower() for x in string.split('_') if x])
return result | Python | nomic_cornstack_python_v1 |
function save self *args **kwargs
begin
set ret = save *args keyword kwargs
comment Does cache invalidation
set cache_key = call make_cache_key type self object_id language
set cache_key self
return ret
end function | def save(self, *args, **kwargs):
ret = super(Translation, self).save(*args, **kwargs)
# Does cache invalidation
cache_key = Translation.objects.make_cache_key(type(self), self.object_id, self.language)
cache.set(cache_key, self)
return ret | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Question 7
comment Level 2
comment Question:
comment Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
comment Note: i=0,1.., X-1; j=0,1,¡Y-1.
comment Example
comment... | #!/usr/bin/env python
#Question 7
#Level 2
#Question:
#Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
#Note: i=0,1.., X-1; j=0,1,¡Y-1.
#Example
#Suppose the following inputs are given to th... | Python | zaydzuhri_stack_edu_python |
print string My favorite color is blue. | print('My favorite color is blue.') | Python | flytech_python_25k |
from adafruit_servokit import ServoKit
import board
import busio
import time
comment On the Jetson Nano
comment Bus 0 (pins 28,27) is board SCL_1, SDA_1 in the jetson board definition file
comment Bus 1 (pins 5, 3) is board SCL, SDA in the jetson definition file
comment Default is to Bus 1; We are using Bus 0
print str... | from adafruit_servokit import ServoKit
import board
import busio
import time
# On the Jetson Nano
# Bus 0 (pins 28,27) is board SCL_1, SDA_1 in the jetson board definition file
# Bus 1 (pins 5, 3) is board SCL, SDA in the jetson definition file
# Default is to Bus 1; We are using Bus 0
print("Initializing Servos")
i2c... | Python | zaydzuhri_stack_edu_python |
function _checkpoint_fn model optimizer epoch best_val_loss checkpoint_dir is_best_so_far
begin
comment Make the checkpoint
set checkpoint = dict
set checkpoint at string next_epoch = epoch + 1
set checkpoint at string best_val_loss = best_val_loss
set checkpoint at string model_state_dict = state dict model
set check... | def _checkpoint_fn(model, optimizer, epoch, best_val_loss, checkpoint_dir, is_best_so_far):
# Make the checkpoint
checkpoint = {}
checkpoint['next_epoch'] = epoch + 1
checkpoint['best_val_loss'] = best_val_loss
checkpoint['model_state_dict'] = model.state_dict()
checkpoint['optimizer_state_dict'... | Python | nomic_cornstack_python_v1 |
comment # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
comment #
comment ----- POST-PROCESSING OF HDF FILES: APPENDING DATA OF ----- #
comment LOCAL CELL DENSITY, NUCLEUS SIZE & DNA CONTENT #
comment FROM FLUORESCENCE SIGNAL INTENSITY #
comment #
comment ----- Class #1: Local Density Calculations ----- #... | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# ----- POST-PROCESSING OF HDF FILES: APPENDING DATA OF ----- #
# LOCAL CELL DENSITY, NUCLEUS SIZE & DNA CONTENT #
# FROM FLUORESCENCE SIGNAL INTENSITY #
... | Python | zaydzuhri_stack_edu_python |
function is_file dirname
begin
string Checks if a path is an actual file that exists
if not is file path dirname
begin
set msg = format string {0} is not an existing file dirname
raise call ArgumentTypeError msg
end
else
begin
return dirname
end
end function | def is_file(dirname):
'''Checks if a path is an actual file that exists'''
if not os.path.isfile(dirname):
msg = "{0} is not an existing file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | Python | jtatman_500k |
string https://www.acmicpc.net/problem/5567 STRATEGY Initialize graph as a node and list of vertices Maintain a set of visited nodes Iterate 1's nodes vertices and if not in set, increment number
function getNumofFriends friends_map
begin
set numFriends = 0
set visited = set
for friend in friends_map at 1
begin
if frie... | """
https://www.acmicpc.net/problem/5567
STRATEGY
Initialize graph as a node and list of vertices
Maintain a set of visited nodes
Iterate 1's nodes vertices and if not in set, increment number
"""
def getNumofFriends(friends_map):
numFriends = 0
visited = set()
for friend in friends_map[1]:
if friend not in visit... | Python | zaydzuhri_stack_edu_python |
function run_search dict_file postings_file queries_file results_file
begin
print string running search on the queries...
comment load in dictionary
set fp = open dict_file string rb
set dic = load pickle fp
close fp
comment to find rows in postings.txt
set diclen = length dic
comment initialise list for outputs to que... | def run_search(dict_file, postings_file, queries_file, results_file):
print('running search on the queries...')
# load in dictionary
fp = open(dict_file, 'rb')
dic = pickle.load(fp)
fp.close()
# to find rows in postings.txt
diclen = len(dic)
# initialise list for outputs to queri... | Python | nomic_cornstack_python_v1 |
function calcstep **args
begin
set begin = args at string begin
set end = args at string end
set step = args at string step
set sum = 0
for num in range begin end + 1 step
begin
set sum = sum + num
end
return sum
end function
print string 3 ~ 5 = call calcstep begin=3 end=5 step=1
print string 3 ~ 5 = call calcstep ste... | def calcstep(**args):
begin = args['begin']
end = args['end']
step = args['step']
sum = 0
for num in range(begin, end + 1, step):
sum += num
return sum
print("3 ~ 5 =", calcstep(begin=3, end=5, step=1))
print("3 ~ 5 =", calcstep(step=1, end=5, begin=3))
#print("3 ~ 5 =", calcstep(3, 5... | Python | zaydzuhri_stack_edu_python |
function test_fk_with_to_field self
begin
set modeladmin = call EmployeeAdmin Employee site
set request = get request_factory string / dict
set user = alfred
set changelist = call get_changelist_instance request
comment Make sure the correct queryset is returned
set queryset = call get_queryset request
assert equal lis... | def test_fk_with_to_field(self):
modeladmin = EmployeeAdmin(Employee, site)
request = self.request_factory.get("/", {})
request.user = self.alfred
changelist = modeladmin.get_changelist_instance(request)
# Make sure the correct queryset is returned
queryset = changelist... | Python | nomic_cornstack_python_v1 |
function serve self filename
begin
raise call NotImplementedError
end function | def serve(self, filename):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function _get_id self s
begin
comment Begin your code
try
begin
return str_to_id at s
end
except any
begin
comment increment the index id
set i = call __len__
set str_to_id at s = i
append id_to_str s
return i
end
end function
comment End your code | def _get_id(self, s):
### Begin your code
try:
return self.str_to_id[s]
except:
#increment the index id
i = self.__len__()
self.str_to_id[s] = i
self.id_to_str.append(s)
return i
### End your code | Python | nomic_cornstack_python_v1 |
function y self value
begin
if not is instance value int
begin
raise call TypeError string y must be an integer
end
if value < 0
begin
raise call ValueError string y must be >= 0
end
set __y = value
end function | def y(self, value):
if not isinstance(value, int):
raise TypeError("y must be an integer")
if value < 0:
raise ValueError("y must be >= 0")
self.__y = value | Python | nomic_cornstack_python_v1 |
comment title: design-twitter
comment detail: https://leetcode.com/submissions/detail/281819792/
comment datetime: Tue Nov 26 21:21:57 2019
comment runtime: 100 ms
comment memory: 22 MB
from collections import deque , defaultdict
import heapq
class Twitter
begin
set FEEDS_SIZE = 10
function __init__ self
begin
string I... | # title: design-twitter
# detail: https://leetcode.com/submissions/detail/281819792/
# datetime: Tue Nov 26 21:21:57 2019
# runtime: 100 ms
# memory: 22 MB
from collections import deque, defaultdict
import heapq
class Twitter:
FEEDS_SIZE = 10
def __init__(self):
"""
Initialize your data struct... | Python | zaydzuhri_stack_edu_python |
from random import randint
function graphDfs graph
begin
string Podział grafu na składowe spójne
string Algorytm wzorowany na algorytmie ze materiałów pomocniczych: https://eduinf.waw.pl/inf/alg/001_search/0129.php
set anchor_amount = 0
for anchor in graph
begin
set anchor_amount = anchor_amount + 1
end
set c = list 0 ... | from random import randint
def graphDfs(graph):
"""Podział grafu na składowe spójne"""
"""Algorytm wzorowany na algorytmie ze materiałów pomocniczych:
https://eduinf.waw.pl/inf/alg/001_search/0129.php"""
anchor_amount = 0
for anchor in graph:
anchor_amount += 1
c = [0] * anchor_amount... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
from view.bd import query
function run dict_config
begin
set numEnsaios = call getMAXofEnsaios dict_config at string experimento_id
set numCombinacoes = call getCombinacoes dict_config at s... | # coding: utf-8
# import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
from view.bd import query
def run(dict_config):
numEnsaios = query.getMAXofEnsaios(dict_config["experimento_id"])
numCombinacoes = query.getCombinacoes(dict_config["experimento_id"])
resultados = q... | Python | zaydzuhri_stack_edu_python |
function render_html self obj context=none
begin
string Generate the 'html' attribute of an oembed resource using a template. Sort of a corollary to the parser's render_oembed method. By default, the current mapping will be passed in as the context. OEmbed templates are stored in: oembed/provider/[app_label]_[model].ht... | def render_html(self, obj, context=None):
"""
Generate the 'html' attribute of an oembed resource using a template.
Sort of a corollary to the parser's render_oembed method. By default,
the current mapping will be passed in as the context.
OEmbed templates are stored in... | Python | jtatman_500k |
function AcquireMode self mode
begin
write self format string acquire:mode {} mode
end function | def AcquireMode(self, mode):
self.write("acquire:mode {}".format(mode)) | Python | nomic_cornstack_python_v1 |
function engage self flow
begin
raise call NotImplementedError string Trigger function 'engage' must be overridden
end function | def engage(self, flow):
raise NotImplementedError("Trigger function 'engage' must be overridden") | Python | nomic_cornstack_python_v1 |
string Read two integer values. After this, calculate the product between them and store the result in a variable named PROD.
set A = integer input
set B = integer input
set PROD = A * B
print string PROD = { PROD } | """
Read two integer values. After this, calculate the product between them and store the result in a variable named PROD.
"""
A = int(input())
B = int(input())
PROD = A*B
print(f'PROD = {PROD}') | Python | zaydzuhri_stack_edu_python |
comment Adds numbers to a list
set my_list = list
set count = 0
while count < 9
begin
set number = integer input string Enter a number for a list:
append my_list number
set count = count + 1
end
print string The list: my_list
comment Adds up the list
print string The sum: sum my_list
comment Gives the max of the list
... | #Adds numbers to a list
my_list = []
count = 0
while count < 9:
number = int(input('Enter a number for a list:\n'))
my_list.append(number)
count += 1
print('The list:',my_list)
#Adds up the list
print('The sum:',sum(my_list))
#Gives the max of the list
print('The maximum:',max(my_list))
#Gives the mini... | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
for j in range i
begin
print k end=string
set k = k + 1
end
print string
end | for i in range(n):
for j in range(i):
print(k, end='')
k +=1
print('')
| Python | zaydzuhri_stack_edu_python |
from fpdf import FPDF
from math import ceil
from definitions import *
class CellRenderer extends FPDF
begin
function __init__ self total_cells
begin
call __init__ orientation=string P unit=string mm format=string A4
call set_margins left=10 top=10 right=10
call set_auto_page_break auto=true margin=MARGIN
call add_page
... | from fpdf import FPDF
from math import ceil
from definitions import *
class CellRenderer(FPDF):
def __init__(self, total_cells):
super().__init__(orientation="P", unit="mm", format="A4")
self.set_margins(left=10, top=10, right=10)
self.set_auto_page_break(auto=True, margin=MARGIN)
self.add_page()
self.set_... | Python | zaydzuhri_stack_edu_python |
function forward_train self img forward_singleop_online idx=0 **kwargs
begin
assert dim img == 5 msg format string Input must have 5 dims, got: {} dim img
set v2_idx = shape at 1 // 2
set img_v1 = contiguous img at tuple slice : : idx Ellipsis
set img_v2 = contiguous img at tuple slice : : v2_idx + idx Ellipsis
i... | def forward_train(self, img, forward_singleop_online, idx=0, **kwargs):
assert img.dim() == 5, \
"Input must have 5 dims, got: {}".format(img.dim())
v2_idx = img.shape[1] // 2
img_v1 = img[:, idx, ...].contiguous()
img_v2 = img[:, v2_idx + idx, ...].contiguous()
if s... | Python | nomic_cornstack_python_v1 |
function phantom_ellipses n_points E
begin
comment Rescaling according to image size
comment semiaxis a
set E at tuple slice : : 0 = E at tuple slice : : 0 * n_points / 2
comment semiaxis b
set E at tuple slice : : 1 = E at tuple slice : : 1 * n_points / 2
comment x
set E at tuple slice : : 2 = E at tupl... | def phantom_ellipses(n_points,E):
#Rescaling according to image size
E[:,0] = E[:,0]*n_points/2 #semiaxis a
E[:,1] = E[:,1]*n_points/2 #semiaxis b
E[:,2] = E[:,2]*n_points/2 #x
E[:,3] = E[:,3]*n_points/2 #y
E[:,4] = E[:,4]*math.pi/180
x,y = np.meshgrid(np.arange(0,n_points)-n_poi... | Python | nomic_cornstack_python_v1 |
string MONTHS PROGRAM -------------- Write a user-input statement where a user enters a month number 1-13. Using the starting string below in your program, print the three month abbreviation for the month number that the user enters. Keep repeating this until the user enters 13 to quit. Once the user quits, print "Good... | '''
MONTHS PROGRAM
--------------
Write a user-input statement where a user enters a month number 1-13.
Using the starting string below in your program, print the three month abbreviation
for the month number that the user enters. Keep repeating this until the user enters 13 to quit.
Once the user quits, print "Goodby... | Python | zaydzuhri_stack_edu_python |
import sys
import os
function DirectoryWatcher Path
begin
set flag = call isabs Path
if flag == false
begin
set Path = absolute path path Path
end
print Path
set exist = is directory path Path
if exist == true
begin
for tuple foldername subfolder filename in walk Path
begin
print string Folder Names: + foldername
for s... | import sys
import os
def DirectoryWatcher(Path):
flag=os.path.isabs(Path)
if flag== False:
Path=os.path.abspath(Path)
print(Path)
exist=os.path.isdir(Path)
if exist==True:
for foldername,subfolder,filename in os.walk(Path):
print("Folder Names: "+foldername)
... | Python | zaydzuhri_stack_edu_python |
comment COEN424 Assignment 1
comment Constantine Karellas - 40109253
comment Michael Arabian - 40095854
from flask import Flask , request , make_response
from requests.api import get
from werkzeug.wrappers import response
import request_pb2
import response_pb2
import json
import csv
set app = call Flask __name__
commen... | #COEN424 Assignment 1
#Constantine Karellas - 40109253
#Michael Arabian - 40095854
from flask import Flask, request, make_response
from requests.api import get
from werkzeug.wrappers import response
import request_pb2
import response_pb2
import json
import csv
app = Flask(__name__)
#location of the files in the repo... | Python | zaydzuhri_stack_edu_python |
function type self
begin
return _type
end function | def type(self):
return self._type | Python | nomic_cornstack_python_v1 |
class Solution
begin
function flipAndInvertImage self A
begin
string :type A: List[List[int]] :rtype: List[List[int]]
if A == list
begin
return A
end
for index in A
begin
reverse index
for i in range length index
begin
set index at i = 1 - index at i
end
end
return A
end function
end class
if __name__ == string __main... | class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
if A==[]:
return A
for index in A:
index.reverse()
for i in range(len(index)):
index[i]=1-index[i]
ret... | Python | zaydzuhri_stack_edu_python |
function test_auth_apiexception self mocker
begin
set api_mock = call Mock
set side_effect = call APIException string something
set sse_mock = call Mock spec=SplitSSEClient
set sse_constructor_mock = call Mock
set return_value = sse_mock
set timer_mock = call Mock
patch string splitio.push.manager.Timer new=timer_mock
... | def test_auth_apiexception(self, mocker):
api_mock = mocker.Mock()
api_mock.authenticate.side_effect = APIException('something')
sse_mock = mocker.Mock(spec=SplitSSEClient)
sse_constructor_mock = mocker.Mock()
sse_constructor_mock.return_value = sse_mock
timer_mock = moc... | Python | nomic_cornstack_python_v1 |
string 包 在day01中创建两个包,然后在每个包中创建一个m0x的文件 在每个文件中创建一个函数,然后调用 导入是否成功的条件: 系统路径(sys.path)+ 导入路径 == 真实路径
comment 导入方式 1 :import 路径.模块名 as 别名
comment 使用:别名.成员
string import package01.m01 as m # import package01.package02.m02 as m2 # m2.fun02() m.fun01()
comment 导入方式 2 : from 路径.模块名 import 成员
string from package01.package02.m02... | """
包
在day01中创建两个包,然后在每个包中创建一个m0x的文件
在每个文件中创建一个函数,然后调用
导入是否成功的条件:
系统路径(sys.path)+ 导入路径 == 真实路径
"""
# 导入方式 1 :import 路径.模块名 as 别名
# 使用:别名.成员
"""import package01.m01 as m
# import package01.package02.m02 as m2
# m2.fun02()
m.fun01()"""
# 导入方式 2 : from 路径.模块名 import 成员
"""from package01.package02.m02 imp... | Python | zaydzuhri_stack_edu_python |
function test_husb_older self
begin
set test = call husb_marr_after_14 fam at 0 fam at 1 at string F01
assert true test
end function | def test_husb_older(self):
test = marr_after_14.husb_marr_after_14(self.fam[0], self.fam[1]['F01'])
self.assertTrue(test) | Python | nomic_cornstack_python_v1 |
comment To search and edit substitution per site rate files for input into mathematica.
import sys
import re
import os | #To search and edit substitution per site rate files for input into mathematica.
import sys
import re
import os
| Python | zaydzuhri_stack_edu_python |
import numpy as np
comment Input data
set math = 84
set english = 89
set biology = 82
comment Define weights
set math_weight = 0.3
set english_weight = 0.4
set biology_weight = 0.3
comment Compute weighted sum
set grade = math * math_weight + english * english_weight + biology * biology_weight
comment Print the grade
p... | import numpy as np
# Input data
math = 84
english = 89
biology = 82
# Define weights
math_weight = 0.3
english_weight = 0.4
biology_weight = 0.3
# Compute weighted sum
grade = math * math_weight + english * english_weight + biology * biology_weight
# Print the grade
print('Mia\'s grade is: {:.2f}'.format(grade)) | Python | iamtarun_python_18k_alpaca |
comment Function 1:
comment No arguments defined
comment Should ask to the user the number of elements in the list
comment According the value inserted ask for each value of the array and push it in a new array
comment Return the array
print string ---------------- FUNCTION ONE ----------------
function askElements
beg... | # Function 1:
# No arguments defined
# Should ask to the user the number of elements in the list
# According the value inserted ask for each value of the array and push it in a new array
# Return the array
print('---------------- FUNCTION ONE ----------------')
def askElements():
print("Insert the quantity of el... | Python | zaydzuhri_stack_edu_python |
function handle_div self tag attrs
begin
if string div in stack
begin
comment self.errmsg('warning: nested <div> tags detected', 0)
pass
end
end function | def handle_div(self, tag, attrs):
if 'div' in self.stack:
# self.errmsg('warning: nested <div> tags detected', 0)
pass | Python | nomic_cornstack_python_v1 |
from pylab import *
set number = decimal input string Give me a number:
if number < 0
begin
print string Don't be so negative!
end
else
begin
print string Glad to see you're feeling non-negative!
end | from pylab import *
number = float(input("Give me a number: "))
if number < 0:
print("Don't be so negative!")
else:
print("Glad to see you're feeling non-negative!")
| Python | zaydzuhri_stack_edu_python |
function testCheckReplaceOperation self
begin
set payload_checker = call PayloadChecker call MockPayload
set block_size = block_size
set data_length = 10000
set op = call CreateMock InstallOperation
set type = REPLACE
comment Pass.
set src_extents = list
assert is none call _CheckReplaceOperation op data_length data_l... | def testCheckReplaceOperation(self):
payload_checker = checker.PayloadChecker(self.MockPayload())
block_size = payload_checker.block_size
data_length = 10000
op = self.mox.CreateMock(
update_metadata_pb2.InstallOperation)
op.type = common.OpType.REPLACE
# Pass.
op.src_extents = []
... | Python | nomic_cornstack_python_v1 |
comment %%
class Point
begin
comment place holder
pass
end class
set p1 = call Point
set p2 = call Point
print p1
print p1 p2
print type p1
print type p2
comment %%
class Point
begin
comment bez ustawiania parametrów na wejściu
function __init__ self
begin
set x = 0
set y = 0
end function
end class
comment powstaje pun... | # %%
##
class Point:
pass # place holder
p1 = Point()
p2 = Point()
print(p1)
print(p1, p2)
print(type(p1))
print(type(p2))
# %%
##
class Point:
def __init__(self): # bez ustawiania parametrów na wejściu
self.x = 0
self.y = 0
p1 = Point() # powstaje punkt o współrzędnych domyślnych
p2 = ... | Python | zaydzuhri_stack_edu_python |
function create_path path
begin
string Creates a absolute path in the file system. :param path: The path to be created
import os
if not exists path path
begin
make directories path
end
end function | def create_path(path):
"""Creates a absolute path in the file system.
:param path: The path to be created
"""
import os
if not os.path.exists(path):
os.makedirs(path) | Python | jtatman_500k |
string Project 3 (Fall 2020) - Red/Black Trees Name: Jeffrey Valentic Professor Onsay 10/27/2020
from __future__ import annotations
from typing import TypeVar , Generic , Callable , Generator
from Project3.RBnode import RBnode as Node
from copy import deepcopy
import queue
set T = call TypeVar string T
class RBtree
beg... | """
Project 3 (Fall 2020) - Red/Black Trees
Name: Jeffrey Valentic
Professor Onsay
10/27/2020
"""
from __future__ import annotations
from typing import TypeVar, Generic, Callable, Generator
from Project3.RBnode import RBnode as Node
from copy import deepcopy
import queue
T = TypeVar('T')
class RBtree:
"""
A ... | Python | zaydzuhri_stack_edu_python |
function __init__ self udisks
begin
set log = call getLogger string udiskie.daemon.Daemon
set state = dict
set udisks = udisks
set event_handlers = dict string device_added list ; string device_removed list ; string device_mounted list ; string device_unmounted list ; string media_added list ; string media_remove... | def __init__(self, udisks):
self.log = logging.getLogger('udiskie.daemon.Daemon')
self.state = {}
self.udisks = udisks
self.event_handlers = {
'device_added': [],
'device_removed': [],
'device_mounted': [],
'device_unmounted': [],
... | Python | nomic_cornstack_python_v1 |
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , Dropout
comment Generate data
set X = call rand 100 5
set y = random integer 2 size=100
comment Split data into training and testing sets
set tuple X_train X... | import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
# Generate data
X = np.random.rand(100, 5)
y = np.random.randint(2, size=100)
# Split data into training and testing sets
X_train, X_test, y_train, ... | Python | jtatman_500k |
function getProductWriter self
begin
return call ProductWriter call FlagCoding_getProductWriter _obj
end function | def getProductWriter(self):
return ProductWriter(FlagCoding_getProductWriter(self._obj)) | Python | nomic_cornstack_python_v1 |
comment 二叉树的最近公共祖先
comment 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
comment 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
comment 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
comment _______3______
comment / \
comment ___5__ ___1__
comment / \ / \
comment 6 _2 0 8
comment / \
co... | # 二叉树的最近公共祖先
# 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
#
# 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
#
# 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
#
# _______3______
# / \
# ___5__ ___1__
# / \ / \
# 6 ... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function placeWordInCrossword self board word
begin
set dirs = list list 0 1 list 0 - 1 list 1 0 list - 1 0
set tuple m n = tuple length board length board at 0
function inRange x y
begin
return x >= 0 and y >= 0 and x < m and y < n
end function
function isValid x y
begin
if call inRange x y
begin
... | class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
dirs = [[0,1],[0,-1],[1,0],[-1,0]]
m, n = len(board), len(board[0])
def inRange(x, y):
return x>=0 and y>=0 and x<m and y<n
def isValid(x, y):
... | Python | zaydzuhri_stack_edu_python |
function merge_and_find_sync_loops self
begin
comment Sanity check if it is mergable
if loop_infos == none or length loop_infos <= 1
begin
debug string It is not mergable
return list
end
comment NxN merge
set loop_mg_infos = list
set all_merged = true
for loop_i in loop_infos
begin
for loop_j in loop_infos
begin
if l... | def merge_and_find_sync_loops(self):
# Sanity check if it is mergable
if self.loop_infos == None or len(self.loop_infos) <= 1:
log.debug("It is not mergable")
return []
# NxN merge
loop_mg_infos = []
all_merged = True
for loop_i in self.loop_infos:... | Python | nomic_cornstack_python_v1 |
class Player extends object
begin
function __init__ self
begin
set x = 2
set y = 2
set inventory = list
set solved_dict = dict string 1 string n ; string 2 string n ; string 3 string n ; string 4 string n ; string 5 string y ; string 6 string y ; string 7 string n ; string 8 string n ; string 9 string n
end function
f... | class Player(object):
def __init__(self):
self.x = 2
self.y = 2
self.inventory = []
self.solved_dict = {"1":"n", "2":"n", "3":"n", "4":"n", "5":"y", "6":"y", "7":"n", "8":"n", "9":"n"}
def map(self):
#This function returns the user x y position
return(self.x, se... | Python | zaydzuhri_stack_edu_python |
function test_start_date_handling self
begin
comment The course home page should 404 for a course starting in the future
set future_course = call create_future_course call datetime 2030 1 1 tzinfo=UTC
set url = call course_home_url future_course
set response = get client url
call assertRedirects response string /dashbo... | def test_start_date_handling(self):
# The course home page should 404 for a course starting in the future
future_course = self.create_future_course(datetime(2030, 1, 1, tzinfo=UTC))
url = course_home_url(future_course)
response = self.client.get(url)
self.assertRedirects(response... | Python | nomic_cornstack_python_v1 |
function setup_virtualenv
begin
call sudo string mkdir -p /home/adage/.virtualenvs user=string adage
call sudo string virtualenv /home/adage/.virtualenvs/adage user=string adage
end function
comment TODO add 'act' alias here
comment alias act='source ~/.virtualenvs/adage/bin/activate' | def setup_virtualenv():
sudo('mkdir -p /home/adage/.virtualenvs', user='adage')
sudo('virtualenv /home/adage/.virtualenvs/adage', user='adage')
# TODO add 'act' alias here
# alias act='source ~/.virtualenvs/adage/bin/activate' | Python | nomic_cornstack_python_v1 |
from behave import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import time
import utilities
decorator call given string we are logged in as {name}
comment course_uuid = {
comment 'Defense Against The Dar... | from behave import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import time
import utilities
# course_uuid = {
# 'Defense Against The Dark Arts': 'ab102e97-e312-49e1-a352-56237e834854',
# 'CSE210'... | Python | zaydzuhri_stack_edu_python |
import os
import json
from sfml.graphics import Texture , Image , Font
set IMAGE_FILE = string image
set TEXTURE_FILE = string texture
set FONT_FILE = string font
set TYPE_KEY = string type
set INDEX_KEY = string index
set LOCATION_KEY = string location
set SETTING_KEY = string setting
class ResourceManager extends obj... | import os
import json
from sfml.graphics import Texture, Image, Font
IMAGE_FILE = "image"
TEXTURE_FILE = "texture"
FONT_FILE = "font"
TYPE_KEY = "type"
INDEX_KEY = "index"
LOCATION_KEY = "location"
SETTING_KEY = "setting"
class ResourceManager(object):
def __init__(self, index_file):
super(ResourceMan... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment projet 2 chapitre 8 : automateTheBoringStuffsWithPython
import shelve , sys , pyperclip
set mcbShelf = open string mcb
if length argv == 3
begin
if lower argv at 1 == string save
begin
set mcbShelf at argv at 2 = call paste
end
else
if lower argv at 1 == string delete
begin
del mcbShe... | #! /usr/bin/python3
#projet 2 chapitre 8 : automateTheBoringStuffsWithPython
import shelve, sys, pyperclip
mcbShelf = shelve.open('mcb')
if len(sys.argv) == 3:
if sys.argv[1].lower() == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()
elif sys.argv[1].lower() == 'delete':
del mcbShelf[sys.argv... | Python | zaydzuhri_stack_edu_python |
async function _close_db self app
begin
terminate app at string db
await call wait_closed
end function | async def _close_db(self, app):
app['db'].terminate()
await app['db'].wait_closed() | Python | nomic_cornstack_python_v1 |
comment 多个函数之间共享数据的操作
comment 1. 使用全局变量
comment 2. 返回值
comment 定义全局变量
set g_num = 0
function modify_value
begin
global g_num
set g_num = 10
print string modify_value函数 全局变量修改后的数据为: g_num
end function
function show
begin
print string show函数 访问全局变量: g_num
end function
call modify_value
show
comment 函数的返回值,可以在不同函数之间共享数据 -... | # 多个函数之间共享数据的操作
# 1. 使用全局变量
# 2. 返回值
# 定义全局变量
g_num = 0
def modify_value():
global g_num
g_num = 10
print("modify_value函数 全局变量修改后的数据为:", g_num)
def show():
print("show函数 访问全局变量:", g_num)
modify_value()
show()
# 函数的返回值,可以在不同函数之间共享数据 -----------
def return_value():
msg = "hello"
return... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.