code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function part_1 begin set atoi = dict string 0 0 ; string 1 1 ; string 2 2 ; string 3 3 ; string 4 4 ; string 5 5 ; string 6 6 ; string 7 7 ; string 8 8 ; string 9 9 function parse_number number begin set tuple sign unsign = tuple number at 0 number at slice 1 : : set unsign = replace unsign string string set unsign...
def part_1(): atoi = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } def parse_number(number): sign, unsign = number[0], number[1:] unsign = unsign.replace("\n", "") u...
Python
zaydzuhri_stack_edu_python
function providerprofile_image_list request format=none begin set user = none if method == string GET begin set images = all set serializer = call ImageSerializer images many=true return call Response data end set error_response = string Method is not GET. return call Response data=error_response status=HTTP_400_BAD_RE...
def providerprofile_image_list(request, format=None): user = None if request.method == 'GET': images = Image.objects.all() serializer = ImageSerializer(images, many=True) return Response(serializer.data) error_response = "Method is not GET." return Response(data=error_respon...
Python
nomic_cornstack_python_v1
function _get_item_id_for_upgrade self package_items option value public=true begin set vs_id = dict string memory 3 ; string cpus 80 ; string nic_speed 26 for item in package_items begin for j in range length item at string categories begin if not item at string categories at j at string id == vs_id at option and item...
def _get_item_id_for_upgrade(self, package_items, option, value, public=True): vs_id = {'memory': 3, 'cpus': 80, 'nic_speed': 26} for item in package_items: for j in range(len(item['categories'])): if not (item['categories'][j]['id'] == v...
Python
nomic_cornstack_python_v1
function assign_io_rev_costs_crops x cost_dataframe rice_prod_file crop_month_fields province x_cols ex_rate begin comment find the crop production months for the province set rice_prod_months = call read_file rice_prod_file set rice_prod_months = loc at SUB_REGION == province set rice_prod_months = call tolist set ric...
def assign_io_rev_costs_crops(x, cost_dataframe,rice_prod_file,crop_month_fields,province, x_cols, ex_rate): # find the crop production months for the province rice_prod_months = gpd.read_file(rice_prod_file) rice_prod_months = rice_prod_months.loc[rice_prod_months.SUB_REGION == province] rice_prod_mont...
Python
nomic_cornstack_python_v1
import math set T = integer input for _ in range T begin set N = integer input set root = integer square root 4 + 4 * N / 2 - 1 print string Case %d: %d % tuple _ + 1 root end
import math T = int(input()) for _ in range(T): N = int(input()) root = int(math.sqrt(4 + 4 * N) / 2)- 1 print('Case %d: %d' %(_ + 1, root))
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self data begin set data = data set next = none end function end class function print_linked_list linked_list begin set p = linked_list print string head end=string while p != none begin print string ( + string data + string )-> end=string set p = next end print string None end functi...
class Node: def __init__(self, data): self.data = data self.next = None def print_linked_list(linked_list): p = linked_list print("head", end='') while p != None: print("(" + str(p.data) + ")->", end='') p = p.next print("None") head = Node(1...
Python
zaydzuhri_stack_edu_python
function jssettings self begin update self return string var %s = %s % tuple js_var_settings_name dumps settings end function
def jssettings(self): self.update() return "var %s = %s" % (self.js_var_settings_name, json.dumps(self.settings))
Python
nomic_cornstack_python_v1
function announcement_approved_email request obj req begin string Email the requested teachers and submitter whenever an administrator approves an announcement request. obj: the Announcement object req: the AnnouncementRequest object if not PRODUCTION begin debug string Not in production. Ignoring email for approved an...
def announcement_approved_email(request, obj, req): """Email the requested teachers and submitter whenever an administrator approves an announcement request. obj: the Announcement object req: the AnnouncementRequest object """ if not settings.PRODUCTION: logger.debug("Not in productio...
Python
jtatman_500k
function delete_dhcp_binding self edge_id binding_id begin set uri = call _build_uri_path edge_id DHCP_SERVICE DHCP_BINDING_RESOURCE binding_id return call do_request HTTP_DELETE uri decode=false end function
def delete_dhcp_binding(self, edge_id, binding_id): uri = self._build_uri_path(edge_id, DHCP_SERVICE, DHCP_BINDING_RESOURCE, binding_id) return self.do_request(HTTP_DELETE, uri, decode=False)
Python
nomic_cornstack_python_v1
function base64_encode_str str_val begin return decode base64 encode encode str_val string utf-8 string utf-8 end function
def base64_encode_str(str_val: str) -> str: return b64encode(str_val.encode('utf-8')).decode('utf-8')
Python
nomic_cornstack_python_v1
comment ****************06.Easter Decoration (nested loop) *************************** set customers = integer input set total = 0 for customer in range 1 customers + 1 begin set purchase = input set purchases = 0 set spent = 0 while not purchase == string Finish begin set purchases = purchases + 1 if purchase == strin...
# ****************06.Easter Decoration (nested loop) *************************** customers = int(input()) total = 0 for customer in range(1, customers + 1): purchase = input() purchases = 0 spent = 0 while not purchase == 'Finish': purchases += 1 if purchase == 'basket': ...
Python
zaydzuhri_stack_edu_python
function generate_variable_names begin while true begin set name = uuid 4 yield string _ { hex } end end function
def generate_variable_names(): while True: name = uuid.uuid4() yield f"_{name.hex}"
Python
nomic_cornstack_python_v1
function list_entry_delete_request self entry_type quarantine_type view_by recipient_list=none sender_list=none begin set data = call assign_params quarantineType=quarantine_type recipientList=recipient_list senderList=sender_list viewBy=view_by return call _http_request string DELETE string quarantine/ { entry_type } ...
def list_entry_delete_request( self, entry_type: str, quarantine_type: str, view_by: str, recipient_list: List[str] = None, sender_list: List[str] = None, ) -> Dict[str, Any]: data = assign_params( quarantineType=quarantine_type, recipi...
Python
nomic_cornstack_python_v1
comment Quirality of the triangle changed in relation to try1.py import figgus as f set n = 4 set grains = list call UnitGrain call UnitGrain call UnitGrain call UnitGrain set s = call Sequence grains for i in call xrange n begin set freq = 10000 - 1000 * i + 1 set duration = 0.2 + 0.05 * i end comment print 100*(i+1) ...
# Quirality of the triangle changed in relation to try1.py import figgus as f n=4 grains=[f.UnitGrain(),f.UnitGrain(),f.UnitGrain(),f.UnitGrain()] s=f.Sequence(grains) for i in xrange(n): s.ordered_unit_grains[i].freq=10000 - 1000*(i+1) s.ordered_unit_grains[i].duration=.2 + 0.05*i #print 100*(i+1) s....
Python
zaydzuhri_stack_edu_python
import math function distance p1 p2 begin set tuple x1 y1 = p1 set tuple x2 y2 = p2 set d = square root x2 - x1 ^ 2 + y2 - y1 ^ 2 return d end function set tuple x1 y1 = tuple 5 3 set tuple x2 y2 = tuple 2 2 print string The distance between 2 points ( { x1 } , { y1 } ) & ( { x2 } , { y2 } ) is: { distance tuple x1 y1 ...
import math def distance(p1,p2): x1,y1 = p1 x2,y2 = p2 d = math.sqrt((x2-x1)**2+(y2-y1)**2) return d x1,y1 = (5,3) x2,y2 = (2,2) print(f"The distance between 2 points ({x1},{y1}) & ({x2},{y2}) is: {distance((x1,y1),(x2,y2))}")
Python
flytech_python_25k
function set_permissions self perm_spec begin if string authenticated in perm_spec begin call set_gen_level AUTHENTICATED_USERS perm_spec at string authenticated end if string anonymous in perm_spec begin call set_gen_level ANONYMOUS_USERS perm_spec at string anonymous end if is instance perm_spec at string users dict ...
def set_permissions(self, perm_spec): if "authenticated" in perm_spec: self.set_gen_level(AUTHENTICATED_USERS, perm_spec['authenticated']) if "anonymous" in perm_spec: self.set_gen_level(ANONYMOUS_USERS, perm_spec['anonymous']) if isinstance(perm_spec['users'], dict)...
Python
nomic_cornstack_python_v1
function unit_of_measurement self begin if zone_variable == string temperature begin return temperature_unit end if zone_variable == string humidity begin return UNIT_PERCENTAGE end if zone_variable == string heating begin return UNIT_PERCENTAGE end if zone_variable == string ac begin return none end end function
def unit_of_measurement(self): if self.zone_variable == "temperature": return self.hass.config.units.temperature_unit if self.zone_variable == "humidity": return UNIT_PERCENTAGE if self.zone_variable == "heating": return UNIT_PERCENTAGE if self.zone_va...
Python
nomic_cornstack_python_v1
function __init__ __self__ id=none begin if id is not none begin set __self__ string id id end end function
def __init__(__self__, *, id: Optional[str] = None): if id is not None: pulumi.set(__self__, "id", id)
Python
nomic_cornstack_python_v1
function aggregation_node2vec_cmd begin set name = open string ./data/name.csv set df_name = read csv name set f = open string ./data/aggregation/node2vec/edgelist_node/node2vec_cmd.txt string w for i in range length df_name begin set name_ = df_name at string name_node_pairs at i write f format string python -m openne...
def aggregation_node2vec_cmd(): name = open('./data/name.csv') df_name = pd.read_csv(name) f = open('./data/aggregation/node2vec/edgelist_node/node2vec_cmd.txt', 'w') for i in range(len(df_name)): name_ = df_name['name_node_pairs'][i] f.write('python -m openne --method node2vec --input d...
Python
nomic_cornstack_python_v1
import os import time import numpy as np import pandas as pd from collections import defaultdict from tqdm import tqdm import matplotlib.pyplot as plt comment Turn interactive plotting off call ioff from utilities import * class CityResidents begin function __init__ self city_num city_code x_size y_size residents_num i...
import os import time import numpy as np import pandas as pd from collections import defaultdict from tqdm import tqdm import matplotlib.pyplot as plt # Turn interactive plotting off plt.ioff() from utilities import * class CityResidents: def __init__(self, city_num, city_code, x_size, y_size, residents_num, in...
Python
zaydzuhri_stack_edu_python
function is_colliding self pos radius begin if fallen begin comment can't collide with fallen trees - they're gone return false end if call overlaps pos radius + r begin return true end else begin return false end end function
def is_colliding(self, pos, radius): if self.fallen: # can't collide with fallen trees - they're gone return False if self.overlaps(pos, radius + self.r): return True else: return False
Python
nomic_cornstack_python_v1
function _width_extraction_fn cls begin return width_fn_pandas end function
def _width_extraction_fn(cls): return width_fn_pandas
Python
nomic_cornstack_python_v1
function calculate_median nums begin comment Sort the set in ascending order sort nums set n = length nums comment Even length if n % 2 == 0 begin set mid1 = n // 2 set mid2 = mid1 - 1 return nums at mid1 + nums at mid2 / 2 end else begin comment Odd length set mid = n // 2 return nums at mid end end function
def calculate_median(nums): nums.sort() # Sort the set in ascending order n = len(nums) if n % 2 == 0: # Even length mid1 = n // 2 mid2 = mid1 - 1 return (nums[mid1] + nums[mid2]) / 2 else: # Odd length mid = n // 2 return nums[mid]
Python
jtatman_500k
function mm begin while true begin set user_in = decimal input string mm: if user_in == 0 begin break end print string inches: user_in / 25.4 end end function if __name__ == string __main__ begin call mm end
def mm(): while True: user_in = float(input('mm: ')) if user_in == 0: break print("inches: ", user_in / 25.4) if __name__ == "__main__": mm()
Python
zaydzuhri_stack_edu_python
function ban user begin call sendMessageToChat format string .ban {} user end function
def ban(user): self.sendMessageToChat(".ban {}".format(user))
Python
nomic_cornstack_python_v1
import hashlib comment Python's hashing functions require binary values function digest_hash data begin set m = call digest return m end function comment if __name__ == '__main__': comment data = b"Hello World!" comment hashedData = digest_hash(data) comment print(hashedData) comment data = data + hashedData comment pr...
import hashlib # Python's hashing functions require binary values def digest_hash(data): m = hashlib.sha1(bin(data).encode()).digest() return m # if __name__ == '__main__': # data = b"Hello World!" # hashedData = digest_hash(data) # print(hashedData) # data = data + hashedData # print(data)
Python
zaydzuhri_stack_edu_python
from py2neo import Graph import time from lru import LRU class Node extends object begin function __init__ self type_id node_type id_s fiscal_code relevant_terms region province city address istat_code adm_code name company_type nation begin set type_id = type_id set node_type = node_type set id = id_s set fiscal_code ...
from py2neo import Graph import time from lru import LRU class Node(object): def __init__(self, type_id, node_type, id_s, fiscal_code, relevant_terms, region, province, city, address, istat_code, adm_code, name, company_type, nation): self.type_id = type_id self.node_type = node_type ...
Python
zaydzuhri_stack_edu_python
import unittest from src.models.models import User class TestUserLogin extends TestCase begin function setUp self begin set __user = call User string user_id string user_name end function function test_should_set_correct_user_login self begin assert equal user_id string user_id string Wrong User Id assert equal name st...
import unittest from src.models.models import User class TestUserLogin(unittest.TestCase): def setUp(self): self.__user = User('user_id', 'user_name') def test_should_set_correct_user_login(self): self.assertEqual(self.__user.user_id, "user_id", "Wrong User Id") self.assertEqual(self...
Python
zaydzuhri_stack_edu_python
comment ! python3 comment open_notify.py - An exercise in learning about APIs with Python using NASA's comment Open Notify API comment https://medium.com/quick-code/absolute-beginners-guide-to-slaying-apis-using-python-7b380dc82236 import requests comment Will start with NASA's http://open-notify.org/ set request = get...
#! python3 # open_notify.py - An exercise in learning about APIs with Python using NASA's # Open Notify API # https://medium.com/quick-code/absolute-beginners-guide-to-slaying-apis-using-python-7b380dc82236 import requests # Will start with NASA's http://open-notify.org/ request = requests.get('http://api.open-notif...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , request , redirect , session , flash from mysqlconnection import connectToMySQL import re set app = call Flask __name__ set secret_key = string secret email set mysql = call connectToMySQL string email_validation set EMAIL_REGEX = compile string ^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._...
from flask import Flask, render_template, request, redirect, session, flash from mysqlconnection import connectToMySQL import re app = Flask(__name__) app.secret_key = 'secret email' mysql = connectToMySQL("email_validation") EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.route('/')...
Python
zaydzuhri_stack_edu_python
function trim_sample seq begin debug string Trim sample. set config = call Configuration set scores = call asarray letter_annotations at string phred_quality set median = decimal call nanmedian scores if median < threshold begin set message = string The median Phred quality ( { median } ) is below the required threshol...
def trim_sample(seq: SeqRecord) -> (int, SeqRecord, array, int, float): logger.debug("Trim sample.") config = Configuration() scores = asarray(seq.letter_annotations["phred_quality"]) median = float(nanmedian(scores)) if median < config.threshold: message = ( f"The median Phred q...
Python
nomic_cornstack_python_v1
function test_basicResponse self begin set response = call successResultOf get call StubTreq call resource string https://example.com/set/headers assert equal code 209 assert equal call getRawHeaders b'X-Single-Header' list b'one' assert equal call getRawHeaders b'X-Multi-Header' list b'two' b'three' end function
def test_basicResponse(self) -> None: response = self.successResultOf( StubTreq(router.resource()).get( "https://example.com/set/headers", ) ) self.assertEqual(response.code, 209) self.assertEqual( response.headers.getRawHeaders(b"X-Sin...
Python
nomic_cornstack_python_v1
for i in range n begin set d = input if is alpha d begin set t = t + tuple d end else begin set t = t + tuple eval d end end print t
for i in range(n): d = input() if d.isalpha(): t+=(d,) else: t+=(eval(d),) print(t)
Python
zaydzuhri_stack_edu_python
function fizzbuzz number begin if number % 15 == 0 begin return string fizzbuzz end else if number % 5 == 0 begin return string buzz end else if number % 3 == 0 begin return string fizz end else begin return string number end end function while inputNumber < 1 or inputNumber > 100 begin set inputNumber = integer input ...
def fizzbuzz(number): if number % 15 == 0: return "fizzbuzz" elif number % 5 == 0: return "buzz" elif number % 3 == 0: return "fizz" else: return str(number) while inputNumber < 1 or inputNumber > 100: inputNumber = int(input("Select number between 1 and 100: ")) fo...
Python
zaydzuhri_stack_edu_python
function administrator_login self begin return get pulumi self string administrator_login end function
def administrator_login(self) -> str: return pulumi.get(self, "administrator_login")
Python
nomic_cornstack_python_v1
function solvemodel gurobi_model begin try begin update gurobi_model write gurobi_model string haraka.lp call optimize end except GurobiError begin print string Error when solving! print GurobiError end return gurobi_model end function
def solvemodel(gurobi_model): try: gurobi_model.update() gurobi_model.write('haraka.lp') gurobi_model.optimize() except GurobiError: print("Error when solving!") print(GurobiError) return gurobi_model
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torch.nn.functional as F function conv3x3 in_channels out_channels stride=1 begin return conv 2d in_channels out_channels kernel_size=3 stride=stride padding=1 bias=false end function class ResidualBlock extends Module begin function __init__ self in_channels out_channels strid...
import torch import torch.nn as nn import torch.nn.functional as F def conv3x3(in_channels, out_channels, stride=1): return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channels, stride=1, downsa...
Python
zaydzuhri_stack_edu_python
function V self begin return word_types end function
def V(self): return self.word_types
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Oct 1 17:47:46 2020 @author: hemma import numpy as np print string I'll think of a number between 1 and 20 and you guess what it is set randNum = random integer 1 20 set numRounds = 0 set foundNum = false while foundNum == false begin set...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 1 17:47:46 2020 @author: hemma """ import numpy as np print("I'll think of a number between 1 and 20 and you guess what it is") randNum = np.random.randint(1, 20) numRounds = 0 foundNum = False while foundNum == False: guessed = int(input("P...
Python
zaydzuhri_stack_edu_python
function show_user_post_form user_id begin set user = call get_or_404 user_id return call render_template string add-post-user.html user=user end function
def show_user_post_form(user_id): user = User.query.get_or_404(user_id) return render_template('add-post-user.html', user=user)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import random import time set compare_counter = 0 set swap_counter = 0 function swap x i j begin set tuple x at i x at j = tuple x at j x at i end function function pivotFirst x lmark rmark begin set pivot_val = x at lmark set pivot_idx = lmark while lmark <= rmark begin while lmark <= rmark an...
#!/usr/bin/python import random import time compare_counter=0 swap_counter=0 def swap(x,i,j): x[i],x[j]=x[j],x[i] def pivotFirst(x,lmark,rmark): pivot_val=x[lmark] pivot_idx=lmark while lmark<=rmark: while lmark <= rmark and x[lmark]<=pivot_val: lmark+=1 while lmark <=rmar...
Python
zaydzuhri_stack_edu_python
comment %% import cv2 import numpy as np comment %% comment Read data with open string ../input/input_question_4 string r as f begin set data = read f end comment Transform str data to float data set bin_data = list for row in split data string at slice : - 1 : begin append bin_data list comprehension decimal p for ...
# %% import cv2 import numpy as np # %% # Read data with open('../input/input_question_4', 'r') as f: data = f.read() # Transform str data to float data bin_data = [] for row in data.split('\n')[:-1]: bin_data.append([float(p) for p in row.split()]) # Transform float data to uint8 bin_data = np.array...
Python
zaydzuhri_stack_edu_python
function read_file file_name begin comment open the file passed in with open file_name newline=string as csvfile begin comment in read mode set reader = reader csvfile delimiter=string set molecules = list set labels = list set i = 0 for row in reader begin set i = i + 1 comment Split on only the first column, separa...
def read_file(file_name): # open the file passed in with open(file_name, newline='') as csvfile: # in read mode reader = csv.reader(csvfile, delimiter=' ') molecules = [] labels = [] i=0 for row in reader: i+=1 # Split on only the first col...
Python
nomic_cornstack_python_v1
function divisor n begin set tuple lower upper = tuple list list set i = 1 while i * i <= n begin if n % i == 0 begin append lower i if i != n // i begin append upper n // i end end set i = i + 1 end return lower + upper at slice : : - 1 end function set cnt = 0 for i in call divisor S begin set a1 = S / i + i - 1 ...
def divisor(n): lower, upper = [], [] i = 1 while i*i <= n: if n % i == 0: lower.append(i) if i != n // i: upper.append(n//i) i += 1 return lower + upper[::-1] cnt = 0 for i in divisor(S): a1 = (S/i)+(i-1)/2 if a1.is_integer(): cnt +...
Python
zaydzuhri_stack_edu_python
function load_model program_name model_context aliases filter_type wlst_mode validate_crd_sections=true begin set _method_name = string load_model set variable_map = dict end function
def load_model(program_name, model_context, aliases, filter_type, wlst_mode, validate_crd_sections=True): _method_name = 'load_model' variable_map = {}
Python
nomic_cornstack_python_v1
function rotate self angle axis begin string Rotate the matrix by some angle about a given axis. The rotation is applied *after* the transformations already present in the matrix. Parameters ---------- angle : float The angle of rotation, in degrees. axis : array-like The x, y and z coordinates of the axis vector to ro...
def rotate(self, angle, axis): """ Rotate the matrix by some angle about a given axis. The rotation is applied *after* the transformations already present in the matrix. Parameters ---------- angle : float The angle of rotation, in degrees. a...
Python
jtatman_500k
function test_frontend_following_like_emoji_twice_post self begin comment Create a second user set new_user = call create_user username=string 1 password=string 1 comment Follow the user call create user=user user_followed=new_user comment Creat a post set new_post = call create user=new_user content=string Lorem ipsum...
def test_frontend_following_like_emoji_twice_post(self): # Create a second user new_user = User.objects.create_user(username="1", password="1") # Follow the user Follow.objects.create(user=self.user, user_followed=new_user) # Creat a post new_post = UpPost.objects.create(...
Python
nomic_cornstack_python_v1
comment coding: utf import time import math , itertools function isPrime nb begin if nb > 1 begin if nb == 2 begin return true end else if nb % 2 == 0 begin return false end for possible in range 3 integer square root nb + 1 2 begin if nb % possible == 0 begin return false end end return true end return false end funct...
#coding: utf import time import math, itertools def isPrime(nb): if nb > 1: if nb == 2: return True elif nb % 2 == 0: return False for possible in range(3, int(math.sqrt(nb) + 1), 2): if nb % possible == 0: return False return True...
Python
zaydzuhri_stack_edu_python
function create_organization_members self id body begin return post call _url id string members data=body end function
def create_organization_members( self, id: str, body: dict[str, Any] ) -> dict[str, Any]: return self.client.post(self._url(id, "members"), data=body)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from scrumble import NaN import scrumble function stitch l begin set d = dict for i in l begin update d i end return d end function comment These mappings should be true when scrumble is run in comment strict or loose mode set strict_ints = dict 0 0 ; - 1 - 1 ; 1 1 ; 1.0 1 ; - 1.0 - 1 ; 1...
# -*- coding: utf-8 -*- from scrumble import NaN import scrumble def stitch(l): d = {} for i in l: d.update(i) return d # These mappings should be true when scrumble is run in # strict or loose mode strict_ints = { 0: 0, -1: -1, 1: 1, 1.0: 1, -1.0: -1, 1.5: NaN, "0": ...
Python
zaydzuhri_stack_edu_python
set lst = list comprehension x for x in range 1 10 set sqr = list map lambda x -> x ^ 2 lst print max sqr - min sqr
lst=[x for x in range(1,10)] sqr=list(map(lambda x:x**2,lst)) print(max(sqr)-min(sqr))
Python
zaydzuhri_stack_edu_python
function _compare_to self other begin raise call NotImplementedError string _compare_to() must be implemented by subclass end function
def _compare_to(self, other): raise NotImplementedError("_compare_to() must be implemented by subclass")
Python
nomic_cornstack_python_v1
function register_namespace alias reg_code pubKey=none password=none begin print string Registering namespace: %s % alias if pubKey == none begin call generate_keys set pubKey = environ at string pubKey end if call check_lspace == true begin print string Device already registred to a namespace return false end set url ...
def register_namespace(alias, reg_code, pubKey=None, password=None): print( " Registering namespace: %s" % (alias) ) if pubKey == None: generate_keys() pubKey = os.environ["pubKey"] if check_lspace() == True: print(" Device already registred to a namespace") return Fa...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from tinydb import TinyDB , Query import sys comment connect to database set db = call TinyDB string db.json set gigs = call table string gigs set Gig = query set test = call table string test set Test = query function uprint *objects sep=string end=string file=stdout begin set enc = enc...
# -*- coding: utf-8 -*- from tinydb import TinyDB, Query import sys # connect to database db = TinyDB('db.json') gigs = db.table('gigs') Gig = Query() test = db.table('test') Test = Query() def uprint(*objects, sep=' ', end='\n', file=sys.stdout): enc = file.encoding if enc == 'UTF-8': print(*objec...
Python
zaydzuhri_stack_edu_python
async function add_mapshot author keyword image conn channel client begin set message = string Couldn't find the map you're uploading mapshot for comment there might be multiple hits? set tuple found mapname = call find_map_name keyword conn if found begin comment check if mapshot for the map already exists if not exis...
async def add_mapshot(author, keyword: str, image, conn: Connection, channel: TextChannel, client): message = "Couldn't find the map you're uploading mapshot for" (found, mapname) = find_map_name(keyword, conn) # there might be multiple hits? if found: # check if mapshot for the map already exist...
Python
nomic_cornstack_python_v1
import math import tcod as tc from components.ai import ConfusedMonster , FrozenMonster from entity import Entity from game_messages import Message function heal *args **kwargs begin set entity = args at 0 set amount = get kwargs string amount set results = list if hp == max_hp begin append results dict string consume...
import math import tcod as tc from components.ai import ConfusedMonster, FrozenMonster from entity import Entity from game_messages import Message def heal(*args, **kwargs): entity = args[0] amount = kwargs.get('amount') results = [] if entity.fighter.hp == entity.fighter.max_hp: ...
Python
zaydzuhri_stack_edu_python
class Solution begin function getHappyString self n k begin set chars = list string a string b string c function helper n i buf begin nonlocal k if n == 0 begin set k = k - 1 if k == 0 begin return join string generator expression chars at j for j in buf end else begin return string end end for j in range 0 3 begin i...
class Solution: def getHappyString(self, n: int, k: int) -> str: chars = ["a", "b", "c"] def helper(n, i, buf): nonlocal k if n == 0: k -= 1 if k == 0: return "".join(chars[j] for j in buf) else: ...
Python
zaydzuhri_stack_edu_python
function draw_lpo lpo skeleton=false transitive=false skeleton_color=tuple 0 0 255 transitive_color=tuple 220 220 220 begin set tuple size off = call calculate_size lpo set doffset = tuple - off at 0 - off at 1 set tuple w h = size set image = call create_image tuple w * 4 h * 4 set d = call Draw image if transitive be...
def draw_lpo(lpo, skeleton=False, transitive=False, skeleton_color=(0,0,255), transitive_color=(220, 220, 220)): size, off = calculate_size(lpo) doffset = -off[0], -off[1] w, h = size image = create_image((w * 4, h * 4)) d = ImageDraw.Draw(image) if transitive: for arc in lpo.arcs: ...
Python
nomic_cornstack_python_v1
function n self begin return shape at 0 end function
def n(self): return self._loc.shape[0]
Python
nomic_cornstack_python_v1
function send_message sender recipients message begin for recipient in recipients begin comment check for even length email addresses if length email % 2 == 0 begin call receive_message sender message end end end function
def send_message(sender, recipients, message): for recipient in recipients: if len(recipient.email) % 2 == 0: # check for even length email addresses recipient.receive_message(sender, message)
Python
jtatman_500k
class Guichetier begin function __init__ self id nom age solde begin set id = id set nom = nom set age = age set solde = solde print string le solde du client nom string est : solde end function function depot self begin set sum = decimal input string entrez le montant à verser : print string depot de : sum string sur ...
class Guichetier: def __init__(self,id,nom,age,solde): self.id=id self.nom=nom self.age=age self.solde=solde print("le solde du client ",nom," est : ",solde) def depot(self): sum=float(input("entrez le montant à verser :")) print("depot de : ",sum," sur le compte de : ",self.nom) self.solde=self.sold...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import rospy import numpy as np from sensor_msgs.msg import Joy from geometry_msgs.msg import Vector3 from Classes.Mobot import inverse_kinematics comment Reduces the publish rate of velocity messages to the robot comment Gets position and button data from falcon comment Saves incoming data...
#!/usr/bin/env python import rospy import numpy as np from sensor_msgs.msg import Joy from geometry_msgs.msg import Vector3 from Classes.Mobot import inverse_kinematics # Reduces the publish rate of velocity messages to the robot # Gets position and button data from falcon # Saves incoming data in 1kHz # Publishes vel...
Python
zaydzuhri_stack_edu_python
string Description: Complete the function circleArea so that it will return the area of a circle with the given radius. Round the returned number to two decimal places (except for Haskell). If the radius is not positive or not a number, return false. Example: circleArea(-1485.86) #returns false circleArea(0) #returns f...
''' Description: Complete the function circleArea so that it will return the area of a circle with the given radius. Round the returned number to two decimal places (except for Haskell). If the radius is not positive or not a number, return false. Example: circleArea(-1485.86) #returns false circleArea(0) ...
Python
zaydzuhri_stack_edu_python
function from_config_file cls profile_name=DEFAULT_PROFILE_NAME config_path=DEFAULT_PATH tokens_path=DEFAULT_TOKENS_PATH token=none retry_timeout=DEFAULT_RETRY_TIMEOUT debug=false begin set config_path = expand user path config_path set profile = call get_profile profile_name if not token begin try begin set tokens_pat...
def from_config_file( cls, profile_name: str = cfg.DEFAULT_PROFILE_NAME, config_path: Union[str, pathlib.Path] = cfg.DEFAULT_PATH, tokens_path: Union[str, pathlib.Path] = cfg.DEFAULT_TOKENS_PATH, token: Optional[str] = None, retry_timeout: int = DEFAULT_RETRY_TIMEOUT, ...
Python
nomic_cornstack_python_v1
function run self begin call ProgressBar __taskName __initValue for val in range 102 begin call setValue val sleep 0.001 end end function
def run(self): self.ProgressBar(self.__taskName, self.__initValue) for val in range(102): self.setValue(val) time.sleep(0.001)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -- coding: utf-8 -- from flask import Flask , jsonify , json comment from flask_restful import Resource, Api from sqlalchemy import Column , ForeignKey , Integer , String , create_engine , DateTime , Float from sqlalchemy.orm import Session , relationship , backref , joinedload_all ...
#!/usr/bin/env python # -- coding: utf-8 -- from flask import Flask, jsonify, json # from flask_restful import Resource, Api from sqlalchemy import Column, ForeignKey, Integer, String, create_engine, DateTime, Float from sqlalchemy.orm import Session, relationship, backref, joinedload_all, relationship from sqlalchemy...
Python
zaydzuhri_stack_edu_python
comment 005.py comment What is the smallest positive number that is evenly divisible by all of the comment numbers from 1 to 20? function main begin comment from looking at common factors in 2-20 print 5 * 7 * 9 * 11 * 13 * 16 * 17 * 19 end function if __name__ == string __main__ begin call main end
# 005.py # What is the smallest positive number that is evenly divisible by all of the # numbers from 1 to 20? def main(): print(5*7*9*11*13*16*17*19) # from looking at common factors in 2-20 if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
from bisect import bisect_left function solve n arr begin sort arr key=lambda x -> x at 0 set d = list set idx = 0 set length = 0 append d arr at 0 for i in range 1 n begin if d at idx at 1 < arr at i at 1 begin set idx = idx + 1 insert d idx arr at i end else begin set tmp = call bisect_left list comprehension i at 1...
from bisect import bisect_left def solve(n, arr): arr.sort(key=lambda x: x[0]) d = [] idx = 0 length = 0 d.append(arr[0]) for i in range(1,n): if d[idx][1] < arr[i][1]: idx+=1 d.insert(idx, arr[i]) else: tmp = bisect_left([i[1] for i in d], a...
Python
zaydzuhri_stack_edu_python
import sys import json import config import MeCab from requests_oauthlib import OAuth1Session import re from collections import Counter comment ============================================================================= comment 引数の処理 comment ============================================================================...
import sys import json import config import MeCab from requests_oauthlib import OAuth1Session import re from collections import Counter # ============================================================================= # 引数の処理 # ============================================================================= # 第一引数を検索キーワードに...
Python
zaydzuhri_stack_edu_python
function logout begin call logout_user return call redirect string / end function
def logout(): logout_user() return redirect('/')
Python
nomic_cornstack_python_v1
function _get_path self path begin print string -+- Send file to recipient. (Type 'cancel' at any time.) while not exists path path begin set path = input string -+- Input filepath >> if call _user_did_cancel path begin set path = string break end else if not exists path path begin print string x-x File or path doesn'...
def _get_path(self, path): print("-+- Send file to recipient. (Type 'cancel' at any time.)") while not os.path.exists(path): path = input("-+- Input filepath >> ") if self._user_did_cancel(path): path = '' break elif not os.path.exis...
Python
nomic_cornstack_python_v1
function obj_get_list self bundle **kwargs begin set filters = dict if has attribute request string GET begin comment Grab a mutable copy. set filters = copy GET end comment Update with the provided kwargs. update filters kwargs set applicable_filters = call build_filters filters=filters try begin set objects = call a...
def obj_get_list(self, bundle, **kwargs): filters = {} if hasattr(bundle.request, 'GET'): # Grab a mutable copy. filters = bundle.request.GET.copy() # Update with the provided kwargs. filters.update(kwargs) applicable_filters = self.build_filters(filters...
Python
nomic_cornstack_python_v1
function losuj_kulki self begin comment wolne - lista zawierajaca puste pola set wolne = list comment dodawanie wolnych miejsc do listy for i in range 10 begin for j in range 10 begin comment sprawdzenie czy w danym miejscu jest wolne miejsce if plansza at i at j == 0 begin comment dodanie wolnego miejsca do listy app...
def losuj_kulki(self): # wolne - lista zawierajaca puste pola wolne = [] # dodawanie wolnych miejsc do listy for i in range(10): for j in range(10): # sprawdzenie czy w danym miejscu jest wolne miejsce if self.plansza[i][j] == 0: ...
Python
nomic_cornstack_python_v1
import sys print string N= set tuple N i j = tuple integer input 0 0 set tuple a b = tuple list list for i in range N - 1 begin append a integer input set i = i + 1 end for j in range N begin append b j + 1 set j = j + 1 end print list set b - set a
import sys print('N= ') N, i, j = int(input()), 0, 0 a, b = list(), list() for i in range(N-1): a.append(int(input())) i += 1 for j in range(N): b.append(j+1) j += 1 print(list(set(b)-set(a)))
Python
zaydzuhri_stack_edu_python
function get_entity self entity_id begin for entity in query Entity self entity_id=entity_id begin return entity end end function
def get_entity(self, entity_id): for entity in Entity.query(self, entity_id=entity_id): return entity
Python
nomic_cornstack_python_v1
comment 输出A1~A5 set num = list map int split input comment n表示数字的个数 set n = num at 0 set a1 = list set a2 = list set a3 = list set a4 = list set a5 = list comment 利用5个数组保存5种数 for i in range 1 n + 1 begin if num at i % 5 == 0 begin append a1 num at i end else if num at i % 5 == 1 begin append a2 num at i end else i...
#输出A1~A5 num=list(map(int,input().split())) #n表示数字的个数 n=num[0] a1=[] a2=[] a3=[] a4=[] a5=[] #利用5个数组保存5种数 for i in range(1,n+1): if num[i]%5==0: a1.append(num[i]) elif num[i]%5==1: a2.append(num[i]) elif num[i]%5==2: a3.append(num[i]) elif num[i]%5==3: a4.append(num[i]) ...
Python
zaydzuhri_stack_edu_python
function is_sf_team_join_from_oob_link_details self begin return _tag == string sf_team_join_from_oob_link_details end function
def is_sf_team_join_from_oob_link_details(self): return self._tag == 'sf_team_join_from_oob_link_details'
Python
nomic_cornstack_python_v1
function test_MYD08_M3 self begin set MYD08_M3_tested = call scale assert is instance MYD08_M3_tested Image end function
def test_MYD08_M3(self): MYD08_M3_tested = MYD08_M3.scale() self.assertIsInstance(MYD08_M3_tested, ee.image.Image)
Python
nomic_cornstack_python_v1
function time self begin from dateutil.parser import parse set raw = get raw_dict string date if raw is not none begin return parse raw end else begin return none end end function
def time(self): from dateutil.parser import parse raw = self.raw_dict.get("date") if raw is not None: return parse(raw) else: return None
Python
nomic_cornstack_python_v1
string * Ref: https://discuss.leetcode.com/topic/55097/simple-python-solution * Key points: The number of tabs is my depth and for each depth I store the current path length. * Explain your thought: - Given a default value 0 for the max absolute length of a file - Split the input string into lines by ' ' - Each line re...
""" * Ref: https://discuss.leetcode.com/topic/55097/simple-python-solution * Key points: The number of tabs is my depth and for each depth I store the current path length. * Explain your thought: - Given a default value 0 for the max absolute length of a file - Split the input string into lines by '\...
Python
zaydzuhri_stack_edu_python
function adaptForRenderer self renderer begin if not buildFrom begin return self end set adaptor = call getRendererAdaptor renderer if adaptor is none begin return self end end function
def adaptForRenderer(self, renderer): if not self.buildFrom: return self adaptor = inputdef.getRendererAdaptor(renderer) if adaptor is None: return self
Python
nomic_cornstack_python_v1
import cv2 import numpy as np set cap = call VideoCapture 0 while true begin comment cap.read() eturns true if everything is all right set tuple ret frame = read cap comment to convert to gray set gray = call cvtColor frame COLOR_BGR2GRAY comment natural frame image show string frame frame comment gray frame image show...
import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: ret,frame = cap.read() #cap.read() eturns true if everything is all right gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # to convert to gray cv2.imshow('frame',frame) # natural frame cv2.imshow('gray',gray) #gray frame if c...
Python
zaydzuhri_stack_edu_python
import math import optimization set starting_points = list 0 1 2 3 4 5 6 7 8 9 10 set step_sizes = list 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 function func x begin return sin x ^ 2 / 2 / log x + 4 2 end function print string Hill Climbing: for starting_point in starting_points begin print string Starting Poi...
import math import optimization starting_points = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] step_sizes = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1] def func(x): return math.sin((x ** 2) / 2) / math.log(x + 4, 2) print("Hill Climbing: ") for starting_point in starting_points: print("\nStarting Poin...
Python
zaydzuhri_stack_edu_python
function save self path table_format=string txt sep=string table_ext=none float_format=string %.12g begin string Saving the system to path Parameters ---------- path : pathlib.Path or string path for the saved data (will be created if necessary, data within will be overwritten). table_format : string Format to save th...
def save(self, path, table_format='txt', sep='\t', table_ext=None, float_format='%.12g'): """ Saving the system to path Parameters ---------- path : pathlib.Path or string path for the saved data (will be created if necessary, data within will be ov...
Python
jtatman_500k
function _latex_ self begin if _latex_name is none begin return string \mbox{ + string self + string } end else begin return _latex_name end end function
def _latex_(self): if self._latex_name is None: return r'\mbox{' + str(self) + r'}' else: return self._latex_name
Python
nomic_cornstack_python_v1
function parse_DESI_brick hdulist select=0 **kwargs begin set fx = data comment Sig if name in list string ERROR string SIG begin set sig = data end else begin set ivar = data set sig = zeros like ivar set gdi = ivar > 0.0 set sig at gdi = square root 1.0 / ivar at gdi end comment Wave set wave = data set wave = call g...
def parse_DESI_brick(hdulist, select=0, **kwargs): fx = hdulist[0].data # Sig if hdulist[1].name in ['ERROR', 'SIG']: sig = hdulist[1].data else: ivar = hdulist[1].data sig = np.zeros_like(ivar) gdi = ivar > 0. sig[gdi] = np.sqrt(1./ivar[gdi]) # Wave wave ...
Python
nomic_cornstack_python_v1
import pytesseract as pyt function img_to_text cover begin set text = call image_to_string open cover set text = split text string set final = string set text = join final text return text end function
import pytesseract as pyt def img_to_text(cover): text = pyt.pytesseract.image_to_string(pyt.pytesseract.Image.open(cover)) text = text.split('\n') final = " " text = final.join(text) return text
Python
zaydzuhri_stack_edu_python
function _momentum_update_key_encoder self begin for tuple param_q param_k in zip parameters encoder_q parameters encoder_k begin set data = data * m + data * 1.0 - m end end function
def _momentum_update_key_encoder(self): for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()): param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)
Python
nomic_cornstack_python_v1
import sys append path string ../../../ import mongoengine import datetime import pymongo from discs.data.underlying.users import User from discs.data.underlying.posts import Post from discs.settings import connect_with_database decorator connect_with_database function check_user name begin set user = first call object...
import sys sys.path.append('../../../') import mongoengine import datetime import pymongo from discs.data.underlying.users import User from discs.data.underlying.posts import Post from discs.settings import connect_with_database @connect_with_database def check_user(name): user = User.objects(username=name).fi...
Python
zaydzuhri_stack_edu_python
function root_mean_squared_error t p begin return square root mean call square t - p end function
def root_mean_squared_error(t, p): return np.sqrt(np.square(t - p).mean())
Python
nomic_cornstack_python_v1
function run_single_parsing_loop self begin if not _parent_signal_conn or not _process begin raise call ValueError string Process not started. end if not is alive _process begin return end try begin call send AGENT_RUN_ONCE end except ConnectionError begin comment If this died cos of an error then we will noticed and r...
def run_single_parsing_loop(self) -> None: if not self._parent_signal_conn or not self._process: raise ValueError("Process not started.") if not self._process.is_alive(): return try: self._parent_signal_conn.send(DagParsingSignal.AGENT_RUN_ONCE) excep...
Python
nomic_cornstack_python_v1
function _iter_attrs_for_field_type cls field_type begin return call iterkeys call _get_defaults_for_field_type field_type end function
def _iter_attrs_for_field_type(cls, field_type): return six.iterkeys(cls._get_defaults_for_field_type(field_type))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Builds a new corpus that can be used by BTM (Biterm Topic comment Model) import argparse import json import os , shutil from _document import parse_corpus function create_vocab corpus begin set w2id = dict set d2ids = dict for doc in corpus begin for word in words begin if not wo...
#!/usr/bin/env python3 ################################################################ ## ## Builds a new corpus that can be used by BTM (Biterm Topic ## Model) ## ################################################################ import argparse import json import os, shutil from _document import parse_corpus def c...
Python
zaydzuhri_stack_edu_python
function add_movie data begin set response = dict comment validate input movie data set movie_details = call AddMovieSerializer data=data if call is_valid begin comment Add new movie record set movie = call Movies keyword data save set response = call build_response STATUS_OK RECORD_NEW record=dict MOVIE_TITLE title ;...
def add_movie(data): response = {} # validate input movie data movie_details = AddMovieSerializer(data = data) if movie_details.is_valid(): # Add new movie record movie = Movies(**data) movie.save() response = Utils.build_response(Constan...
Python
nomic_cornstack_python_v1
import os set dir = list directory string /data/code print dir set dir = call scandir string /data/code with dir as entries begin for entry in entries begin print type entry print name end end
import os dir = os.listdir('/data/code') print(dir) dir = os.scandir('/data/code') with dir as entries: for entry in entries: print(type(entry)) print(entry.name)
Python
zaydzuhri_stack_edu_python
function _get_expert_parallel_group group_name begin assert group_name in _EXPERT_PARALLEL_GROUP msg string expert parallel group is not initialized return _EXPERT_PARALLEL_GROUP at group_name end function
def _get_expert_parallel_group(group_name): assert group_name in _EXPERT_PARALLEL_GROUP, \ 'expert parallel group is not initialized' return _EXPERT_PARALLEL_GROUP[group_name]
Python
nomic_cornstack_python_v1
comment coding=utf8 import sys import ipaddress function getCIDR filename begin with open filename string r as f begin set ip_list = list comprehension strip ip for ip in read lines f if ip end return ip_list end function function transformCIDR ip begin return list call ip_network ip strict=false end function function ...
#coding=utf8 import sys import ipaddress def getCIDR(filename): with open(filename, 'r') as f: ip_list = [ip.strip() for ip in f.readlines() if ip] return ip_list def transformCIDR(ip): return list(ipaddress.ip_network(ip, strict=False)) def transformRange(ip_range): startip = ip_range.sp...
Python
zaydzuhri_stack_edu_python
class Solution begin function findTheDifference self s t begin set result = list comprehension 0 for i in range 26 set ascii_a = ordinal string a for i in range length s begin set c_s = s at i set c_t = t at i set result at ordinal c_s - ascii_a = result at ordinal c_s - ascii_a + 1 set result at ordinal c_t - ascii_a ...
class Solution: def findTheDifference(self, s: str, t: str) -> str: result = [0 for i in range(26)] ascii_a = ord('a') for i in range(len(s)): c_s = s[i] c_t = t[i] result[ord(c_s) - ascii_a] += 1 result[ord(c_t) - ascii_a] -= 1 resul...
Python
zaydzuhri_stack_edu_python
from turtle import Turtle , Screen import random set screen = call Screen setup screen width=500 height=400 set user_bet = call textinput title=string Make your bet prompt=string Choose a color to see if your turtle wins the race: set colors = list string red string orange string yellow string green string blue string ...
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt = "Choose a color to see if your turtle wins the race: ") colors = ["red", "orange", "yellow", "green", "blue", "purple"] turtles = [] start = False # loop t...
Python
zaydzuhri_stack_edu_python
function linux2_script begin with open string buildRenameLinux-x86_64.sh string w as script begin write script format string mv dist/exe.linux-x86_64-{}.{}.tar.gz dist/arelle-linux-x86_64-{}.tar.gz version_info at 0 version_info at 1 VERSION_STRING end end function
def linux2_script(): with open("buildRenameLinux-x86_64.sh", "w") as script: script.write( "mv dist/exe.linux-x86_64-{}.{}.tar.gz " "dist/arelle-linux-x86_64-{}.tar.gz\n" .format( sys.version_info[0], sys.version_info[1], VERSION_STRING ...
Python
nomic_cornstack_python_v1