code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_dispatch_missing self begin set logic = dict assert raises KeyError dispatch end function
def test_dispatch_missing(self): self.skill.logic = {} self.assertRaises(KeyError, self.skill.dispatch)
Python
nomic_cornstack_python_v1
function multiply_two_nums num1 num2 begin set sign = if expression num1 at 0 < 0 ? num2 at 0 < 0 then - 1 else 1 set num1 at 0 = absolute num1 at 0 set num2 at 0 = absolute num2 at 0 set result = list 0 * length num1 + length num2 for i in reversed range length num1 begin for j in reversed range length num2 begin set ...
def multiply_two_nums(num1, num2): sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1 num1[0] = abs(num1[0]) num2[0] = abs(num2[0]) result = [0]*(len(num1) + len(num2)) for i in reversed(range(len(num1))): for j in reversed(range(len(num2))): result[i+j+1] += num1[i] * num2[j] ...
Python
zaydzuhri_stack_edu_python
function distance x1 y1 z1 x2 y2 z2 begin return square root x1 - x2 ^ 2 + y1 - y2 ^ 2 + z1 - z2 ^ 2 end function
def distance(x1, y1, z1, x2, y2, z2): return math.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)
Python
nomic_cornstack_python_v1
comment create a 300x300 canvas. comment create a line drawing function that takes 2 parameters: comment the x and y coordinates of the line's starting point comment and draws a line from that point to the center of the canvas. comment draw 3 lines with that function. from tkinter import * set root = call Tk set canvas...
# create a 300x300 canvas. # create a line drawing function that takes 2 parameters: # the x and y coordinates of the line's starting point # and draws a line from that point to the center of the canvas. # draw 3 lines with that function. from tkinter import * root = Tk() canvas = Canvas(root, width=300, height=300)...
Python
zaydzuhri_stack_edu_python
set a = list comprehension input for i in range 3 print a at 0 at 0 + a at 1 at 1 + a at 2 at 2 sep=string
a = [input() for i in range(3)] print(a[0][0]+a[1][1]+a[2][2], sep='')
Python
zaydzuhri_stack_edu_python
function test_calculate_offsets_word_part self begin set applicable_terms = list tuple string act string a set text = string I am about to act on this transaction. set t = call Terms none set matches = call calculate_offsets text applicable_terms assert equal 1 length matches assert equal 1 length matches at 0 at 2 end...
def test_calculate_offsets_word_part(self): applicable_terms = [('act', 'a')] text = "I am about to act on this transaction." t = Terms(None) matches = t.calculate_offsets(text, applicable_terms) self.assertEqual(1, len(matches)) self.assertEqual(1, len(matches[0][2]))
Python
nomic_cornstack_python_v1
function validate_ldap_dn param options=none begin if not param begin return end try begin import ldap import ldap.dn end except ImportError begin set msg = string The python ldap package is required to use this functionality. raise call ParamValidationError msg end try begin call str2dn param end except DECODING_ERROR...
def validate_ldap_dn(param, options=None): if not param: return try: import ldap import ldap.dn except ImportError: msg = ( 'The python ldap package is required to use this functionality.' ) raise ParamValidationError(msg) try: ldap.dn...
Python
nomic_cornstack_python_v1
function load_xml self title_info_element begin call set_attributes title_info_element self set title_element = find title_info_element string {%s}title % MODS if title_element is not none begin set new_title = title call load_xml title_element set title = new_title end set nonsort_element = find title_info_element str...
def load_xml(self, title_info_element): set_attributes(title_info_element,self) title_element = title_info_element.find('{%s}title' % ns.MODS) if title_element is not None: new_title = title() new_title.load_xml(title_element) self.title = new...
Python
nomic_cornstack_python_v1
function bytecode_to_string self begin set out = call StringIO call write_bytecode out return call getvalue end function
def bytecode_to_string(self): out = StringIO() self.write_bytecode(out) return out.getvalue()
Python
nomic_cornstack_python_v1
function get self begin call is_empty print _collection at - 1 del _collection at - 1 end function
def get(self): self.is_empty() print(self._collection[-1]) del self._collection[-1]
Python
nomic_cornstack_python_v1
function getExpirationDate self begin return call getExpirationDate end function
def getExpirationDate(self): return self.getStrikes()[0].getExpirationDate()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Mar 31 03:52:56 2015 @author: Adrián de las Matas de la Fuente import circleDetection as circleD import croppingImages as cropImg import ImageOperations as imgOperations import setupFile as setup import SVMModel as svmModel import croppingLeftBorder as clb import comp...
# -*- coding: utf-8 -*- """ Created on Tue Mar 31 03:52:56 2015 @author: Adrián de las Matas de la Fuente """ import circleDetection as circleD import croppingImages as cropImg import ImageOperations as imgOperations import setupFile as setup import SVMModel as svmModel import croppingLeftBorder as clb import computi...
Python
zaydzuhri_stack_edu_python
string **Selection sort 1. 오름차순 - 숫자: 작은수 -> 큰수 - 영문: A->Z - 한글: ㄱ->ㅎ 2. 내림차순 - 숫자: 큰수 -> 작은수 - 영문: Z->A - 한글: ㅎ->ㄱ comment HW02Pandas02_12_Sort01Selection_김채현 set sortNum = list 2 5 6 1 2 8 33 77 12 for i in range length sortNum - 1 begin for j in range i + 1 length sortNum begin if sortNum at i > sortNum at j begin c...
''' **Selection sort 1. 오름차순 - 숫자: 작은수 -> 큰수 - 영문: A->Z - 한글: ㄱ->ㅎ 2. 내림차순 - 숫자: 큰수 -> 작은수 - 영문: Z->A - 한글: ㅎ->ㄱ ''' #HW02Pandas02_12_Sort01Selection_김채현 sortNum = [2,5,6,1,2,8,33,77,12] for i in range(len(sortNum)-1): for j in range(i+1,len(sortNum)): if (sortNum[i]>sortNum[j]): Temp=sortNum[i] #교환 A...
Python
zaydzuhri_stack_edu_python
function delete_datasource self datasource_name begin if datasource_name is none begin raise call ValueError string Datasource names must be a datasource name end else begin set datasource = call get_datasource datasource_name=datasource_name if datasource begin comment remove key until we have a delete method on proje...
def delete_datasource(self, datasource_name: str): if datasource_name is None: raise ValueError("Datasource names must be a datasource name") else: datasource = self.get_datasource(datasource_name=datasource_name) if datasource: # remove key until we h...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Jun 21 12:34:47 2019 @author: Nout import time import os from pathlib import Path change directory parents at 1 from A22DSE.Parameters.Par_Class_All import Aircraft from A22DSE.Parameters.Par_Class_Conventional import TotalAC import numpy as np import matplotlib.pyplo...
# -*- coding: utf-8 -*- """ Created on Fri Jun 21 12:34:47 2019 @author: Nout """ import time import os from pathlib import Path os.chdir(Path(__file__).parents[1]) from A22DSE.Parameters.Par_Class_All import Aircraft from A22DSE.Parameters.Par_Class_Conventional import TotalAC import numpy as np import matplotlib.py...
Python
zaydzuhri_stack_edu_python
comment Softmax // import matplotlib.pyplot as plt import numpy as np comment 100 set x = array range 1 5 function softmax x begin return exp x / sum exp x end function set y = softmax x set ratio = y set labels = y call pie ratio labels=labels shadow=true startangle=90 show
# Softmax // import matplotlib.pyplot as plt import numpy as np x = np.arange(1, 5) # 100 def softmax(x): return np.exp(x) / np.sum(np.exp(x)) y = softmax(x) ratio = y labels = y plt.pie(ratio, labels=labels, shadow=True, startangle=90) plt.show()
Python
zaydzuhri_stack_edu_python
from forex_python.converter import CurrencyRates from tkinter import * from datetime import * print now function show_table event begin set c = call CurrencyRates set cur_from = string THB set dict_currency = call get_rates cur_from comment print(dict_currency) set input_amount = decimal get textbox_input_currency comm...
from forex_python.converter import CurrencyRates from tkinter import * from datetime import * print(datetime.now) def show_table(event): c = CurrencyRates() cur_from = "THB" dict_currency = c.get_rates(cur_from) #print(dict_currency) input_amount = float(textbox_input_currency.g...
Python
zaydzuhri_stack_edu_python
import logging from gensim.models import word2vec from bs4 import BeautifulSoup import pandas as pd import numpy as np from bs4 import BeautifulSoup from keras.preprocessing.text import Tokenizer , text_to_word_sequence import nltk import re from nltk import tokenize from MasterProject.data_Preprocessing.Datasets impor...
import logging from gensim.models import word2vec from bs4 import BeautifulSoup import pandas as pd import numpy as np from bs4 import BeautifulSoup from keras.preprocessing.text import Tokenizer, text_to_word_sequence import nltk import re from nltk import tokenize from MasterProject.data_Preprocessing.Datasets import...
Python
zaydzuhri_stack_edu_python
function lineage self begin return _parent end function
def lineage(self) -> 'lngmod.Level': return self._parent
Python
nomic_cornstack_python_v1
import os import re import json import unicodedata function save_json json_structure outfilename begin set tuple _ file_extension = call splitext outfilename if not file_extension begin set outfilename = outfilename + string .json end if exists path outfilename begin remove os outfilename end if is instance json_struct...
import os import re import json import unicodedata def save_json(json_structure, outfilename): _, file_extension = os.path.splitext(outfilename) if not file_extension: outfilename += ".json" if os.path.exists(outfilename): os.remove(outfilename) if isinstance(json_structure, set): ...
Python
zaydzuhri_stack_edu_python
function VDegree self *args begin return call GeomConvert_CompBezierSurfacesToBSplineSurface_VDegree self *args end function
def VDegree(self, *args): return _GeomConvert.GeomConvert_CompBezierSurfacesToBSplineSurface_VDegree(self, *args)
Python
nomic_cornstack_python_v1
function clean_up_activation_order self order begin set result = list for name in order begin if call is_category name begin set cat_desc = categories at name set present = set order ? set features comment We eagerly add every dependency, later we will remove duplicates if present begin set tuple total_order _ = call g...
def clean_up_activation_order(self, order): result = list() for name in order: if self.is_category(name): cat_desc = self.categories[name] present = set(order) & set(cat_desc.features) # We eagerly add every dependency, later we will remove duplicates if present: ...
Python
nomic_cornstack_python_v1
function loadSpriteImages path begin if not is file path join path path string moves.json begin print string Error: 'moves.json' is required to be in folder: { path } ! exit end comment make raw string into a python dictionary set sprite_info = call loadJsonSprite path string moves.json comment base name is used to bui...
def loadSpriteImages(path): if not os.path.isfile(os.path.join(path,"moves.json")): print(f"Error: 'moves.json' is required to be in folder: {path}!") sys.exit() # make raw string into a python dictionary sprite_info = loadJsonSprite(path,"moves.json") # base name is used to build...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python set cnt = 0 set fmap = dict for line in open string ./format_data/train.txt begin set tokens = split line set i = 0 for token in tokens begin set i = i + 1 if i <= 8 begin continue end comment if not token.startswith('int#xxx'): # XXX: feature filtering comment continue if not starts with toke...
#!/usr/bin/python cnt = 0 fmap = {} for line in open('./format_data/train.txt'): tokens = line.split() i = 0 for token in tokens: i += 1 if i <= 8: continue #if not token.startswith('int#xxx'): # XXX: feature filtering # continue if not (token.start...
Python
zaydzuhri_stack_edu_python
import unittest from toycache.cache import Cache from toycache.cache_interface import CacheProtocolCommand , CacheInterface class CacheInterfaceTestCase extends TestCase begin function setUp self begin set _cache = cache set _cache_interface = call CacheInterface _cache end function function test_exec_set self begin se...
import unittest from toycache.cache import Cache from toycache.cache_interface import CacheProtocolCommand, CacheInterface class CacheInterfaceTestCase(unittest.TestCase): def setUp(self): self._cache = Cache() self._cache_interface = CacheInterface(self._cache) def test_exec_set(self): ...
Python
zaydzuhri_stack_edu_python
function blend_transparent background_img overlay_img begin comment TODO: this is now very slow..., optimize comment Perhaps check Pillow's alpha composite comment https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.alpha_composite comment from: https://stackoverflow.com/questions/36921496/how-to-join...
def blend_transparent(background_img, overlay_img): # TODO: this is now very slow..., optimize # Perhaps check Pillow's alpha composite # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.alpha_composite # from: https://stackoverflow.com/questions/36921496/how-to-join-png-with-...
Python
nomic_cornstack_python_v1
function plateau_idxs self i begin if _r_sp_idxs at i is none begin set _r_sp_idxs at i = call r_sp_idx i end set sp_idx = _r_sp_idxs at i if sp_idx == - 1 begin return tuple - 1 - 1 end set p_end_idx = sp_idx for i in call xrange sp_idx - 1 - 1 - 1 begin if rhos at i + 1 > rhos at i begin set p_end_idx = i + 1 break e...
def plateau_idxs(self, i): if self._r_sp_idxs[i] is None: self._r_sp_idxs[i] = self.r_sp_idx(i) sp_idx = self._r_sp_idxs[i] if sp_idx == -1: return -1, -1 p_end_idx = sp_idx for i in xrange(sp_idx-1, -1, -1): if rhos[i + 1] > rhos[i]: ...
Python
nomic_cornstack_python_v1
comment This is my abstract class. It initializes the attributes, I think class Animal extends object begin function __init__ self begin comment These are the attributes common to all subclasses set name = string set phylum = string set klass = string set family = string set genus = string set url = string set li...
# This is my abstract class. It initializes the attributes, I think class Animal(object): def __init__(self): # These are the attributes common to all subclasses self.name = "" self.phylum = "" self.klass = "" self.family = "" self.genus = "" self.url = "" ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import math import outputparse class Results begin set OUTPUT_FOLDERS = list tuple string accuracy_outputs/ string acc function __init__ self sort=string valid_acc begin set p = call Parser sort_column=sort end function function top_10 self table=false begin return cal...
import matplotlib.pyplot as plt import numpy as np import math import outputparse class Results: OUTPUT_FOLDERS=[ ('accuracy_outputs/', 'acc'), ] def __init__(self, sort='valid_acc'): self.p = outputparse.Parser(sort_column=sort) def top_10(self, table=False): return self.top_k(10, table=table) def to...
Python
zaydzuhri_stack_edu_python
function get_title self begin return title end function
def get_title(self): return self.title
Python
nomic_cornstack_python_v1
import re from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse , redirect function reg request current_path begin set permission_list = get session string permission_list list set flag = false for permission in permission_list begin set ret = match permission current_path if re...
import re from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse,redirect def reg(request,current_path): permission_list = request.session.get("permission_list", []) flag = False for permission in permission_list: ret = re.match(permission, current_path) ...
Python
zaydzuhri_stack_edu_python
function archive archive_name files verbose=false begin set archive_type = split archive_name string . at - 1 if archive_type != string gz and archive_type != string bz2 begin error string the archive has to be a *.tar.gz or a *.tar.bz2 file end set archive_file = open archive_name string w:%s % archive_type for file i...
def archive(archive_name, files, verbose=False): archive_type = archive_name.split('.')[-1] if archive_type != 'gz' and archive_type != 'bz2': optparser.error('the archive has to be a *.tar.gz or a *.tar.bz2 file') archive_file = tarfile.open(archive_name, 'w:%s' % archive_type) for file in f...
Python
nomic_cornstack_python_v1
comment %s - for strings set name = string Martin comment %d - for integers set age = 23 comment %f - for floating point numbers set height = 180.5 print string %s is %d years old. My height is %f % tuple name age height comment %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right o...
# %s - for strings name = "Martin" # %d - for integers age = 23 # %f - for floating point numbers height = 180.5 print("%s is %d years old.\nMy height is %f" % (name, age, height)) # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # %x/%X - Integers in hex repr...
Python
zaydzuhri_stack_edu_python
function sum_list nums begin if not nums begin return 0 end return nums at 0 + call sum_list nums at slice 1 : : end function comment 15 call sum_list list 1 2 3 4 5
def sum_list(nums): if not nums: return 0 return nums[0] + sum_list(nums[1:]) sum_list([1,2,3,4,5]) # 15
Python
jtatman_500k
import turtle set my_turtle = call Turtle call showturtle set my_screen = call Screen call bgcolor string blue comment Draw Here comment draw solid shape call fillcolor string red call begin_fill call goto 200 0 call goto 200 200 call goto 0 200 call goto 0 0 call end_fill comment set line thickness call width 10 comme...
import turtle my_turtle = turtle.Turtle() my_turtle.showturtle() my_screen = turtle.Screen() my_screen.bgcolor('blue') # Draw Here my_turtle.fillcolor("red") # draw solid shape my_turtle.begin_fill() my_turtle.goto(200, 0) my_turtle.goto(200, 200) my_turtle.goto(0, 200) my_turtle.goto(0, 0) my_turtle.end_fill() my_...
Python
zaydzuhri_stack_edu_python
function _add_user_request self lfn user begin if user not in user_requests begin set user_requests at user = set end if lfn not in user_lfn_requests begin set user_lfn_requests at lfn = set end add user_requests at user lfn add user_lfn_requests at lfn user end function
def _add_user_request(self, lfn, user): if user not in self.user_requests: self.user_requests[user] = sets.Set() if lfn not in self.user_lfn_requests: self.user_lfn_requests[lfn] = sets.Set() self.user_requests[user].add(lfn) self.user_lfn_requests[lfn].add(user)
Python
nomic_cornstack_python_v1
import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense comment 1. Data set x_train = array list 1 2 3 4 5 6 7 8 9 10 set y_train = array list 2 4 6 8 10 12 14 16 18 20 set x_test = array list 101 102 103 104 105 106 107 108 109 110 set y_test ...
import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense #1. Data x_train = np.array([1,2,3,4,5,6,7,8,9,10]) y_train = np.array([2,4,6,8,10,12,14,16,18,20]) x_test = np.array([101, 102, 103, 104, 105, 106, 107, 108, 109, 110]) y_test = np.array...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment auther:Liul5 comment date:2019/3/29 13:41 comment tools:PyCharm comment Python:2.7.15 function house plan begin if string # not in plan begin return 0 end set plan = split plan comment print plan set raw = list comprehension i for tuple i j in enumerate plan for tuple m n in enumerate j if ...
# coding=utf-8 # auther:Liul5 # date:2019/3/29 13:41 # tools:PyCharm # Python:2.7.15 def house(plan): if "#" not in plan: return 0 plan = plan.split() # print plan raw = [i for i, j in enumerate(plan) for m, n in enumerate(j) if n == "#"] column = [m for i, j in enumerate(plan) for m, n in...
Python
zaydzuhri_stack_edu_python
function get_post_key self begin set response = get session forum_url set post_key = attrs at string value return post_key end function
def get_post_key(self): response = self.session.get(config.forum_url) post_key = response.html.xpath("//input[@name='my_post_key']", first=True).attrs['value'] return post_key
Python
nomic_cornstack_python_v1
class SocialNetworkUser begin function __init__ self name age interests begin set name = name set age = age set interests = interests end function function get_name self begin return name end function function set_name self name begin set name = name end function function get_age self begin return age end function func...
class SocialNetworkUser: def __init__(self, name, age, interests): self.name = name self.age = age self.interests = interests def get_name(self): return self.name def set_name(self, name): self.name = name def get_age(self): return s...
Python
jtatman_500k
if m == 0 or n == 0 or length l == 0 begin print 1 end set matrix = list comprehension list comprehension 0 for _ in range m for _ in range n for i in range n begin for j in range m begin set matrix at i at j = l at i * m + j end end set dp = list comprehension list 0 * m for _ in range n set dp at n - 1 at m - 1 = max...
if m == 0 or n == 0 or len(l) == 0: print(1) matrix = [[0 for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): matrix[i][j] = l[i*m+j] dp = [[0] * m for _ in range(n)] dp[n-1][m-1] = max(1-matrix[n-1][m-1] ,1) for i in range(n-2, -1, -1): dp[i][m-1] = max(dp[i+1][m-...
Python
zaydzuhri_stack_edu_python
comment @lc app=leetcode id=1815 lang=python3 comment [1815] Maximum Number of Groups Getting Fresh Donuts comment https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/description/ comment algorithms comment Hard (16.72%) comment Likes: 26 comment Dislikes: 6 comment Total Accepted: 384 comment T...
# # @lc app=leetcode id=1815 lang=python3 # # [1815] Maximum Number of Groups Getting Fresh Donuts # # https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/description/ # # algorithms # Hard (16.72%) # Likes: 26 # Dislikes: 6 # Total Accepted: 384 # Total Submissions: 2.2K # Testcase Exampl...
Python
zaydzuhri_stack_edu_python
for tuple k v in items d begin set d1 at v = k end print d print d1
for k, v in d.items(): d1[v] = k print(d) print(d1)
Python
zaydzuhri_stack_edu_python
function modal request subject_pk item_pk begin set item = call get_object_or_404 Item pk=item_pk set subject = call get_object_or_404 Subject pk=subject_pk set quick_buttons = all set sections = call convert_string_into_data_type all set context = dict string item item ; string subject subject ; string sections sectio...
def modal(request, subject_pk, item_pk): item = get_object_or_404(Item, pk=item_pk) subject = get_object_or_404(Subject, pk=subject_pk) quick_buttons = item.modal.all() sections = convert_string_into_data_type(item.modal.all()) context = { 'item': item, 'subject': subject, '...
Python
nomic_cornstack_python_v1
function test_expose_method self begin set f = lambda request -> none set f_ = call call expose string /test_expose f call assert_ f_ is f end function
def test_expose_method(self): f = lambda request: None f_ = self.app.expose('/test_expose')(f) self.assert_(f_ is f)
Python
nomic_cornstack_python_v1
function load_profile path profile begin set profiles = load path try begin return profiles at profile end except KeyError begin return call Profile none none none none end end function
def load_profile(path, profile): profiles = load(path) try: return profiles[profile] except KeyError: return Profile(None, None, None, None)
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment Complete the kangaroo function below. function kangaroo xv begin set x1 = xv at 0 set v1 = xv at 1 set x2 = xv at 2 set v2 = xv at 3 string if x1<x2 and v1>v2: print('YES') elif x1>x2 and v1<v2: print('YES') elif x1==x2: print('YES')...
#!/bin/python3 import math import os import random import re import sys # Complete the kangaroo function below. def kangaroo(xv): x1 = xv[0] v1 = xv[1] x2 = xv[2] v2 = xv[3] """ if x1<x2 and v1>v2: print('YES') elif x1>x2 and v1<v2: print('YES') elif x1==x2: ...
Python
zaydzuhri_stack_edu_python
string Created on 2018年6月2日 @author: Administrator from numpy import * import os import shutil comment get the number of lines in the file function file2matric filename begin comment prepare matrix to return set imagename = list comment prepare labels return set classLabelVector = list set fr = open filename string r...
''' Created on 2018年6月2日 @author: Administrator ''' from numpy import * import os import shutil def file2matric(filename): #get the number of lines in the file imagename = [] #prepare matrix to return classLabelVector = [] #prepare labels return fr = open(filename,'r') ...
Python
zaydzuhri_stack_edu_python
function dominantIndex nums begin if length nums == 1 begin return 0 end set index = index nums max nums set a = pop nums index return if expression a >= max nums * 2 then index else - 1 end function function dominantIndex_2 nums begin if length nums == 1 begin return 0 end set Max = 0 set secordMax = 0 set index = 0 f...
def dominantIndex(nums): if len(nums) == 1: return 0 index = nums.index(max(nums)) a = nums.pop(index) return index if a >= max(nums) * 2 else -1 def dominantIndex_2(nums): if len(nums) == 1: return 0 Max = 0 secordMax = 0 index = 0 for i in range(len(nums)): ...
Python
zaydzuhri_stack_edu_python
function test_update_contact_association self begin set patient1 = call create_patient dict string mobile_number string 12223334444 set patient2 = call create_patient set subject_number = subject_number set node = call create_xml_patient dict string Subject_Number subject_number ; string Mobile_Number string 4333222111...
def test_update_contact_association(self): patient1 = self.create_patient({'mobile_number': '12223334444'}) patient2 = self.create_patient() subject_number = patient1.subject_number node = self.create_xml_patient({'Subject_Number': subject_number, ...
Python
nomic_cornstack_python_v1
from itertools import islice import numpy as np function vpack arrays shape fill dtype=none begin string like `np.vstack` but for `arrays` of different lengths in the first axis. shorter ones will be padded with `fill` at the end. set array = call full shape fill dtype for tuple row arr in zip array arrays begin set ro...
from itertools import islice import numpy as np def vpack(arrays, shape, fill, dtype= None): """like `np.vstack` but for `arrays` of different lengths in the first axis. shorter ones will be padded with `fill` at the end. """ array = np.full(shape, fill, dtype) for row, arr in zip(array, arrays)...
Python
zaydzuhri_stack_edu_python
for x in range x begin for level in range 1 x + 1 begin print string # * level end end print string następna choinka
for x in range(x): for level in range(1, x + 1): print('#' * level) print("następna choinka")
Python
zaydzuhri_stack_edu_python
function _signal_handler *args begin set _user_exit = true end function
def _signal_handler(*args): self._user_exit = True
Python
nomic_cornstack_python_v1
comment Input engloba lo que el usuario debe de escribir desde el teclado en la terminal comment La funcion print añade un salto de linea por lo que el usuario al contestar comment lo hace en una linea más abajo comment print("Cómo te llamas: ") comment nombre = input() comment print("Me alegro de conocerte, ",nombre) ...
#Input engloba lo que el usuario debe de escribir desde el teclado en la terminal #La funcion print añade un salto de linea por lo que el usuario al contestar # lo hace en una linea más abajo #print("Cómo te llamas: ") #nombre = input() #print("Me alegro de conocerte, ",nombre) #------------ #Con ,end="" hace que ...
Python
zaydzuhri_stack_edu_python
from aip import AipOcr import time import requests from bs4 import BeautifulSoup import urllib.parse , urllib.request import _thread string 1、首先是获取图片关键词 2、然后得到百度页面 3、然后根据搜索引擎获得每一个页面问题答案出现的次数,统计最多的,以最多的为最终答案 set config = dict string appId string 10778787 ; string apiKey string sizuhfENuir0VkDszacrIz0K ; string secretKey...
from aip import AipOcr import time import requests from bs4 import BeautifulSoup import urllib.parse, urllib.request import _thread ''' 1、首先是获取图片关键词 2、然后得到百度页面 3、然后根据搜索引擎获得每一个页面问题答案出现的次数,统计最多的,以最多的为最终答案 ''' config = { "appId": "10778787", "apiKey": "sizuhfENuir0VkDszacrIz0K", "secretKey": "AjH9S8kAQyzP5vsU...
Python
zaydzuhri_stack_edu_python
function handle_endtag self tag begin string Handler of ending tag processing (overrided, private) debug format string Encountered an end tag : {0} tag if tag in sanitizelist begin set level = level - 1 return end if tag in unclosedTags begin return end if isNotPurify or tag in whitelist_keys begin append data string <...
def handle_endtag(self, tag): """ Handler of ending tag processing (overrided, private) """ self.log.debug( u'Encountered an end tag : {0}'.format(tag) ) if tag in self.sanitizelist: self.level -= 1 return if tag in self.unclosedTags: r...
Python
jtatman_500k
async function keep_alive self period=1 margin=0.3 begin set interval = period set margin = margin end function
async def keep_alive(self, period=1, margin=.3): self.KeepAlive.interval = period self.KeepAlive.margin = margin
Python
nomic_cornstack_python_v1
function clean_strokes sample_strokes factor=100 begin comment Useful function for exporting data to .json format. set copy_stroke = list set added_final = false for j in range length sample_strokes begin set finish_flag = integer sample_strokes at j at 4 if finish_flag == 0 begin append copy_stroke list integer round...
def clean_strokes(sample_strokes, factor=100): # Useful function for exporting data to .json format. copy_stroke = [] added_final = False for j in range(len(sample_strokes)): finish_flag = int(sample_strokes[j][4]) if finish_flag == 0: copy_stroke.append([ ...
Python
nomic_cornstack_python_v1
function _set_url_channel_max self value begin try begin set channel_max = integer value end except ValueError as exc begin raise call ValueError format string Invalid channel_max value {!r}: {!r} value exc end set channel_max = channel_max end function
def _set_url_channel_max(self, value): try: channel_max = int(value) except ValueError as exc: raise ValueError('Invalid channel_max value {!r}: {!r}'.format( value, exc, )) self.channel_max = channel_max
Python
nomic_cornstack_python_v1
function save_run_params_in_file folder_path filename run_config begin with open join path folder_path string run_params.conf string w as run_param_file begin for tuple attr value in sorted items __dict__ begin write run_param_file attr + string : + string value + string end end end function
def save_run_params_in_file(folder_path, filename, run_config): with open(path.join(folder_path, "run_params.conf"), 'w') as run_param_file: for attr, value in sorted(run_config.__dict__.items()): run_param_file.write(attr + ': ' + str(value) + '\n')
Python
nomic_cornstack_python_v1
from sklearn.datasets import load_breast_cancer from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_validate , KFold from numpy import mean from pandas import DataFrame from openpyxl import load_workbook import pandas as pd import matpl...
from sklearn.datasets import load_breast_cancer from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_validate, KFold from numpy import mean from pandas import DataFrame from openpyxl import load_workbook import pandas as pd impor...
Python
zaydzuhri_stack_edu_python
comment =-=-=-= DAY 78 [Medium] =-=-=-= comment Given k sorted singly linked lists, write a function to merge all the lists into comment one sorted singly linked list.
# =-=-=-= DAY 78 [Medium] =-=-=-= # # Given k sorted singly linked lists, write a function to merge all the lists into # one sorted singly linked list.
Python
zaydzuhri_stack_edu_python
function heuristic_3_correction h root_h begin comment resultant = set resultant = 1 - if expression h < root_h then h / root_h else 0 debug string Corrected heuristic value 3: { resultant } return resultant end function
def heuristic_3_correction(h: float, root_h: float): # resultant = resultant = 1 - ((h / root_h) if h < root_h else 0) logger.debug(f'Corrected heuristic value 3: {resultant}') return resultant
Python
nomic_cornstack_python_v1
function _per_cycle_intensities_to_signal_lognormal intensities per_cycle_parameters max_possible=5 begin raise call NotImplementedError end function
def _per_cycle_intensities_to_signal_lognormal(intensities, per_cycle_parameters, max_possible=5): raise NotImplementedError()
Python
nomic_cornstack_python_v1
comment print absolute value of an integer set a = input string please enter a number set a = integer a if a >= 0 begin print a end else begin print - a end
# print absolute value of an integer a = input ('please enter a number') a = int(a) if a >= 0: print (a) else: print (-a)
Python
zaydzuhri_stack_edu_python
function validate_fuzzer fuzzer begin if not match FUZZER_NAME_REGEX fuzzer begin raise exception string Fuzzer "%s" may only contain lowercase letters, numbers, or underscores. % fuzzer end set fuzzers_directories = call get_directories FUZZERS_DIR if fuzzer not in fuzzers_directories begin raise exception string Fuzz...
def validate_fuzzer(fuzzer: str): if not re.match(FUZZER_NAME_REGEX, fuzzer): raise Exception( 'Fuzzer "%s" may only contain lowercase letters, numbers, ' 'or underscores.' % fuzzer) fuzzers_directories = get_directories(FUZZERS_DIR) if fuzzer not in fuzzers_directories: ...
Python
nomic_cornstack_python_v1
import datasets import os import re from collections import Counter import tensorflow as tf from sklearn.model_selection import train_test_split comment Converts the unicode file to ascii function unicode_to_ascii s begin return join string generator expression c for c in call normalize string NFD s if call category c...
import datasets import os import re from collections import Counter import tensorflow as tf from sklearn.model_selection import train_test_split # Converts the unicode file to ascii def unicode_to_ascii(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ name type arguments=none defines=none depends_on=none description=none get_debug_info=none linked_service_name=none on_inactive_mark_as=none policy=none query_timeout=none script_linked_service=none script_path=none state=none storage_linked_services=none user_properties=none variables=none b...
def __init__(__self__, *, name: str, type: str, arguments: Optional[Sequence[Any]] = None, defines: Optional[Mapping[str, Any]] = None, depends_on: Optional[Sequence['outputs.ActivityDependencyResponse']] = None, descr...
Python
nomic_cornstack_python_v1
function load_data filename begin assert exists path filename == true set dat = call loadmat filename set inputs = dat at string inputs comment print len(inputs) set targets = dat at string targets comment print len(targets) assert length inputs == length targets global alldata global indim global outdim set indim = le...
def load_data(filename): assert os.path.exists(filename)==True dat = scipy.io.loadmat(filename) inputs = dat['inputs'] #print len(inputs) targets = dat['targets'] #print len(targets) assert len(inputs)==len(targets) global alldata global indim global outdim indim = len(inp...
Python
nomic_cornstack_python_v1
function _get_design self mean_part inno_part poly_orders begin if length poly_orders == 3 begin set mat_X = call _build_dmatrix mean_part poly_orders at 0 + 1 set mat_Z = call _build_dmatrix inno_part poly_orders at 1 + 1 set mat_W = call _build_mat_W poly_orders at 2 + 1 end else begin set mat_X = array call dmatrix ...
def _get_design(self, mean_part, inno_part, poly_orders): if len(poly_orders) == 3: mat_X = self._build_dmatrix(mean_part, poly_orders[0] + 1) mat_Z = self._build_dmatrix(inno_part, poly_orders[1] + 1) mat_W = self._build_mat_W(poly_orders[2] + 1) else: ...
Python
nomic_cornstack_python_v1
function CmndConverter valuemapping value idx readconverter writeconverter tasmotacmnd begin set result = none if callable readconverter and readconverter == passwordread or callable writeconverter and writeconverter == passwordwrite begin if value == HIDDEN_PASSWORD begin return none end else begin set result = value ...
def CmndConverter(valuemapping, value, idx, readconverter, writeconverter, tasmotacmnd): result = None if (callable(readconverter) and readconverter == passwordread) or (callable(writeconverter) and writeconverter == passwordwrite): if value == HIDDEN_PASSWORD: return None else: ...
Python
nomic_cornstack_python_v1
function diconnect_vpn self begin popen string net stop "Wacom Professional Service" shell=true call setIcon call QIcon string unlock.png call setToolTip string Pan GPS: Disconnected call showMessage string Pan GPS string Disconnected end function
def diconnect_vpn(self): subprocess.Popen('net stop "Wacom Professional Service"', shell=True) self.setIcon(QtGui.QIcon('unlock.png')) self.setToolTip('Pan GPS: Disconnected') self.showMessage('Pan GPS', 'Disconnected')
Python
nomic_cornstack_python_v1
function policy_assignment_id self begin return get pulumi self string policy_assignment_id end function
def policy_assignment_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "policy_assignment_id")
Python
nomic_cornstack_python_v1
function walklevel top_dir level=none begin set top_dir = right strip top_dir sep assert is directory path top_dir set num_sep = count top_dir sep for tuple root dirs files in walk top_dir begin yield tuple root dirs files if level is not none begin set num_sep_this = count root sep if num_sep + level <= num_sep_this b...
def walklevel(top_dir, level=None): top_dir = top_dir.rstrip(os.path.sep) assert os.path.isdir(top_dir) num_sep = top_dir.count(os.path.sep) for root, dirs, files in os.walk(top_dir): yield root, dirs, files if level is not None: num_sep_this = root.count(os.path.sep) ...
Python
nomic_cornstack_python_v1
function update self **kwargs begin for tuple field value in items kwargs begin set attribute self field value end save update_fields=list keys kwargs end function
def update(self, **kwargs): for field, value in kwargs.items(): setattr(self, field, value) self.save(update_fields=list(kwargs.keys()))
Python
nomic_cornstack_python_v1
function longSub count longestList currentList begin set i = count set lengList = currentList print string Current best: + string longestList set done = false while i < listLen + 1 and done == false begin if numlistsplit at i != string and done == false begin comment if the current element is greater than the previous...
def longSub(count, longestList, currentList): i = count lengList = currentList print("Current best: " + str(longestList)) done = False while i < listLen + 1 and done == False: if numlistsplit[i] != "" and done == False: if int(numlistsplit[i]) >= int(numlists...
Python
zaydzuhri_stack_edu_python
function load_PublicKey self file begin set public_key = call import_key read open file string rb end function
def load_PublicKey(self, file): self.public_key=RSA.import_key(open(file,"rb").read())
Python
nomic_cornstack_python_v1
function align_strs x y begin set lines_x = split x string set lines_y = split y string set max_len = max length lines_x length lines_y set result = string for i in range max_len begin if i < length lines_x begin set result = result + lines_x at i + string end if i < length lines_y begin set result = result + lines_y...
def align_strs(x,y): lines_x = x.split('\n') lines_y = y.split('\n') max_len = max(len(lines_x),len(lines_y)) result = "" for i in range(max_len): if i < len(lines_x): result += lines_x[i] + "\n" if i < len(lines_y): result += lines_y[i] + "\n" return result
Python
jtatman_500k
function sieve_of_eratosthenes n begin comment Create a boolean array "prime[0..n]" and initialize comment all entries it as true. A value in prime[i] will comment finally be false if i is Not a prime, else true. set prime = list comprehension true for i in range n + 1 set p = 2 while p * p <= n begin comment If prime[...
def sieve_of_eratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): # If prime[p] is not changed, th...
Python
iamtarun_python_18k_alpaca
comment 多个小球在画布中移动 from tkinter import * import random import time class Ball begin function __init__ self canvas color sx sy begin set canvas = canvas set id = call create_oval 20 20 55 55 fill=color move id sx sy comment 移动速度 set starts = list - 3 - 2 - 1 1 2 3 shuffle random starts set x = starts at 0 set y = starts...
#多个小球在画布中移动 from tkinter import * import random import time class Ball: def __init__(self,canvas,color,sx,sy): self.canvas = canvas self.id=canvas.create_oval(20,20,55,55,fill=color) self.canvas.move(self.id,sx,sy) starts=[-3,-2,-1,1,2,3]#移动速度 random.shuffle(starts)...
Python
zaydzuhri_stack_edu_python
function encodeSettingsJSONDict self begin set dct = call encodeSettingsJSONDict update dct dict string numberOfIterations _numberOfIterations ; string maximumSubIterations _maximumSubIterations ; string updateReferenceState _updateReferenceState return dct end function
def encodeSettingsJSONDict(self) -> dict: dct = super().encodeSettingsJSONDict() dct.update({ "numberOfIterations": self._numberOfIterations, "maximumSubIterations": self._maximumSubIterations, "updateReferenceState": self._updateReferenceState }) ...
Python
nomic_cornstack_python_v1
function test_callables_rendered begin set v_content = string {% <5 %}bla{% end %} set v_headers = dict string foo string {% <5 %}bar{% end %} set v_status = string {% <5 %}999{% end %} class TestFile extends File begin set content = lambda p -> tuple v_content true set headers = lambda p -> tuple v_headers true set st...
def test_callables_rendered(): v_content = '{% <5 %}bla{% end %}' v_headers = {'foo': '{% <5 %}bar{% end %}'} v_status = '{% <5 %}999{% end %}' class TestFile(test.File): content = lambda p: (v_content, True) headers = lambda p: (v_headers, True) status = lambda p: (v_st...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue May 02 16:50:38 2017 @author: Shah Faisal Mazhar comment Keep this .py file with the data file to get the result import xml.etree.cElementTree as ET comment Loading the xml file set tree = call ElementTree file=string CsI.xml set root = get root tree comment Creating ...
# -*- coding: utf-8 -*- """ Created on Tue May 02 16:50:38 2017 @author: Shah Faisal Mazhar """ #Keep this .py file with the data file to get the result import xml.etree.cElementTree as ET #Loading the xml file tree=ET.ElementTree(file="CsI.xml") root=tree.getroot() #Creating seperate files for each of the ...
Python
zaydzuhri_stack_edu_python
function build_batch_spec self batch_definition begin set batch_spec_params : dict = call _generate_batch_spec_parameters_from_batch_definition batch_definition=batch_definition comment batch_spec_passthrough via Data Connector config set batch_spec_passthrough : dict = deep copy batch_spec_passthrough comment batch_sp...
def build_batch_spec(self, batch_definition: BatchDefinition) -> BatchSpec: batch_spec_params: dict = ( self._generate_batch_spec_parameters_from_batch_definition( batch_definition=batch_definition ) ) # batch_spec_passthrough via Data Connector config ...
Python
nomic_cornstack_python_v1
function get_keywords target_dir ref_dir num_keywords min_freq begin comment get number of words and freqs in target and reference directories set tuple target_num_wds target_freqs = call get_num_wds_freqs target_dir set tuple ref_num_wds ref_freqs = call get_num_wds_freqs ref_dir comment calculate frequency ratio betw...
def get_keywords(target_dir, ref_dir, num_keywords, min_freq): # get number of words and freqs in target and reference directories target_num_wds, target_freqs = get_num_wds_freqs(target_dir) ref_num_wds, ref_freqs = get_num_wds_freqs(ref_dir) # calculate frequency ratio between target corpus and refe...
Python
nomic_cornstack_python_v1
function send_email subject content begin set gmail_address = CREDS at string gmail_address set gmail_password = CREDS at string gmail_password set message = call MIMEText content set message at string Subject = string survey.py complete set message at string From = gmail_address set message at string To = gmail_addres...
def send_email(subject, content): gmail_address = CREDS['gmail_address'] gmail_password = CREDS['gmail_password'] message = MIMEText(content) message['Subject'] = 'survey.py complete' message['From'] = gmail_address message['To'] = gmail_address
Python
nomic_cornstack_python_v1
function print_tree self spacing=string begin comment Base case: we've reached a leaf if is instance root Leaf begin print spacing + string Predict predictions return end comment Print the question at this node print spacing + string question comment Call this function recursively on the true branch print spacing + str...
def print_tree(self, spacing=""): # Base case: we've reached a leaf if isinstance(self.root, Leaf): print(spacing + "Predict", self.root.predictions) return # Print the question at this node print(spacing + str(self.root.question)) # Call this function ...
Python
nomic_cornstack_python_v1
function has_stp_cli self begin set cmd = call cli string show spanning-tree active return string enabled in cmd end function
def has_stp_cli(self): cmd = self.cli("show spanning-tree active") return " enabled " in cmd
Python
nomic_cornstack_python_v1
import os import random import re import sys import math from collections import Counter set DAMPING = 0.85 set SAMPLES = 10000 function main begin if length argv != 2 begin exit string Usage: python pagerank.py corpus end set corpus = call crawl argv at 1 set ranks = call sample_pagerank corpus DAMPING SAMPLES print s...
import os import random import re import sys import math from collections import Counter DAMPING = 0.85 SAMPLES = 10000 def main(): if len(sys.argv) != 2: sys.exit("Usage: python pagerank.py corpus") corpus = crawl(sys.argv[1]) ranks = sample_pagerank(corpus, DAMPING, SAMPLES) print(f"PageRan...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- set fileline = list with open string CONTCAR string r as f begin set lines = read lines f for line in lines begin append fileline split strip line end end set atomx = list for i in range 2 4 begin append atomx round decimal fileline at i at 0 4 end set atomy = li...
#!/usr/bin/python # -*- coding: utf-8 -*- fileline=[] with open ("CONTCAR",'r') as f: lines=f.readlines() for line in lines: fileline.append(line.strip().split()) atomx=[] for i in range(2,4): atomx.append(round(float(fileline[i][0]),4)) atomy=[] for i in range(2,4): atomy.appe...
Python
zaydzuhri_stack_edu_python
function rename_link_dialog self begin set old_link = string call text set rename_link_dialog = call QDialog set new_link_layout = call QVBoxLayout set link_name = call QLineEdit set button_box = call QDialogButtonBox call addButton Cancel call connect reject set link_create_btn = string Rename Link set link_create_btn...
def rename_link_dialog(self): old_link = str(self.sender().currentItem().text()) rename_link_dialog = QtGui.QDialog() new_link_layout = QtGui.QVBoxLayout() link_name = QtGui.QLineEdit() button_box = QtGui.QDialogButtonBox() button_box.addButton(QtGui.QDialogButtonBox....
Python
nomic_cornstack_python_v1
async function test_scan_devices_without_session_wrong_re hass aioclient_mock begin get aioclient_mock format string http://{}/common_page/login.html HOST cookies=dict string sessionToken string 654321 post format string http://{}/xml/getter.xml HOST content=b'successful' cookies=dict string sessionToken string 654321 ...
async def test_scan_devices_without_session_wrong_re(hass, aioclient_mock): aioclient_mock.get( "http://{}/common_page/login.html".format(HOST), cookies={'sessionToken': '654321'} ) aioclient_mock.post( "http://{}/xml/getter.xml".format(HOST), content=b'successful', c...
Python
nomic_cornstack_python_v1
function get_spectrum self leftchan=1 rightchan=- 1 begin return array call GetSpectrum leftchan rightchan end function
def get_spectrum(self, leftchan=1, rightchan=-1): return np.array(self.det.GetSpectrum(leftchan, rightchan))
Python
nomic_cornstack_python_v1
function _parse_network_settings opts current begin comment Normalize keys set opts = dictionary comprehension lower k : v for tuple k v in items opts set current = dictionary comprehension lower k : v for tuple k v in items current comment Check for supported parameters set retain_settings = get opts string retain_set...
def _parse_network_settings(opts, current): # Normalize keys opts = {k.lower(): v for (k, v) in opts.items()} current = {k.lower(): v for (k, v) in current.items()} # Check for supported parameters retain_settings = opts.get("retain_settings", False) result = {} if retain_settings: ...
Python
nomic_cornstack_python_v1
function resolve_file file begin if call is_file begin return string call Path file end if call is_file begin return string call Path expand user path file end raise call ValueError string File path ` { file } ` could not be resolved end function
def resolve_file(file: str) -> str: if Path(file).is_file(): return str(Path(file)) if Path(os.path.expanduser(file)).is_file(): return str(Path(os.path.expanduser(file))) raise ValueError(f"File path `{file}` could not be resolved")
Python
nomic_cornstack_python_v1
function plot_many_y_break_x x y yer=none xlabel=none ylabel=none ynames=none label=none domain=none domain_2=none frac=none yrange=none undertext=none savedir=none marker=none plotspecs=none groupings=none vlines=none legend_title=none n_legend_columns=none text=none begin if savedir is none begin set save_dir = get c...
def plot_many_y_break_x(x, y, yer=None, xlabel = None, ylabel = None, ynames = None, label = None, domain=None, domain_2=None, frac=None, yrange = None, undertext =None, savedir = None, marker=None, plotspecs = None, groupings=None, vlines = None, legend_title=None, n_leg...
Python
nomic_cornstack_python_v1
function use_move self a d move begin if name == string Switch begin return call send_out_lead_quietly team_id end if not call inhibitors a begin return end comment creating an actual Move object from the storage object set m = call unpack call set_up_move a m append channel string { name } used ** { name } **! set las...
def use_move(self, a: pk.Mon, d: pk.Mon, move: pk.PackedMove): if move.name == "Switch": return self.send_out_lead_quietly(a.team_id) if not self.inhibitors(a): return m = move.unpack() # creating an actual Move object from the storage object self.set...
Python
nomic_cornstack_python_v1
import sys import mrjob from mrjob.job import MRJob import re from itertools import islice , izip import itertools from mrjob.step import MRStep from mrjob.protocol import JSONValueProtocol set WORD_RE = compile string [a-zA-Z]+ class BigramCount extends MRJob begin set OUTPUT_PROTOCOL = JSONValueProtocol function mapp...
import sys import mrjob from mrjob.job import MRJob import re from itertools import islice, izip import itertools from mrjob.step import MRStep from mrjob.protocol import JSONValueProtocol WORD_RE = re.compile(r'[a-zA-Z]+') class BigramCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def map...
Python
jtatman_500k
comment An example of the back-tracking algorithm. comment Essentially, teaching a computer to find a word in a dictionary matching comment a given string of characters. comment This demonstrates the simple algorithm of backtracking using comment a one dimensional example -- matching letters from the Word Jumble commen...
# # An example of the back-tracking algorithm. # # Essentially, teaching a computer to find a word in a dictionary matching # a given string of characters. # # This demonstrates the simple algorithm of backtracking using # a one dimensional example -- matching letters from the Word Jumble # to letters in the dict...
Python
zaydzuhri_stack_edu_python
function Inject self pad=0 *args begin call AssertPadIndex pad for arg in args begin if is instance object tuple begin set tuple obj props = object if not is instance props dict begin raise call TypeError format string Injection failed: {} is not a valid format! arg end call Register obj pad keyword props end else begi...
def Inject(self, pad=0, *args): self.AssertPadIndex(pad) for arg in args: if isinstance(object, tuple): obj, props = object if not isinstance(props, dict): raise TypeError( "Injection failed: {} is not a valid format...
Python
nomic_cornstack_python_v1