code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/python comment -*- coding: utf-8 comment Appends a line with annotations to the previous verse comment For ASCII Encoding/Decoding of Inuktitut Syllabary import io import codecs import unicodedata import sys import re call reload sys call setdefaultencoding string utf8 set inputname = string input nam...
#!/usr/bin/python # -*- coding: utf-8 # Appends a line with annotations to the previous verse # For ASCII Encoding/Decoding of Inuktitut Syllabary import io import codecs import unicodedata import sys import re reload(sys) sys.setdefaultencoding('utf8') inputname = 'input name' outputname = 'output name' def conver...
Python
zaydzuhri_stack_edu_python
function tokenize self begin return _TOKENIZER end function
def tokenize(self): return self._TOKENIZER
Python
nomic_cornstack_python_v1
function chain self *arg **kw begin set result = none comment extract the static arguments (if any) from arg so they can comment be passed to each plugin call in the chain set static = list comprehension a for tuple static a in zip get attribute method string static_args list arg if static for tuple p meth in plugins b...
def chain(self, *arg, **kw): result = None # extract the static arguments (if any) from arg so they can # be passed to each plugin call in the chain static = [a for (static, a) in zip(getattr(self.method, 'static_args', []), arg) if static] for...
Python
nomic_cornstack_python_v1
function __init__ self odgt cfg begin comment parse options set cfg = cfg set imgSizes = imgSizes set imgMaxSize = imgMaxSize set padding_constant = padding_constant set root_dataset = root if is instance odgt list begin set list_sample = odgt end else if is instance odgt str begin set list_sample = list comprehension ...
def __init__( self, odgt, cfg: DictConfig ): # parse options self.cfg = cfg self.imgSizes = self.cfg.datamodule.imgSizes self.imgMaxSize = self.cfg.datamodule.imgMaxSize self.padding_constant = self.cfg.datamodule.padding_constant self.root_dataset = self...
Python
nomic_cornstack_python_v1
import math import random from vector import Vector2d , DirectionalVector from bezier import make_bezier class Space begin set LISTENER_POSITION = call Vector2d 0 0 set ROOM_RADIUS = 30 set NEAREST_DISTANCE_TO_LISTENER = 0.1 set MIN_CURVATURE = 50.0 / 360 * 2 * pi set MAX_CURVATURE = 80.0 / 360 * 2 * pi set TRAJECTORY_...
import math import random from vector import Vector2d, DirectionalVector from bezier import make_bezier class Space: LISTENER_POSITION = Vector2d(0, 0) ROOM_RADIUS = 30 NEAREST_DISTANCE_TO_LISTENER = 0.1 MIN_CURVATURE = 50.0 / 360 * 2*math.pi MAX_CURVATURE = 80.0 / 360 * 2*math.pi TRAJECTORY_PR...
Python
zaydzuhri_stack_edu_python
function kill_calibrators self begin if calibrator_popen is not none begin call send_signal SIGINT set calibrator_popen = none end end function
def kill_calibrators(self): if self.calibrator_popen is not None: self.calibrator_popen.send_signal(subprocess.signal.SIGINT) self.calibrator_popen = None
Python
nomic_cornstack_python_v1
import logging import os import sys from utils import slack from utils import git from github import UnknownObjectException call basicConfig format=string %(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d:%(funcName)s] %(message)s level=INFO set logger = call getLogger __name__ function main begin comment TODO: add ...
import logging import os import sys from utils import slack from utils import git from github import UnknownObjectException logging.basicConfig( format="%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d:%(funcName)s] %(message)s", level=logging.INFO ) logger = logging.getLogger(__name__) def main(): #...
Python
zaydzuhri_stack_edu_python
from random import randint import rotations import solving comment Brings the cube to the solved state (by setting the colors of the blocks) function cube_to_solved begin set cube = tuple list string string string string string string string string string list string string string string string string st...
from random import randint import rotations import solving # Brings the cube to the solved state (by setting the colors of the blocks) def cube_to_solved(): cube = ['','','','','','','','',''],['','','','','','','','',''],['','','','','','','','',''],['','','','','','','','',''],['','','','','','','','',''...
Python
zaydzuhri_stack_edu_python
string 勒让德正交多项式 import math import numpy as np import matplotlib.pyplot as plt function chengji fx1 fx2 n1 n2 begin set ans = list for n in range n1 + n2 - 1 begin set temp = 0 for i in range n1 begin if n - i < 0 begin break end else if n - i >= n2 begin continue end else begin set temp = temp + fx1 at i * fx2 at n -...
''' 勒让德正交多项式 ''' import math import numpy as np import matplotlib.pyplot as plt def chengji(fx1, fx2, n1, n2): ans = [] for n in range(n1 + n2 - 1): temp = 0 for i in range(n1): if (n - i < 0): break elif (n - i >= n2): continue ...
Python
zaydzuhri_stack_edu_python
function sntl model num_classes dataset k teacher power_iter norm_beta freeze_bn reuse_statistic reuse_teacher_statistic begin set save_name = string sntl_ { power_iter } _ { norm_beta } _ { if expression freeze_bn then string True else string False } _ { if expression reuse_teacher_statistic then string rts_ else stri...
def sntl(model, num_classes, dataset, k, teacher, power_iter, norm_beta, freeze_bn, reuse_statistic, reuse_teacher_statistic): save_name = f"sntl_{power_iter}_{norm_beta}_" \ f"{'True' if freeze_bn else 'False'}_" \ f"{'rts_' if reuse_teacher_statistic else ''}" \ ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Dec 28 12:20:39 2020 @author: Raghu import pyttsx3 import datetime import speech_recognition as sr import wikipedia import smtplib import webbrowser as wb import os comment taking screenshots import pyautogui comment for battery,cpu updates import psutil import pyjoke...
# -*- coding: utf-8 -*- """ Created on Sat Dec 28 12:20:39 2020 @author: Raghu """ import pyttsx3 import datetime import speech_recognition as sr import wikipedia import smtplib import webbrowser as wb import os import pyautogui #taking screenshots import psutil #for battery,cpu updates import pyjokes engine = py...
Python
zaydzuhri_stack_edu_python
import random comment slownik znakow set sz = string abcdefghijklmnoprstwxyzqABCDEFGHIJKLMNOPRSTXYZQ@!$ set iloscZnakow = 8 set haslo = join string random sample sz iloscZnakow print haslo
import random #slownik znakow sz = 'abcdefghijklmnoprstwxyzqABCDEFGHIJKLMNOPRSTXYZQ@!$' iloscZnakow = 8 haslo = "".join(random.sample(sz,iloscZnakow)) print(haslo)
Python
zaydzuhri_stack_edu_python
function print_grid grid begin set minz = min keys grid set maxz = max keys grid set miny = 0 set maxy = 0 set minx = 0 set maxx = 0 for tuple z planes in items grid begin if length planes begin set miny = min miny min planes set maxy = max maxy max planes end for lines in values grid at z begin if length lines begin s...
def print_grid(grid): minz = min(grid.keys()) maxz = max(grid.keys()) miny = 0 maxy = 0 minx = 0 maxx = 0 for z, planes in grid.items(): if len(planes): miny = min(miny, min(planes)) maxy = max(maxy, max(planes)) for lines in grid[z].values(): ...
Python
zaydzuhri_stack_edu_python
function updateApsLabels self begin set label_format = guiApsLabels + string %d call forceRender end function
def updateApsLabels(self): self.apsLabels.mapper.label_format = (self.guiApsLabels + " %d") self.forceRender()
Python
nomic_cornstack_python_v1
import math function calculate_area sides begin comment Triangle if length sides == 3 begin set tuple a b c = sides comment Semiperimeter set s = a + b + c / 2 set area = square root s * s - a * s - b * s - c return area end else comment Quadrilateral if length sides == 4 begin set tuple a b c d = sides set area = a * ...
import math def calculate_area(sides): if len(sides) == 3: # Triangle a, b, c = sides s = (a + b + c) / 2 # Semiperimeter area = math.sqrt(s * (s - a) * (s - b) * (s - c)) return area elif len(sides) == 4: # Quadrilateral a, b, c, d = sides area = (a * b * c *...
Python
greatdarklord_python_dataset
comment This is an infinite loop that has a breakout key set number = 0 set total = 0 while true begin set x = input string enter a number if x == string end begin break end try begin set xval = integer x end except any begin print string that is not valid input continue end set total = total + 1 set number = number + ...
# This is an infinite loop that has a breakout key number=0 total=0 while True: x=input('enter a number') if x=='end': break try: xval=int(x) except: print('that is not valid input') continue ...
Python
zaydzuhri_stack_edu_python
from mlstocks.tipranks import download_stats_tipranks from mlstocks.yahoo_finance import download_stats_yahoo , download_history_yahoo set ticker = string AAPL comment --- Download statistics set tuple basic_stats all_stats = call download_stats_tipranks ticker print string ----------- Basic stats print basic_stats pri...
from mlstocks.tipranks import download_stats_tipranks from mlstocks.yahoo_finance import download_stats_yahoo, download_history_yahoo ticker='AAPL' # --- Download statistics basic_stats, all_stats = download_stats_tipranks(ticker) print('----------- Basic stats') print(basic_stats) print('----------- Advanced stat...
Python
zaydzuhri_stack_edu_python
class Solution begin function majorityElement self nums begin string :type nums: List[int] :rtype: int sort nums return nums at length nums // 2 end function end class if __name__ == string __main__ begin set nums = list 2 2 1 1 1 2 2 print call majorityElement nums end
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return nums[len(nums)//2] if __name__ == "__main__": nums = [2,2,1,1,1,2,2] print(Solution().majorityElement(nums))
Python
zaydzuhri_stack_edu_python
function load_feature feature_name caf_dose features_path begin comment gets the paths to the folders where the specified feature is stored set subject_paths = glob glob join path features_path string * feature_name set feature = dict for path in subject_paths begin comment extract the subject id from the current path...
def load_feature(feature_name, caf_dose, features_path): # gets the paths to the folders where the specified feature is stored subject_paths = glob.glob(os.path.join(features_path, "*", feature_name)) feature = {} for path in subject_paths: # extract the subject id from the current path (second...
Python
nomic_cornstack_python_v1
function get_code_num_rgb s begin string Get rgb code numbers from an RGB escape code. Raises InvalidRgbEscapeCode if an invalid number is found. set parts = split s string ; if length parts != 5 begin raise call InvalidRgbEscapeCode s reason=string Count is off. end set rgbparts = parts at slice - 3 : : if not ends ...
def get_code_num_rgb(s: str) -> Optional[Tuple[int, int, int]]: """ Get rgb code numbers from an RGB escape code. Raises InvalidRgbEscapeCode if an invalid number is found. """ parts = s.split(';') if len(parts) != 5: raise InvalidRgbEscapeCode(s, reason='Count is off.') rgbparts = p...
Python
jtatman_500k
comment For web scrapping task we need to insatall bs4 module comment For install that module type "pip.exe install bs4" command line into cmd comment After that import BeautifulSoup from bs4 module from bs4 import BeautifulSoup import requests set search = input string Enter search Term: set params = dict string q sea...
# For web scrapping task we need to insatall bs4 module # For install that module type "pip.exe install bs4" command line into cmd # After that import BeautifulSoup from bs4 module from bs4 import BeautifulSoup import requests search = input('Enter search Term:') params = {"q": search} # url = {"https://www.bing.com...
Python
zaydzuhri_stack_edu_python
import numpy as np class Directional begin function __init__ self direction ambient_intensity=0.4 local_intensity=0.6 color=none begin string Define directional light. Only required parameter is direction, all others will set to default values set direction = array direction comment Normalized vector pointing towards l...
import numpy as np class Directional: def __init__(self, direction, ambient_intensity=0.4, local_intensity=0.6, color=None): """ Define directional light. Only required parameter is direction, all others will set to default values """ self.direction = np.array(direction) # Normalized vect...
Python
zaydzuhri_stack_edu_python
import os from flask import Flask set app = call Flask __name__ comment Retorna el contenido de un archivo function contenido_de_archivo ruta begin with open ruta string r as archivo begin set contenido = read archivo end return contenido end function decorator call route string / comment Index de la pagina function in...
import os from flask import Flask app = Flask(__name__) #Retorna el contenido de un archivo def contenido_de_archivo(ruta): with open(ruta, 'r') as archivo: contenido = archivo.read() return contenido #Index de la pagina @app.route("/") def index(): return contenido_de_archivo("demos/fixed/index3.html") #Est...
Python
zaydzuhri_stack_edu_python
function find_substring string substring begin comment Find the index of the substring in the string set index = find string substring comment If the substring is found, return True and the index if index != - 1 begin return tuple true index end comment If the substring is not found, return False and -1 as the index re...
def find_substring(string, substring): # Find the index of the substring in the string index = string.find(substring) # If the substring is found, return True and the index if index != -1: return True, index # If the substring is not found, return False and -1 as the index return False...
Python
greatdarklord_python_dataset
from __future__ import print_function import os from pprint import pprint import requests from pympler import asizeof function part_of_merge r c merges begin for merge in merges begin if merge at string startRowIndex <= r < merge at string endRowIndex and merge at string startColumnIndex <= c < merge at string endColum...
from __future__ import print_function import os from pprint import pprint import requests from pympler import asizeof def part_of_merge(r, c, merges): for merge in merges: if ( merge["startRowIndex"] <= r < merge["endRowIndex"] and merge["startColumnIndex"] <= c < merge["endColumn...
Python
zaydzuhri_stack_edu_python
function cyan cls s begin return call _wrap_colour s CYAN end function
def cyan(cls, s): return cls._wrap_colour(s, cls.CYAN)
Python
nomic_cornstack_python_v1
function ner_features tokens index history begin comment Pad the sequence with placeholders set tokens = list tuple string __START2__ string __START2__ tuple string __START1__ string __START1__ + list tokens + list tuple string __END1__ string __END1__ tuple string __END2__ string __END2__ set history = list string __S...
def ner_features(tokens, index, history): # Pad the sequence with placeholders tokens = [('__START2__', '__START2__'), ('__START1__', '__START1__')] + list(tokens) + [('__END1__', '__END1__'), ('__END2__', '__END2__')] ...
Python
nomic_cornstack_python_v1
function histogram_elements example_list begin set histogram = dict for i in example_list begin set histogram at i = count example_list i end return histogram end function
def histogram_elements(example_list): histogram = {} for i in example_list: histogram[i] = example_list.count(i) return histogram
Python
iamtarun_python_18k_alpaca
function getLength self begin return sideLength end function
def getLength(self): return self.sideLength
Python
nomic_cornstack_python_v1
for _ in call xrange input begin set N = input set A = map int split call raw_input set HT = dict for a in A begin set HT at a = 1 end end
for _ in xrange(input()): N = input() A = map(int, raw_input().split()) HT = {} for a in A: HT[a] = 1
Python
zaydzuhri_stack_edu_python
string Note: Please run the code in google colab or jupyter notebook to avoid unnecessary errors string Note: Uncomment the below code only if run in google colab Download the load2vec model comment !python -m spacy download en_core_web_md string Import the spacy library and load the word2vec model import spacy set nlp...
""" Note: Please run the code in google colab or jupyter notebook to avoid unnecessary errors """ """ Note: Uncomment the below code only if run in google colab Download the load2vec model """ #!python -m spacy download en_core_web_md """ Import the spacy library and load the word2vec model """ import spacy nlp = s...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import math function main begin set resultat = call pointimage 350 0 250 1300 600 set indice = call testimage resultat return indice end function function calculnormale intersec begin string calcul la normale à la surface du cylindre au point intersec set x = dot list ...
import numpy as np import matplotlib.pyplot as plt import math def main(): resultat = pointimage(350,0,250,1300,600) indice = testimage(resultat) return indice def calculnormale(intersec): """calcul la normale à la surface du cylindre au point intersec""" x = intersec.dot([1,0,0]) y = inte...
Python
zaydzuhri_stack_edu_python
comment 골드바흐의 추측 comment https://www.acmicpc.net/problem/6588 import sys import math function isPrime num begin if num == 1 begin return false end for i in range 2 integer square root num + 1 begin if num % i == 0 begin return false end end return true end function function checkConjecture target begin comment 4 set ha...
#골드바흐의 추측 #https://www.acmicpc.net/problem/6588 import sys import math def isPrime(num): if num == 1: return False for i in range(2, int(math.sqrt(num))+1): if num % i == 0: return False return True def checkConjecture(target): #4 half = int(target/2) for...
Python
zaydzuhri_stack_edu_python
function forward_reinforce self prob target reward cuda=false begin set N = size target 0 set C = size prob 1 set one_hot = zeros tuple N C if cuda begin set one_hot = cuda one_hot end call scatter_ 1 view data tuple - 1 1 1 set one_hot = type ByteTensor set one_hot = call Variable one_hot if cuda begin set one_hot = c...
def forward_reinforce(self, prob, target, reward, cuda=False): N = target.size(0) C = prob.size(1) one_hot = torch.zeros((N, C)) if cuda: one_hot = one_hot.cuda() one_hot.scatter_(1, target.data.view((-1,1)), 1) one_hot = one_hot.type(torch.ByteTensor) ...
Python
nomic_cornstack_python_v1
string Python 3.8.5 64-bit Author: Adam Turner <turner.adch@gmail.com> Based on a scrapy spider written by Liam Xiao. comment pypi import requests import lxml.html import sqlalchemy import numpy as np import pandas as pd comment standard library import pathlib from datetime import datetime comment local import conndb f...
""" Python 3.8.5 64-bit Author: Adam Turner <turner.adch@gmail.com> Based on a scrapy spider written by Liam Xiao. """ # pypi import requests import lxml.html import sqlalchemy import numpy as np import pandas as pd # standard library import pathlib from datetime import datetime # local import conndb from validation im...
Python
zaydzuhri_stack_edu_python
function lastmod self category begin string Return the last modification of the entry. set lastitems = call only string modification_date return modification_date end function
def lastmod(self, category): """Return the last modification of the entry.""" lastitems = EntryModel.objects.published().order_by('-modification_date').filter(categories=category).only('modification_date') return lastitems[0].modification_date
Python
jtatman_500k
function main_background begin call fill COLOR_BACKGROUND end function
def main_background(): surface.fill(COLOR_BACKGROUND)
Python
nomic_cornstack_python_v1
function test_udp_alt_iteration begin set cmd = list string python string dnsck/dnsck.py string -s string 8.8.8.8 string google.com string -i string 1 set process = run cmd shell=false check=true assert returncode == 0 end function
def test_udp_alt_iteration(): cmd = ["python", "dnsck/dnsck.py", "-s", "8.8.8.8", "google.com", "-i", "1"] process = subprocess.run(cmd, shell=False, check=True) assert process.returncode == 0
Python
nomic_cornstack_python_v1
function retrieve_public_genesets options=dict retrieve_all=false begin set genesets_url = TRIBE_URL + string /api/v1/geneset/ set genesets = list set tribe_connection = get requests genesets_url params=options set error_template_string = string Error when retrieving public genesets from tribe. Got response from Trib...
def retrieve_public_genesets(options={}, retrieve_all=False): genesets_url = TRIBE_URL + '/api/v1/geneset/' genesets = [] tribe_connection = requests.get(genesets_url, params=options) error_template_string = ( "Error when retrieving public genesets from tribe. " "Got response from Tr...
Python
nomic_cornstack_python_v1
function f_W_T_to_P_T_gc u P_0 r_f d s T wealth alpha_0 alpha_1 begin set tuple beta_0 beta_1 beta_2 = call f_beta P_0 r_f d s T set P_T = call f_P_T u P_0 r_f d s T set ln_P_T = call f_ln_P_T u P_0 r_f d s T if ln_P_T > - beta_1 / 2 * beta_2 begin set W_T = call f_W_T_gc u P_0 r_f d s T wealth alpha_0 alpha_1 set R_T ...
def f_W_T_to_P_T_gc(u, P_0, r_f, d, s, T, wealth, alpha_0, alpha_1): (beta_0, beta_1, beta_2) = f_beta(P_0, r_f, d, s, T) P_T = f_P_T(u, P_0, r_f, d, s, T) ln_P_T = f_ln_P_T(u, P_0, r_f, d, s, T) if ln_P_T > - beta_1 / (2 * beta_2): W_T = f_W_T_gc(u, P_0, r_f, d, s, T, wealth, alpha_0,...
Python
nomic_cornstack_python_v1
function load_Mitochondria self dataset_dir subset begin comment Add classes. We have only one class to add. call add_class string Mitochondria 1 string Mitochondria comment Train or validation dataset? assert subset in list string train string val set dataset_dir = join path dataset_dir subset for filename in list dir...
def load_Mitochondria(self, dataset_dir, subset): # Add classes. We have only one class to add. self.add_class("Mitochondria", 1, "Mitochondria") # Train or validation dataset? assert subset in ["train", "val"] dataset_dir = os.path.join(dataset_dir, subset) for filena...
Python
nomic_cornstack_python_v1
function test_loggin_required self begin set response = get client RESGATE_URL assert equal status_code HTTP_401_UNAUTHORIZED end function
def test_loggin_required(self): response = self.client.get(RESGATE_URL) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Python
nomic_cornstack_python_v1
function normalize_key_for_search library_key begin return replace library_key version_guid=none branch=none end function
def normalize_key_for_search(library_key): return library_key.replace(version_guid=None, branch=None)
Python
nomic_cornstack_python_v1
function calculate_error k_means_matrix begin return sum list comprehension min dist for dist in k_means_matrix end function
def calculate_error(k_means_matrix): return sum([min(dist) for dist in k_means_matrix])
Python
nomic_cornstack_python_v1
function move self state action begin set newx = state at 0 + action at 0 set newy = state at 1 + action at 1 if newx < 0 begin return false end if newx > xlim - 1 begin return false end if newy < 0 begin return false end if newy > ylim - 1 begin return false end return list newx newy end function
def move(self, state, action): newx = state[0] + action[0] newy = state[1] + action[1] if newx < 0: return False if newx > self.xlim - 1: return False if newy < 0: return False if newy > self.ylim - 1: return False ...
Python
nomic_cornstack_python_v1
from tokenrules import tokens from ast import * set precedence = tuple tuple string right string ASSIGN tuple string nonassoc string COMPARE function p_statements p begin string statements : statements_list set p at 0 = call Statements p at 1 end function function p_statements_list p begin string statements_list : stat...
from tokenrules import tokens from ast import * precedence = ( ('right', 'ASSIGN'), ('nonassoc', 'COMPARE'), ) def p_statements(p): '''statements : statements_list''' p[0] = Statements(p[1]) def p_statements_list(p): '''statements_list : statement statements_list | ''' ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import math comment //////////////////////////////////////////////////////////////////////////////// Read Data set donor = read csv string Donors.csv comment print(donor) set hospital = read csv string Hospitals.csv comment print(hospital) comment ////////////////////////////////////////////////////...
import pandas as pd import math # //////////////////////////////////////////////////////////////////////////////// Read Data donor = pd.read_csv('Donors.csv') # print(donor) hospital = pd.read_csv('Hospitals.csv') # print(hospital) # /////////////////////////////////////////////////////////////////////////////// D...
Python
zaydzuhri_stack_edu_python
function check_neutron_notifications_toolchain self begin call revert_snapshot string deploy_toolchain call check_plugins_online call check_neutron_notifications end function
def check_neutron_notifications_toolchain(self): self.env.revert_snapshot("deploy_toolchain") self.check_plugins_online() self.check_neutron_notifications()
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string test the almost a circle project import unittest from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestClassMerthods extends TestCase begin string test the almost a circle project function test_Base_id self begin assert equal id 1...
#!/usr/bin/python3 """test the almost a circle project""" import unittest from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestClassMerthods(unittest.TestCase): """test the almost a circle project""" def test_Base_id(self): self.assertEqual(B...
Python
zaydzuhri_stack_edu_python
comment intersection () method returns a set of intersection between two sets print intersection set1 set2 comment difference () method returns a set of differences in two sets comment chem set2 otlichaetsja ot set1 print difference set2 set1 print difference set1 set2 comment union ()method will return a set of all va...
#intersection () method returns a set of intersection between two sets print(set1.intersection(set2)) # difference () method returns a set of differences in two sets print(set2.difference(set1)) # chem set2 otlichaetsja ot set1 print(set1.difference(set2)) #union ()method will return a set of all value from both sets ...
Python
zaydzuhri_stack_edu_python
function extractCityData city_url begin set city_data = list set error_file = writer open ERRORS string wb comment get state and city name set city = replace base name path city_url string - string set state = replace base name path directory name path city_url string - string comment grab html of city page try begin ...
def extractCityData(city_url): city_data = [] error_file = csv.writer(open(ERRORS, 'wb')) # get state and city name city = os.path.basename(city_url).replace('-', ' ') state = os.path.basename(os.path.dirname(city_url)).replace('-', ' ') # grab html of city page try: city_site = lxml.html.parse(cit...
Python
nomic_cornstack_python_v1
function distance l1 l2 begin set length = length l1 if length l2 < length begin set length = length l2 end set sum = 0 for i in range length begin set sum = sum + l1 at i - l2 at i ^ 2 end set d = square root sum return d end function
def distance(l1,l2): length = len(l1) if len(l2) < length: length = len(l2) sum = 0 for i in range(length): sum += (l1[i]-l2[i])**2 d = math.sqrt(sum) return d
Python
nomic_cornstack_python_v1
import networkx as nx from abc import ABC , abstractmethod class AbstractRankingSystem extends ABC begin string decorator abstractmethod function getNodesRanking self graph begin raise NotImplementedError end function function setNodesRank self graph ranking drawMode=false begin string Set rank attribute for each node...
import networkx as nx from abc import ABC, abstractmethod class AbstractRankingSystem(ABC): """ """ @abstractmethod def getNodesRanking(self, graph): raise NotImplementedError def setNodesRank(self, graph, ranking, drawMode=False): """ Set rank attribute for each node in th...
Python
zaydzuhri_stack_edu_python
function spin self seconds begin set time_end = time + seconds while time < time_end begin call processEvents end end function
def spin(self, seconds): time_end = time.time() + seconds while time.time() < time_end: QApplication.processEvents()
Python
nomic_cornstack_python_v1
function uid_split groups begin comment This method should really be built into gob somehow. return generator expression tuple group id for tuple group ids in groups for id in ids end function
def uid_split(groups): # This method should really be built into gob somehow. return ( (group, id) for group,ids in groups for id in ids )
Python
nomic_cornstack_python_v1
from keras.datasets import reuters from keras import models from keras import layers import numpy as np import matplotlib.pyplot as plt function vectorize_sequences sequences dimension=10000 begin string Method to vectorize data. Args: sequences (array): An array of newswires as lists of word indices dimension (int, op...
from keras.datasets import reuters from keras import models from keras import layers import numpy as np import matplotlib.pyplot as plt def vectorize_sequences(sequences: list, dimension=10000): """Method to vectorize data. Args: sequences (array): An array of newswires as lists of word indices ...
Python
zaydzuhri_stack_edu_python
class Trie begin function __init__ self begin set trie = dict end function function addSentence self sentence weight begin set trie = trie set sentence_hash = call hash sentence for c in sentence begin if c not in trie begin set trie at c = dict string sentences list ; string freq dict end set trie = trie at c if se...
class Trie: def __init__(self): self.trie={} def addSentence(self,sentence,weight): trie=self.trie sentence_hash=hash(sentence) for c in sentence: if(c not in trie): trie[c]={"sentences":[],"freq":{}} trie=trie[c] if(sentence_ha...
Python
zaydzuhri_stack_edu_python
function drop self begin set being = subject set items = get body if items begin set item = items at 0 call move_item_from_being_to_map item being raise call Handled end end function
def drop(self): being = self.subject items = being.body.get() if items: item = items[0] self.session.hax2.move_item_from_being_to_map(item, being) raise event.Handled()
Python
nomic_cornstack_python_v1
comment input of dict_list can be taken from user also set dict_list = list dict string name string affirm ; string confidence 0.9448149204254 dict string name string affirm ; string confidence 0.944814920425415 dict string name string inform ; string confidence 0.9842240810394287 dict string name string inform ; strin...
#input of dict_list can be taken from user also dict_list=[{'name': 'affirm', 'confidence': 0.9448149204254}, {'name': 'affirm', 'confidence': 0.944814920425415}, {'name': 'inform', 'confidence': 0.9842240810394287}, {'name': 'inform', 'confidence': 0.9842240810394287}] output = [] for dict in dict_list: f=0 ...
Python
zaydzuhri_stack_edu_python
function __init__ self pattern flags=0 begin if flags begin set str_flags = call decodeflags flags set pattern = string (?%s:%s) % tuple str_flags pattern end call __init__ pattern end function
def __init__(self, pattern, flags=0): if flags: str_flags = hre.decodeflags(flags) pattern = r"(?%s:%s)"%(str_flags, pattern) super(Regex, self).__init__(pattern)
Python
nomic_cornstack_python_v1
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
function run_captured working_path *cmd check=true begin call assert_working_path working_path set git_cmd = list cmd insert git_cmd 0 string git comment type: Dict[str, Any] set options = dictionary set options at string stdout = PIPE set options at string stderr = STDOUT debug lightgray working_path string $ reset *g...
def run_captured(working_path: Path, *cmd: str, check: bool = True) -> Tuple[int, str]: assert_working_path(working_path) git_cmd = list(cmd) git_cmd.insert(0, "git") options = dict() # type: Dict[str, Any] options["stdout"] = subprocess.PIPE options["stderr"] = subprocess.STDOUT ui.debug(...
Python
nomic_cornstack_python_v1
function preProcessImage imagePath model input_height input_width begin set image = call load_img imagePath target_size=tuple input_height input_width set image = call img_to_array image set image = reshape np image tuple 1 input_height input_width 3 if model == string VGG16 begin set image = call preprocess_input imag...
def preProcessImage(imagePath, model, input_height, input_width): image = I.load_img(imagePath, target_size=(input_height, input_width)) image = I.img_to_array(image) image = np.reshape(image,(1, input_height, input_width,3)) if model == 'VGG16': image = preprocess_input(image) elif model ==...
Python
nomic_cornstack_python_v1
import random comment Returns the user's input function get_integer message=string Enter a number: reqLength=0 begin comment Uses try to check in pInput is an integer when converting try begin comment Gets the input set pInput = input message comment Checks if reqLength was set if length pInput == 0 begin pass end else...
import random # Returns the user's input def get_integer(message = "Enter a number: ", reqLength = 0): # Uses try to check in pInput is an integer when converting try: # Gets the input pInput = input(message) # Checks if reqLength was set if len(pInput) == 0: ...
Python
zaydzuhri_stack_edu_python
from params import getParams from scipy.stats import laplace , norm from ystockquote import get_price from operator import mul from numpy import exp from bs import BlackScholes from functools import reduce class futurePrice begin function __init__ self ticker begin set ticker = ticker set params = call getParams ticker...
from params import getParams from scipy.stats import laplace, norm from ystockquote import get_price from operator import mul from numpy import exp from bs import BlackScholes from functools import reduce class futurePrice(): def __init__(self, ticker): self.ticker = ticker params = getParams(tic...
Python
zaydzuhri_stack_edu_python
function recovery_onchain_dialog self inputs outputs recovery_keypairs begin set external_keypairs = none set invoice = none comment trusted coin requires this if call run_hook string abort_send self begin return end set is_sweep = false set make_tx = lambda fee_est -> call make_unsigned_transaction coins=inputs output...
def recovery_onchain_dialog(self, inputs, outputs, recovery_keypairs): external_keypairs = None invoice = None # trusted coin requires this if run_hook('abort_send', self): return is_sweep = False make_tx = lambda fee_est: self.wallet.make_unsigned_transaction...
Python
nomic_cornstack_python_v1
function take_screenshot self filepath begin call get_screenshot_as_file filepath end function
def take_screenshot(self, filepath): self.driver.get_screenshot_as_file(filepath)
Python
nomic_cornstack_python_v1
function spam begin global eggs set eggs = 43 print eggs end function set eggs = 42 call spam print eggs
def spam(): global eggs eggs = 43 print(eggs) eggs = 42 spam() print(eggs)
Python
zaydzuhri_stack_edu_python
function relative_rate self begin return call sink_f_sptr_relative_rate self end function
def relative_rate(self): return _qtgui_swig.sink_f_sptr_relative_rate(self)
Python
nomic_cornstack_python_v1
from __future__ import division import numpy as np import sys import math import pandas as pd function meancov f1 begin set virginica = list set versicolor = list set setosa = list for each in f1 begin set classvar = split each string , if classvar at 4 == string Iris-virginica begin append virginica classvar at sli...
from __future__ import division import numpy as np import sys import math import pandas as pd def meancov(f1): virginica=[] versicolor=[] setosa=[] for each in f1: classvar=each.split(',') if(classvar[4]=="Iris-virginica"): virginica.append(classvar[0:4]) elif(class...
Python
zaydzuhri_stack_edu_python
function _create_answers_dict self answers_json_path begin comment There are no answers in the test dataset if dataset_type == TEST and not val_test_split begin return dict end print string Loading VQA answers data from -> answers_json_path set answers_json = load json open answers_json_path comment Please note that a...
def _create_answers_dict(self, answers_json_path): # There are no answers in the test dataset if self.dataset_type == DatasetType.TEST and not self.val_test_split: return {} print('Loading VQA answers data from ->', answers_json_path) answers_json = json.load(open(answers_j...
Python
nomic_cornstack_python_v1
function add_counters_for_all_exercises df exercises counters time_windows begin for exercise_code in call tqdm exercises desc=string Adding the counters for { length exercises } exercises begin set df = call add_exercise_code_counters_for_each_time_window df exercise_code counters time_windows end return df end functi...
def add_counters_for_all_exercises( df: pd.DataFrame, exercises: tuple, counters: tuple, time_windows: tuple ) -> pd.DataFrame: for exercise_code in tqdm( exercises, desc=f"Adding the counters for {len(exercises)} exercises" ): df = add_exercise_code_counters_for_each_time_window( ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment Introduction to Programming Exercises. comment Exercise :Area of a Field. string Create a program that reads the lenght and width of a farmer's field from the user in feet. Display the area of the field in acres. Hint: There are 43,560 square feet in a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Introduction to Programming Exercises. # Exercise :Area of a Field. """ Create a program that reads the lenght and width of a farmer's field from the user in feet. Display the area of the field in acres. Hint: There are 43,560 square feet in an acre. """ ACRE = 4356...
Python
zaydzuhri_stack_edu_python
function string_to_float string begin set _SCALE_FACTOR_DICT = dict string P 1000000000000000.0 ; string T 1000000000000.0 ; string G 1000000000.0 ; string M 1000000.0 ; string K 1000.0 ; string k 1000.0 ; string _ 1 ; string % 0.01 ; string c 0.01 ; string m 0.001 ; string u 1e-06 ; string n 1e-09 ; string p 1e-12 ; s...
def string_to_float(string): _SCALE_FACTOR_DICT = {'P':1e15, 'T':1e12, 'G':1e9, 'M':1e6, 'K':1e3, 'k':1e3, '_':1, '%':1e-2, 'c':1e-2, 'm':1e-3, 'u':1e-6, 'n':1e-9, 'p':1e-12, 'f':1e-15, 'a':1e-18, 'z':1e-21, 'y':1e-24} if (type(string) == float) or (type(strin...
Python
nomic_cornstack_python_v1
function get_ali_and_center self begin return list comprehension tuple v call get_center f for tuple f v in enumerate data end function
def get_ali_and_center(self): return [(v, self.get_center(f)) \ for f, v in enumerate(self.data)]
Python
nomic_cornstack_python_v1
function pop self begin if call is_empty begin raise EmptyError end set ptr = ptr - 1 return stk at ptr end function
def pop(self) -> Any: if self.is_empty(): raise FixedStack.EmptyError self.ptr -= 1 return self.stk[self.ptr]
Python
nomic_cornstack_python_v1
function query self begin set uri = call genuri string gateway-service set queryobject = call GatewayServiceQuery connection uri return queryobject end function
def query(self): uri = common.genuri('gateway-service') queryobject = nvpquery.GatewayServiceQuery(self.connection, uri) return queryobject
Python
nomic_cornstack_python_v1
function test_allowed_filings_blocker_filing_incomplete monkeypatch app session jwt test_name state legal_types username roles filing_statuses expected begin set token = call helper_create_jwt jwt roles=roles username=username set headers = dict string Authorization string Bearer + token comment pylint: disable=unused-...
def test_allowed_filings_blocker_filing_incomplete(monkeypatch, app, session, jwt, test_name, state, legal_types, username, roles, filing_statuses, expected): token = helper_create_jwt(jwt, roles=roles, username=username) headers = {'Authorization': 'Bearer ' +...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Jul 8 12:40:05 2018 @author: Milton comment %% import pandas as pd import numpy as np set frames = list comment Cargo los excels en una nueva matriz comment Dentro de Range hay que poner el número de matrices que tengo, 17 para chile, 1 para Colombia for i in range 2...
# -*- coding: utf-8 -*- """ Created on Sun Jul 8 12:40:05 2018 @author: Milton """ #%% import pandas as pd import numpy as np frames = [] #Cargo los excels en una nueva matriz for i in range(2): #Dentro de Range hay que poner el número de matrices que tengo, 17 para chile, 1 para Colombia df = pd.re...
Python
zaydzuhri_stack_edu_python
function parseProgress self line begin if not progress begin return none end set prog = call _parseLine progress line if not prog begin return none end set prog_val = 0.0 if prog at - 1 == string % begin try begin set prog_val = call literal_eval prog at slice : - 1 : end except tuple ValueError SyntaxError begin pass...
def parseProgress(self, line): if not self.progress: return None prog = self._parseLine(self.progress, line) if not prog: return None prog_val = 0.0 if prog[-1] == '%': try: prog_val = literal_eval(prog[:-1]) exc...
Python
nomic_cornstack_python_v1
string Created on Nov 4, 2016 @author: Stefan class Student begin function __init__ self stud_id name group begin string Constructor set __stud_id = stud_id set __name = name set __group = group end function decorator property function stud_id self begin return __stud_id end function decorator setter function stud_id s...
''' Created on Nov 4, 2016 @author: Stefan ''' class Student: def __init__(self, stud_id, name, group): ''' Constructor ''' self.__stud_id = stud_id self.__name = name self.__group = group @property def stud_id(self): return sel...
Python
zaydzuhri_stack_edu_python
function _get_metrics_computers self begin if is_classification_model begin return call ModuleList list call Accuracy05 call AccuracyAtOptimalThreshold call OptimalThreshold call FalsePositiveRateOptimalThreshold call FalseNegativeRateOptimalThreshold call AreaUnderRocCurve call AreaUnderPrecisionRecallCurve call Binar...
def _get_metrics_computers(self) -> ModuleList: if self.is_classification_model: return ModuleList([Accuracy05(), AccuracyAtOptimalThreshold(), OptimalThreshold(), FalsePositiveRateOptimalThreshold(), ...
Python
nomic_cornstack_python_v1
class Character begin comment Create a character function __init__ self char_name char_description begin set name = char_name set description = char_description set conversation = none set direction = none end function comment Describe this character function describe self begin print name + string is here! print descr...
class Character(): # Create a character def __init__(self, char_name, char_description): self.name = char_name self.description = char_description self.conversation = None self.direction = None # Describe this character def describe(self): print( self.name + " is...
Python
zaydzuhri_stack_edu_python
function __build_snmpv3_user self target begin comment default object is blank set user = dict if string user in target begin set user = target at string user end comment get username set name = get user string username string comment get the authentication key set auth_key = none if string auth_key in user begin set ...
def __build_snmpv3_user(self, target): # default object is blank user = {} if "user" in target: user = target["user"] # get username name = user.get("username", "") # get the authentication key auth_key = None if "auth_key" in user: ...
Python
nomic_cornstack_python_v1
comment !/home/maharshmellow/anaconda3/bin/python3.5 comment -*- coding: UTF-8 -*- import cgitb import cgi import os from formatWord import formatWord import pickle from subprocess import Popen , PIPE , DEVNULL call enable print string Content-Type: text/html;charset=utf-8 print comment sets the max length of the post ...
#!/home/maharshmellow/anaconda3/bin/python3.5 # -*- coding: UTF-8 -*- import cgitb import cgi import os from formatWord import formatWord import pickle from subprocess import Popen, PIPE, DEVNULL cgitb.enable() print("Content-Type: text/html;charset=utf-8") print() # sets the max length of the post request (in bytes...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment Date: 2021/7/1 10:40 from typing import List comment 执行用时:44 ms, 在所有 Python3 提交中击败了67.23%的用户 comment 内存消耗:14.8 MB, 在所有 Python3 提交中击败了88.24%的用户 class Solution begin function numWays self n relation k begin set f = list comprehension list comprehension 0 for _ in range n for _ in range k + 1 ...
# coding=utf-8 # Date: 2021/7/1 10:40 from typing import List # 执行用时:44 ms, 在所有 Python3 提交中击败了67.23%的用户 # 内存消耗:14.8 MB, 在所有 Python3 提交中击败了88.24%的用户 class Solution: def numWays(self, n: int, relation: List[List[int]], k: int) -> int: f = [[0 for _ in range(n)] for _ in range(k + 1)] f[0][0] = 1 ...
Python
zaydzuhri_stack_edu_python
function remove_value_from_vocab self vocab begin set value = json at string value set v = find Setting name=vocab if not v begin return tuple string 404 end try begin call remove_value_from_vocab value end except RuntimeException as exception begin return tuple exception 400 end return call get_vocab end function
def remove_value_from_vocab(self, vocab): value = request.json['value'] v = Setting.find(name=vocab) if not v: return '', 404 try: v.remove_value_from_vocab(value) except RuntimeException as exception: return exception, 400 return v.get...
Python
nomic_cornstack_python_v1
function lock self value=true begin set lock_ = value return self end function
def lock(self, value=True): self.lock_ = value return self
Python
nomic_cornstack_python_v1
import random set list_elements = list 1 2 3 4 5 6 7 shuffle random list_elements print list_elements
import random list_elements = [1,2,3,4,5,6,7] random.shuffle(list_elements) print (list_elements)
Python
flytech_python_25k
string This is a trivial example of a gitrepo-based profile; The profile source code and other software, documentation, etc. are stored in in a publicly accessible GIT repository (say, github.com). When you instantiate this profile, the repository is cloned to all of the nodes in your experiment, to `/local/repository`...
"""This is a trivial example of a gitrepo-based profile; The profile source code and other software, documentation, etc. are stored in in a publicly accessible GIT repository (say, github.com). When you instantiate this profile, the repository is cloned to all of the nodes in your experiment, to `/local/repository`. ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np set seed = 77 call set_random_seed seed set x_data = array list list 1 2 1 1 list 2 1 3 2 list 3 1 3 4 list 4 1 5 5 list 1 7 5 5 list 1 2 5 6 list 1 6 6 6 list 1 7 6 7 dtype=float32 set y_data = array list list 0 0 1 list 0 0 1 list 0 0 1 list 0 1 0 list 0 1 0 list 0 1 0 list ...
import tensorflow as tf import numpy as np seed = 77 tf.set_random_seed(seed) x_data = np.array([[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2, 5, 6], [1, 6, 6, 6], [1, 7, 6, 7]], dtype=np.float32) y_data = np.array(...
Python
zaydzuhri_stack_edu_python
function _get_sid_counter self begin return __sid_counter end function
def _get_sid_counter(self): return self.__sid_counter
Python
nomic_cornstack_python_v1
function count_unique_words string begin comment Remove punctuation marks from the string set string = replace replace replace replace string string , string string . string string ? string string ! string comment Split the string into words set words = split string comment Create a set to store unique words set unique...
def count_unique_words(string): # Remove punctuation marks from the string string = string.replace(",", "").replace(".", "").replace("?", "").replace("!", "") # Split the string into words words = string.split() # Create a set to store unique words unique_words = set() # Iterate over the ...
Python
greatdarklord_python_dataset
function _state_to_scale self original_state orig_ind remove_mean=false begin if scaling is not none begin return call trf_mean_and_std original_state scaling at orig_ind remove=remove_mean end return original_state end function
def _state_to_scale(self, original_state: Arr, orig_ind: int, remove_mean: bool = False) -> Arr: if self.scaling is not None: return trf_mean_and_std(original_state, self.scaling[orig_ind], remove=remove_mean) return original_state
Python
nomic_cornstack_python_v1
comment Question 4 set height_prompt = string So, you want to ride the roller coaster? How tall are you ...? set height = integer input height_prompt set can_ride = height >= 120 if can_ride begin print string Hop on! end else begin print string Sorry, not today :( end
# Question 4 height_prompt = f"So, you want to ride the roller coaster? How tall are you ...? " height = int(input(height_prompt)) can_ride = height>=120 if can_ride: print("Hop on!") else: print("Sorry, not today :(")
Python
zaydzuhri_stack_edu_python
function get_desctiptive_name self begin set long_name = string year + string + make + string + model return title long_name end function
def get_desctiptive_name(self): long_name = str(self.year) + ' ' + self.make + ' '+self.model return long_name.title()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string @author: guardati Problema 4.7 Calcula e imprime el resultado de la serie: 1**1 + 2**2 + 3**3 + … + n**n set n = integer input string Ingrese el valor de n: set serie = 0 for i in range 1 n + 1 begin set serie = serie + i ^ i end print string El resultado de la serie es: { serie }
# -*- coding: utf-8 -*- """ @author: guardati Problema 4.7 Calcula e imprime el resultado de la serie: 1**1 + 2**2 + 3**3 + … + n**n """ n = int(input('Ingrese el valor de n: ')) serie = 0 for i in range(1, n + 1): serie += i ** i print(f'El resultado de la serie es: {serie}')
Python
zaydzuhri_stack_edu_python
function inet_aton addr begin set b = call inet_aton addr return call unpack string !I b at 0 end function
def inet_aton(addr): b = socket.inet_aton(addr) return struct.unpack('!I', b)[0]
Python
nomic_cornstack_python_v1
string data_tools module. Contains DataTools class for data-oriented tasks import os from datetime import datetime from typing import Tuple , Optional , Union import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from context import KglToolsContext , KglToolsContextChild set __all_...
""" data_tools module. Contains DataTools class for data-oriented tasks """ import os from datetime import datetime from typing import Tuple, Optional, Union import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from ..context import KglToolsContext, KglToolsContextChild __all_...
Python
zaydzuhri_stack_edu_python
function backprop node v begin set this_node = node while this_node is not none begin comment change stats set n = n + 1 set w = w + v set q = w / n comment change pointer set this_node = parent end end function
def backprop(node, v): this_node = node while this_node is not None: # change stats this_node.n += 1 this_node.w += v this_node.q = this_node.w / this_node.n # change pointer this_node = this_node.parent
Python
nomic_cornstack_python_v1