code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function __len__ self begin return integer ceil total_frame_count / batch_size end function
def __len__(self): return int(np.ceil(self.total_frame_count / self.batch_size))
Python
nomic_cornstack_python_v1
function assemble_tens num word units tens others_tens begin comment numbers less than 20 if num < 20 begin for tuple key value in items tens begin if num == key begin set word = word + value end end end else begin comment numbers greater than 19 comment tens set tens = num // 10 * 10 for tuple key value in items other...
def assemble_tens(num, word, units, tens, others_tens): # numbers less than 20 if num < 20: for key, value in tens.items(): if num == key: word += value # numbers greater than 19 else: # tens tens = (num // 10) * 10 for key, value in others_te...
Python
zaydzuhri_stack_edu_python
function get_default_app_config begin comment 1. Set function variables set file_location = string APP_DIR + string /application/static/app_config.yaml comment 2. Read the YAML file set yaml_dict = call read_yaml file_location comment 3. Return a dictionary of the contents return yaml_dict end function
def get_default_app_config(): # 1. Set function variables file_location = str(APP_DIR) + '/application/static/app_config.yaml' # 2. Read the YAML file yaml_dict = read_yaml(file_location) # 3. Return a dictionary of the contents return yaml_dict
Python
nomic_cornstack_python_v1
comment Link to the question: comment https://www.interviewbit.com/problems/3-sum-zero/ comment Similar logic as 3 Sum problem, but shitty edge cases. comment This doesn't run on Python 3 IB IDE for some reason comment but runs on Python 2 IB IDE. class Solution begin comment @param A : list of integers comment @return...
# Link to the question: # https://www.interviewbit.com/problems/3-sum-zero/ # Similar logic as 3 Sum problem, but shitty edge cases. # This doesn't run on Python 3 IB IDE for some reason # but runs on Python 2 IB IDE. class Solution: # @param A : list of integers # @return a list of list of integers def th...
Python
zaydzuhri_stack_edu_python
import urllib2 import re import datetime from bs4 import BeautifulSoup from collections import namedtuple class StockData extends object begin set HEADER = string Ticker,Price ($),Drug,Indication,Phase,Date(YMD),Catalyst,Mean Recommendation,Strong Buy,Buy,Recommendation Count,Target Min($),Target Mean($),Target High($)...
import urllib2 import re import datetime from bs4 import BeautifulSoup from collections import namedtuple class StockData(object): HEADER = "Ticker,Price ($),Drug,Indication,Phase,Date(YMD),Catalyst,Mean Recommendation,Strong Buy,Buy,Recommendation Count,Target Min($),Target Mean($),Target High($),Growth(%),Marke...
Python
zaydzuhri_stack_edu_python
function filterDataframeBySenSpeLimit value_sen value_spe dataframe_values_models begin set datafram_values_filtered = query dataframe_values_models format string Sensitivity >= {0} and Specificity >= {1} value_sen value_spe return datafram_values_filtered end function
def filterDataframeBySenSpeLimit(value_sen, value_spe, dataframe_values_models): datafram_values_filtered = dataframe_values_models.query('Sensitivity >= {0} and Specificity >= {1}'.format(value_sen, value_spe)) return datafram_values_filtered
Python
nomic_cornstack_python_v1
function find directory begin set path = join path directory DEFAULT_FILE if exists path path begin return path end else begin return none end end function
def find(directory): path = os.path.join(directory, DEFAULT_FILE) if os.path.exists(path): return path else: return None
Python
nomic_cornstack_python_v1
if sl > 1250 begin print format string O seu novo salário é de R$ {:.2f} com um reajuste de 10% sl * 1.1 end else begin print format string O seu novo salário é de R$ {:.2f} com um reajuste de 15% sl * 1.15 end
if sl >1250: print('O seu novo salário é de R$ {:.2f} com um reajuste de 10%'.format(sl*1.1)) else: print('O seu novo salário é de R$ {:.2f} com um reajuste de 15%'.format(sl * 1.15))
Python
zaydzuhri_stack_edu_python
function _validPlayerBalance self playerBalance quotedName begin if quotedName begin return match string ^(.+)[\s]+[0-9.]+$ playerBalance end else begin return match string ^(.*[a-zA-Z]{1}.*)[\s]+[0-9.]+$ playerBalance end end function
def _validPlayerBalance(self, playerBalance,quotedName): if quotedName: return re.match(r"^(.+)[\s]+[0-9.]+$",playerBalance) else: return re.match(r"^(.*[a-zA-Z]{1}.*)[\s]+[0-9.]+$",playerBalance)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2 comment -*- coding: utf-8 -*- comment mongo_data comment use mongodb pyalgotrade and un800 comment vim:fileencoding=utf-8:sw=4:et -*- coding: utf-8 -*- comment alpaca trade stock comment 该指标是有Richard Donchian发明的,是有3条不同颜色的曲线组成的, comment 该指标用周期(一般都是20)内的最高价和最低价来显示市场价格的波动性, comment 当其通道窄时表示市场波动较小...
#!/usr/bin/python2 # -*- coding: utf-8 -*- # mongo_data # # use mongodb pyalgotrade and un800 # # vim:fileencoding=utf-8:sw=4:et -*- coding: utf-8 -*- # # alpaca trade stock # 该指标是有Richard Donchian发明的,是有3条不同颜色的曲线组成的, # 该指标用周期(一般都是20)内的最高价和最低价来显示市场价格的波动性, # 当其通道窄时表示市场波动较小,反之通道宽则表示市场波动比较大 #该具体分析为: # 当价格冲冲破...
Python
zaydzuhri_stack_edu_python
import math set AB = input string Длина первого катета: set AC = input string Длина второго катета: set AB = decimal AB set AC = decimal AC set BC = square root AB ^ 2 + AC ^ 2 set S = AB * AC / 2 print string Гипотенуза: BC print string Площадь S
import math AB = input("Длина первого катета: ") AC = input("Длина второго катета: ") AB = float(AB) AC = float(AC) BC = math.sqrt(AB ** 2 + AC ** 2) S = (AB * AC) / 2 print('Гипотенуза:', BC) print('Площадь', S)
Python
zaydzuhri_stack_edu_python
comment in built class in python for unit testing import unittest from calc import Calc comment inherits from unittest class CalcTest extends TestCase begin function setUp self begin set c = call Calc end function function testAdd self begin comment fn to test add fn comment test adding 2 pos numbers assert equal 3 add...
import unittest #in built class in python for unit testing from calc import Calc class CalcTest(unittest.TestCase): #inherits from unittest def setUp(self): self.c = Calc() def testAdd(self): #fn to test add fn self.assertEqual(3, self.c.add(1,2)) #test adding ...
Python
zaydzuhri_stack_edu_python
function get_function_of_card card_name begin set card_dict = call get_card_dict card_name set function = card_dict at string function return if expression function then string function else function end function
def get_function_of_card(card_name): card_dict = get_card_dict(card_name) function = card_dict['function'] return str(function) if function else function
Python
nomic_cornstack_python_v1
import numpy as np from numpy import exp from scipy.optimize import curve_fit import matplotlib.pyplot as plt from uncertainties import ufloat from scipy.stats import sem from math import e import scipy.integrate as integrate set tuple l1 x1 y1 t1 = call genfromtxt string Werte2.txt unpack=true set tuple l2 x2 y2 t2 = ...
import numpy as np from numpy import exp from scipy.optimize import curve_fit import matplotlib.pyplot as plt from uncertainties import ufloat from scipy.stats import sem from math import e import scipy.integrate as integrate l1, x1, y1, t1= np.genfromtxt('Werte2.txt', unpack=True) l2, x2, y2 ,t2= np.genfromtxt('Werte...
Python
zaydzuhri_stack_edu_python
function crc data begin set c = 4294967295 for b in data begin set c = c ? 8 ? CRC_32_TABLE at c ? b ? 255 end return c ? 4294967295 end function
def crc(data): c = 0xFFFFFFFF for b in data: c = (c >> 8) ^ CRC_32_TABLE[(c ^ b) & 255] return c ^ 0xFFFFFFFF
Python
nomic_cornstack_python_v1
function structuredPath resource begin set rn : str = rn comment if CSE if ty == CSEBase begin return rn end comment retrieve identifier record of the parent if pi := pi is none or length pi == 0 begin comment Logging.logErr('PI is None') return rn end set rpi = call identifier pi if length rpi == 1 begin return call c...
def structuredPath(resource:Resource) -> str: rn:str = resource.rn if resource.ty == T.CSEBase: # if CSE return rn # retrieve identifier record of the parent if (pi := resource.pi) is None or len(pi) == 0: # Logging.logErr('PI is None') return rn rpi = CSE.storage.identifier(pi) if len(rpi) == 1: return...
Python
nomic_cornstack_python_v1
function cost_filter_press blk begin set t0 = first time comment Add cost variable and constraint set capital_cost = variance pyo initialize=1 units=base_currency bounds=tuple 0 none doc=string Capital cost of unit operation set Q = call convert flow_vol to_units=gal / hr comment Get parameter dict from database set pa...
def cost_filter_press(blk): t0 = blk.flowsheet().time.first() # Add cost variable and constraint blk.capital_cost = pyo.Var( initialize=1, units=blk.config.flowsheet_costing_block.base_currency, bounds=(0, None), doc="Capital cost of unit operation...
Python
nomic_cornstack_python_v1
set S = input set S_len = length S print string x * S_len
S = input() S_len = len(S) print("x" * S_len)
Python
zaydzuhri_stack_edu_python
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
function microsalt_case_qc_pass begin return string microsalt_case_qc_pass end function
def microsalt_case_qc_pass() -> str: return "microsalt_case_qc_pass"
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import re comment tell and seek function Read_file file begin set fh = open file string r for line in read lines fh begin set line = strip line if match string ^\s*$ line begin continue end comment print (line) set aa = search string (\d+\.\d+\.\d+\.\d+) line if aa begin print call group end s...
#!/usr/bin/python3 import re ## tell and seek def Read_file(file): fh = open(file,"r") for line in fh.readlines(): line = line.strip() if re.match(r'^\s*$',line): continue #print (line) aa = re.search(r'(\d+\.\d+\.\d+\.\d+)',line) if a...
Python
zaydzuhri_stack_edu_python
function hi name=string Leng Ting begin return string Hello, + name end function print call hi set greet = hi del hi comment print(hi()) print call greet
def hi(name="Leng Ting"): return('Hello, ' + name) print(hi()) greet = hi del hi #print(hi()) print(greet())
Python
zaydzuhri_stack_edu_python
function determine_sign number begin if number < 0 begin return string Negative end else if number > 0 begin return string Positive end else begin return string Zero end end function set number = decimal input string Enter a number: set sign = call determine_sign number print sign
def determine_sign(number): if number < 0: return "Negative" elif number > 0: return "Positive" else: return "Zero" number = float(input("Enter a number: ")) sign = determine_sign(number) print(sign)
Python
jtatman_500k
function has_inf x begin set helper = call LayerHelper string isinf keyword locals set out = call create_variable_for_type_inference dtype=dtype call append_op type=string isinf inputs=dict string X x outputs=dict string Out out return out end function
def has_inf(x): helper = LayerHelper("isinf", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type="isinf", inputs={"X": x}, outputs={"Out": out}) return out
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon Sep 10 20:54:44 2018 @author: Tanasha import pandas as pd import random import numpy as np set possibilitiesArray = dict string Race list 3 ; string Gender list 2 ; string GenderIdentity list 3 ; string Personality list 16 ; string Sexuality list 4 ; string RightArm l...
# -*- coding: utf-8 -*- """ Created on Mon Sep 10 20:54:44 2018 @author: Tanasha """ import pandas as pd import random import numpy as np possibilitiesArray = {'Race':[3], 'Gender': [2], 'GenderIdentity': [3], 'Personality':[16], 'Sexuality':[4], 'RightArm': [5], 'LeftArm': [5], 'RightLeg': [5], 'LeftLeg': [5], 'Head'...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python class parent begin set parentattr = 10 end class
#!/usr/bin/python class parent: parentattr=10
Python
zaydzuhri_stack_edu_python
comment check permutation 1.2 comment given two strings write a method to decide if one is a permutation of the other function sort string begin set content = list string sort content set results = join string content return results end function function permutations one two begin if length one != length two begin ret...
# check permutation 1.2 # given two strings write a method to decide if one is a permutation of the other def sort(string): content = list(string) content.sort() results = ''.join(content) return results def permutations(one, two): if len(one) != len(two): return False else: r...
Python
zaydzuhri_stack_edu_python
function build_profile first last **user_info begin string Build a dictionary containing everything we know about a user. set profile = dict set profile at string first name = first set profile at string last name = last for tuple key value in items user_info begin set profile at key = value end return profile end fun...
def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile['first name'] = first profile['last name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build...
Python
zaydzuhri_stack_edu_python
import hashlib function proof_of_work transaction begin comment 0부터 시작 set nonce = 0 comment 난이도 set difficulty = 4 while true begin set input_data = encode string transaction + string nonce set computed_hash = hex digest sha256 input_data if computed_hash at slice : difficulty : == string 0 * difficulty begin break ...
import hashlib def proof_of_work(transaction): nonce = 0 # 0부터 시작 difficulty = 4 # 난이도 while True: input_data = (str(transaction) + str(nonce)).encode() computed_hash = hashlib.sha256(input_data).hexdigest() if computed_hash[:difficulty] == "0" * difficulty: break ...
Python
zaydzuhri_stack_edu_python
import random comment Welcome message print string Welcome to the Toss Coin App! print string I'll toss a coin the number of times you want! comment Get number of flips set times = integer input string How many times should I flip the coin? comment Ask the user if we should display all results set answer = lower input ...
import random # Welcome message print("Welcome to the Toss Coin App!") print("\nI'll toss a coin the number of times you want!") # Get number of flips times = int(input("How many times should I flip the coin? ")) # Ask the user if we should display all results answer = input("Would you like to see each flip? (y/n) ...
Python
zaydzuhri_stack_edu_python
string Test getting a segmentation from the SV Data Manager. This is tested using the Demo Project. import sv comment Create a Python segmentation group object from the SV Data Manager 'Segmentations/aorta' node. set seg_name = string aorta set segmentation_group = call get_segmentation seg_name set num_segs = call num...
''' Test getting a segmentation from the SV Data Manager. This is tested using the Demo Project. ''' import sv ## Create a Python segmentation group object from the SV Data Manager 'Segmentations/aorta' node. # seg_name = "aorta" segmentation_group = sv.dmg.get_segmentation(seg_name) num_segs = segmentation_group...
Python
zaydzuhri_stack_edu_python
function open self call_site_level=1 begin if is_open begin if open_site begin raise call LifecycleError format string {0}({1}) is already open {2} __name__ call id self call format_trace string end end if not allow_reuse and is_used begin raise call LifecycleError format string {0}({1}) cannot be reused {2} __name__ c...
def open(self, call_site_level=1): if self.is_open: if self.open_site: raise self.LifecycleError("{0}({1}) is already open\n{2}".format( self.__class__.__name__, id(self), self.format_trace(" "))) if not self.ScopedOptions.allow_reuse and self.is_used: ...
Python
nomic_cornstack_python_v1
function test_vcdone_in_CS_with_valid_view_no_from_get_msgs_for_lagged_nodes node_with_nodestack begin set fake_view_changer = view_changer set get_msgs_for_lagged_nodes = partial get_msgs_for_lagged_nodes fake_view_changer set _accepted_view_change_done_message = tuple string someNode ledger_summary set vch_messages =...
def test_vcdone_in_CS_with_valid_view_no_from_get_msgs_for_lagged_nodes(node_with_nodestack): fake_view_changer = node_with_nodestack.view_changer fake_view_changer.get_msgs_for_lagged_nodes = functools.partial(ViewChanger.get_msgs_for_lagged_nodes, ...
Python
nomic_cornstack_python_v1
function get_song_url self song_id begin set values = dict string action string song ; string filter song_id set root = call __call_api values if not root begin return none end set song = call getElementsByTagName string song at 0 set song_url = data return song_url end function
def get_song_url(self, song_id): values = { 'action' : 'song', 'filter' : song_id, } root = self.__call_api(values) if not root: return None song = root.getElementsByTagName('song')[0] song_url = song.getElementsByTagName('url')[0]....
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import messagebox import Punto class Aplicacion begin function __init__ self ventanaPrincipal begin comment Creacion de la ventana principal set ventana = ventanaPrincipal comment Titulo de la ventana title ventana string Draw_A comment Tamano de la ventana 1366x768 pixeles call geome...
from tkinter import * from tkinter import messagebox import Punto class Aplicacion: def __init__(self, ventanaPrincipal): self.ventana = ventanaPrincipal # Creacion de la ventana principal self.ventana.title("Draw_A") # Titulo de la ventana self.ventana.geometry("1366x768") # Ta...
Python
zaydzuhri_stack_edu_python
function gt_roidb self begin comment Caching disabled for experimentation comment cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') comment if os.path.exists(cache_file): comment with open(cache_file, 'rb') as fid: comment roidb = cPickle.load(fid) comment print '{} gt roidb loaded from {}'.format...
def gt_roidb(self): # Caching disabled for experimentation # cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') # if os.path.exists(cache_file): # with open(cache_file, 'rb') as fid: # roidb = cPickle.load(fid) # print '{} gt roidb loa...
Python
nomic_cornstack_python_v1
from pandas.core.dtypes.common import is_numeric_dtype , is_string_dtype from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder , StandardScaler from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer class ProcessData extends object beg...
from pandas.core.dtypes.common import is_numeric_dtype, is_string_dtype from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer class ProcessData(object): ...
Python
zaydzuhri_stack_edu_python
function retrieve_all_hosts database_connection begin set cursor = call cursor dictionary=true set query = string SELECT h.hostid, h.host, h.hostslug FROM ww_hosts h WHERE h.host <> '(TBD)' ORDER BY h.hostslug ASC; execute cursor query set result = call fetchall close cursor if not result begin return none end set host...
def retrieve_all_hosts(database_connection: mysql.connector.connect ) -> List[Dict]: cursor = database_connection.cursor(dictionary=True) query = ("SELECT h.hostid, h.host, h.hostslug " "FROM ww_hosts h " "WHERE h.host <> '(TBD)' " "ORDER BY h.hostsl...
Python
nomic_cornstack_python_v1
for i in range t begin set n = integer input set x = 1 + 8 * n set y = integer x ^ 0.5 end
for i in range(t): n=int(input()) x=1+8*n y=int(x**0.5)
Python
zaydzuhri_stack_edu_python
from django.contrib.auth.models import BaseUserManager class UserManager extends BaseUserManager begin function create_user self email first_name last_name password is_student is_employer profile_picture=none begin if not email begin raise call ValueError string User must have an email end if not password begin raise c...
from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, is_student, is_employer, profile_picture=None): if not email: raise ValueError("User must have an email") if not...
Python
zaydzuhri_stack_edu_python
function watch_secret_list_with_http_info self **kwargs begin set all_params = list string pretty string label_selector string field_selector string watch string resource_version string timeout_seconds append all_params string callback append all_params string _return_http_data_only set params = locals for tuple key va...
def watch_secret_list_with_http_info(self, **kwargs): all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritem...
Python
nomic_cornstack_python_v1
function formatColorfa a begin return string #%02x%02x%02x % tuple integer round a at 0 * 255 integer round a at 1 * 255 integer round a at 2 * 255 end function
def formatColorfa(a): return '#%02x%02x%02x' % (int(round(a[0]*255)),int(round(a[1]*255)),int(round(a[2]*255)))
Python
nomic_cornstack_python_v1
function customer_updated begin set revel_url = call instance_url req=request set payload = json set revel_id = payload at string id set created_date = call format_date payload at string created_date set updated_date = call format_date payload at string updated_date set obj = call RevelResource revel_id=revel_id create...
def customer_updated(): revel_url = instance_url(req=request) payload = request.json revel_id = payload['id'] created_date = format_date(payload['created_date']) updated_date = format_date(payload['updated_date']) obj = RevelResource(revel_id=revel_id, created_date=cre...
Python
nomic_cornstack_python_v1
function number_of_donations self begin return length donations end function
def number_of_donations(self): return len(self.donations)
Python
nomic_cornstack_python_v1
comment Compute frequency array of k-mers in a text set __author__ = string Abdelrahman Hosny <abdelrahman.hosny@ieee.org> function symboltonumber symbol begin if symbol == string A begin return 0 end else if symbol == string C begin return 1 end else if symbol == string G begin return 2 end else if symbol == string T ...
# Compute frequency array of k-mers in a text __author__ = 'Abdelrahman Hosny <abdelrahman.hosny@ieee.org>' def symboltonumber(symbol): if symbol == 'A': return 0 elif symbol == 'C': return 1 elif symbol == 'G': return 2 elif symbol == 'T': return 3 def patterntonumbe...
Python
zaydzuhri_stack_edu_python
function row Y row s=none ax=false line=string - marker=string o color=string k linewidth=2 markersize=8 xlabel=none ylabel=none title=none xlim=false ylim=false yaxis=string lin xaxis=string mp legend=false marksep=true begin string Plots the specified parameter Y along the outer target Returns: Figure object if ax=Fa...
def row(Y,row,s=None,ax=False,line='-',marker='o',color='k',linewidth=2,markersize=8,xlabel=None,ylabel=None,title=None,xlim=False,ylim=False,yaxis="lin",xaxis="mp",legend=False,marksep=True): """ Plots the specified parameter Y along the outer target Returns: Figure object if ax=False [default], Void otherwi...
Python
nomic_cornstack_python_v1
function _derive_transformation_matrices self begin if has attribute self string _primaries and has attribute self string _whitepoint begin if _primaries is not none and _whitepoint is not none begin set npm = call normalised_primary_matrix _primaries _whitepoint set _derived_RGB_to_XYZ_matrix = npm set _derived_XYZ_to...
def _derive_transformation_matrices(self): if hasattr(self, '_primaries') and hasattr(self, '_whitepoint'): if self._primaries is not None and self._whitepoint is not None: npm = normalised_primary_matrix(self._primaries, self._whitepo...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import pandas as pd import sys function isResidentCenter target begin set firstChar = call slice 0 1 return is digit str end function function isExtractTarget target begin set isHealth = call slice 0 2 == string 보건 set isWelfareCenter = call slice 0 3 == string 지자체 set isLibrary = str == s...
#!/usr/bin/env python3 import pandas as pd import sys def isResidentCenter(target): firstChar = target.str.slice(0, 1) return firstChar.str.isdigit() def isExtractTarget(target): isHealth = (target.str.slice(0, 2) == '보건') isWelfareCenter = (target.str.slice(0, 3) == '지자체') isLibrary = (target.str...
Python
zaydzuhri_stack_edu_python
comment -*- coding=utf-8 -*- string "A very simple MNIST classifier. See extensive documentation at http://tensorflow.org/tutorials/mnist/beginners/index.md from __future__ import absolute_import from __future__ import division from __future__ import print_function comment Import data from tensorflow.examples.tutorials...
# -*- coding=utf-8 -*- """"A very simple MNIST classifier. See extensive documentation at http://tensorflow.org/tutorials/mnist/beginners/index.md """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Import data from tensorflow.examples.tutorials.mnist imp...
Python
zaydzuhri_stack_edu_python
import socket import threading import time import errno set __all__ = list string EventGenerator class EventGeneratingThread extends Thread begin set daemon = true function __init__ self event_generator begin call __init__ self set event_generator = event_generator end function function run self begin while true begin ...
import socket import threading import time import errno __all__ = ["EventGenerator"] class EventGeneratingThread(threading.Thread): daemon = True def __init__(self, event_generator): threading.Thread.__init__(self) self.event_generator = event_generator def run(self): while True:...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set drive_motors = call MotorPair string B string D set left_motor = call Motor string B set right_motor = call Motor string D set left_color = call ColorSensor string A set right_color = call ColorSensor string F set left_attachment = call Motor string C set right_attachment = call Motor s...
def __init__(self): self.drive_motors = MotorPair('B', 'D') self.left_motor = Motor("B") self.right_motor = Motor("D") self.left_color = ColorSensor('A') self.right_color = ColorSensor('F') self.left_attachment = Motor('C') self.right_attachment = Motor('E') ...
Python
nomic_cornstack_python_v1
function main begin import argparse set parser = call ArgumentParser call add_argument string -i string --input help=string Input .py file nargs=string + set args = call parse_args set mod_func = list for pyfile in input begin set tree = parse ast read open pyfile set methods = sorted set comprehension name for node i...
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help='Input .py file', nargs='+') args = parser.parse_args() mod_func = [] for pyfile in args.input: tree = ast.parse(open(pyfile).read()) methods = sorted({node.name for node i...
Python
nomic_cornstack_python_v1
function dist targets lo hi nbucket begin set distribution = list for _ in range nbucket begin append distribution list end for i in range lo hi begin if 0 <= i and i < length targets begin append distribution at i % nbucket targets at i end end return distribution end function
def dist(targets, lo, hi, nbucket): distribution = [] for _ in range(nbucket): distribution.append([]) for i in range(lo, hi): if 0 <= i and i < len(targets): distribution[i % nbucket].append(targets[i]) return distribution
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string @author: Thando Peter 1908664@students.wits.ac.za @author: Tieho Ramphore 1908649@students.wits.ac.za @author: Olebogeng Maleho 1862666@students.wits.ac.za string Information of the structure of the data (All this information can be found in the poker-hand.name file): Attribute Info...
# -*- coding: utf-8 -*- """ @author: Thando Peter 1908664@students.wits.ac.za @author: Tieho Ramphore 1908649@students.wits.ac.za @author: Olebogeng Maleho 1862666@students.wits.ac.za """ """ Information of the structure of the data (All this information can be found in the poker-hand.name file): Attribute Inform...
Python
zaydzuhri_stack_edu_python
from turtle import * call shape string triangle call color string blue call speed - 1 call fillcolor string yellow call begin_fill call circle 50 call end_fill call mainloop
from turtle import * shape('triangle') color('blue') speed(-1) fillcolor('yellow') begin_fill() circle(50) end_fill() mainloop()
Python
zaydzuhri_stack_edu_python
function add a b begin return a + b end function function introduce begin print string Hello, I'm Partrick! print string I'm BATMAN!! end function function joke begin print string Dani end function function shout begin print string Asgar! end function
def add(a, b): return a + b def introduce(): print("Hello, I'm Partrick!") print("I'm BATMAN!!") def joke(): print("Dani") def shout(): print("Asgar!")
Python
zaydzuhri_stack_edu_python
function get_streets_flat self begin return edges end function
def get_streets_flat(self): return self.edges
Python
nomic_cornstack_python_v1
function get_oldest_filename self begin string Get the original filename of this content. Implies follow set commit_and_name_iter = call get_commits_and_names_iter source_path set tuple _commit name = next commit_and_name_iter return name end function
def get_oldest_filename(self): ''' Get the original filename of this content. Implies follow ''' commit_and_name_iter = self.git.get_commits_and_names_iter( self.content.source_path) _commit, name = next(commit_and_name_iter) return name
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Dec 23 21:53:42 2019 @author: henry-mac import math function truncate number digits begin set stepper = 10.0 ^ digits return call trunc stepper * number / stepper end function set test_player1 = list string Charles Oakley string 50 string...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 23 21:53:42 2019 @author: henry-mac """ import math def truncate(number, digits) -> float: stepper = 10.0 ** digits return math.trunc(stepper * number) / stepper test_player1 = ['Charles Oakley', '50', '3.8', '2.2', '33.8', '34.6', '86.2', ...
Python
zaydzuhri_stack_edu_python
string given a binary tree, calculate the total node depths comment recursive approach comment time: O(n) | space: O(h) - call stack of the recursive will be the almost the height of the tree comment the recursive approach has to go thorough all the branches function calculateNodeDepth root depth=0 begin if root is non...
''' given a binary tree, calculate the total node depths ''' # recursive approach # time: O(n) | space: O(h) - call stack of the recursive will be the almost the height of the tree # the recursive approach has to go thorough all the branches def calculateNodeDepth(root, depth = 0): if root is None: retu...
Python
zaydzuhri_stack_edu_python
function fibonacci n begin set memo = dict function fibMemo n memo begin if n in memo begin return memo at n end if n <= 2 begin return 1 end set memo at n = call fibMemo n - 1 memo + call fibMemo n - 2 memo return memo at n end function if n < 0 begin if n % 2 == 0 begin return - call fibMemo absolute n memo end else...
def fibonacci(n): memo = {} def fibMemo(n, memo): if n in memo: return memo[n] if n <= 2: return 1 memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo) return memo[n] if n < 0: if n % 2 == 0: return -fibMemo(abs(n), memo) ...
Python
jtatman_500k
function __init__ __self__ apt=none goo=none mig_instances_allowed=none post_step=none pre_step=none reboot_config=none windows_update=none yum=none zypper=none begin if apt is not none begin set __self__ string apt apt end if goo is not none begin set __self__ string goo goo end if mig_instances_allowed is not none be...
def __init__(__self__, *, apt: Optional[pulumi.Input['AptSettingsArgs']] = None, goo: Optional[pulumi.Input['GooSettingsArgs']] = None, mig_instances_allowed: Optional[pulumi.Input[bool]] = None, post_step: Optional[pulumi.Input['ExecStepArgs']] = None...
Python
nomic_cornstack_python_v1
function end_encounter self begin comment Add the encounter responses received by enemy (i.e. said by player) to global history set _response_history = _response_history + encounter_responses set current_enemy = none comment self.in_encounter = False comment Empty encounter response cache set encounter_responses = list...
def end_encounter(self): # Add the encounter responses received by enemy (i.e. said by player) to global history self._response_history += self.current_enemy.encounter_responses self.current_enemy = None # self.in_encounter = False self.encounter_responses = [] # Empty encounte...
Python
nomic_cornstack_python_v1
comment Queue Class implementation based on a python list comment @Author Josh Wright class Queue begin comment constructor method comment @param self comment The queue being constructed comment @param args comment Arguments passed in to be added to the queue comment @requires args is a python list comment @ensures sel...
# Queue Class implementation based on a python list #@Author Josh Wright class Queue: #constructor method #@param self # The queue being constructed #@param args # Arguments passed in to be added to the queue #@requires args is a python list #@ensures self is an empty queue or a queue of...
Python
zaydzuhri_stack_edu_python
function validate uri deep=true begin comment function aliases to open URIs set join = urljoin set opener = lambda d -> url open join uri d comment the descriptor set datapackage = loads read call opener string datapackage.json comment validate the descriptor call validateMetadata datapackage SCHEMA comment validate ea...
def validate(uri, deep=True): # function aliases to open URIs join = urllib.parse.urljoin opener = lambda d: urllib.request.urlopen(join(uri,d)) # the descriptor datapackage = json.loads(opener("datapackage.json").read()) # validate the descriptor validateMetadata(datapackage,SCHEMA) ...
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn class DQNAgent extends Module begin function __init__ self name in_dim=128 h_dim=128 out_dim=16 lr=1e-05 gamma=0.99 begin call __init__ set name = name set in_dim = in_dim set h_dim = h_dim set out_dim = out_dim set lr = lr comment self.gamma = gamma set fc = sequential linear in_dim ...
import torch import torch.nn as nn ## class DQNAgent(nn.Module): def __init__(self, name, in_dim=128, h_dim=128, out_dim=16, lr=1e-5, gamma=0.99): super(DQNAgent, self).__init__() self.name = name self.in_dim = in_dim self.h_dim = h_dim self.out_dim = out_dim...
Python
zaydzuhri_stack_edu_python
comment abstract factory create objects that are used to assemble large objec, all comment these objects are of one "family" comment first concrete factory a define all create_xxx method, the others only define comment object they created, factory a, a <- b, a <- c class DiagramFactory begin function create_text self t...
# abstract factory create objects that are used to assemble large objec, all # these objects are of one "family" # first concrete factory a define all create_xxx method, the others only define # object they created, factory a, a <- b, a <- c class DiagramFactory: def create_text(self, text, fontsize=12): r...
Python
zaydzuhri_stack_edu_python
function _replace_property property_key property_value resource logical_id begin string Replace a property with an asset on a given resource This method will mutate the template Parameters ---------- property str The property to replace on the resource property_value str The new value of the property resource dict Dict...
def _replace_property(property_key, property_value, resource, logical_id): """ Replace a property with an asset on a given resource This method will mutate the template Parameters ---------- property str The property to replace on the resource proper...
Python
jtatman_500k
function solution clothes begin set answer = 1 set dicClothes = dict for c in clothes begin if c at 1 in keys dicClothes begin set dicClothes at c at 1 = dicClothes at c at 1 + 1 end else begin set dicClothes at c at 1 = 1 end end print values dicClothes for item in values dicClothes begin print item set answer = answ...
def solution(clothes): answer = 1 dicClothes = {} for c in clothes: if c[1] in dicClothes.keys(): dicClothes[c[1]] = dicClothes[c[1]] + 1 else : dicClothes[c[1]] = 1 print(dicClothes.values()) for item in dicClothes.values(): print(item) answer...
Python
zaydzuhri_stack_edu_python
from pyspark.sql import SparkSession from pyspark.sql.functions import isnull , when , count , col set dataset_names = list string cargo string contact string container string header set col_fullness_checks = dict string cargo list string identifier string container_number ; string contact list string identifier string...
from pyspark.sql import SparkSession from pyspark.sql.functions import isnull, when, count, col dataset_names = ['cargo', 'contact', 'container', 'header'] col_fullness_checks = { 'cargo': ['identifier', 'container_number'], 'contact': ['identifier', 'contact_type'], 'container': ['identifier', 'container_number'],...
Python
zaydzuhri_stack_edu_python
function create_aeroo_report self cr uid ids data report_xml context begin set context = copy context assert code in tuple string oo-odt string oo-ods string oo-doc string oo-xls string oo-csv string oo-pdf assert in_format in tuple string oo-odt string oo-ods set output_format = code at slice 3 : : set input_format ...
def create_aeroo_report( self, cr, uid, ids, data, report_xml, context): context = context.copy() assert report_xml.out_format.code in ( 'oo-odt', 'oo-ods', 'oo-doc', 'oo-xls', 'oo-csv', 'oo-pdf', ) assert report_xml.in_format in ('oo-odt', 'oo-ods') outp...
Python
nomic_cornstack_python_v1
function _load self is_implicit_include name *symbols **symbol_kwargs begin comment type: (bool, str, *str, **str) -> None assert symbols or symbol_kwargs msg string expected at least one symbol to load comment Grab the current build context from the top of the stack. set build_env = _current_build_env comment Resolve ...
def _load(self, is_implicit_include, name, *symbols, **symbol_kwargs): # type: (bool, str, *str, **str) -> None assert symbols or symbol_kwargs, "expected at least one symbol to load" # Grab the current build context from the top of the stack. build_env = self._current_build_env ...
Python
nomic_cornstack_python_v1
function test__remove_excl_file_2 self begin set rsync = call RsyncMethod settings meta log comms false assert equal exclude_file join path environ at string HOME string test_myocp string myocp_excl set exclude_file = join path environ at string HOME string temp/myocp_excl with open exclude_file string w as fp begin wr...
def test__remove_excl_file_2(self): rsync = RsyncMethod(self.settings, self.meta, self.log, self.comms, False) self.assertEqual(rsync.exclude_file, os.path.join(os.environ['HOME'],"test_myocp","myocp_excl")) rsync.exclude_file = os.path.join(os.environ['HOME'],"temp/myocp_excl") with ope...
Python
nomic_cornstack_python_v1
import sys call setrecursionlimit 10 ^ 7 set input = lambda -> strip read line stdin function main begin set tuple N K = map int split input set ans = N % K print if expression ans < absolute ans - K then ans else absolute ans - K end function call main
import sys sys.setrecursionlimit(10**7) input = lambda: sys.stdin.readline().strip() def main(): N,K = map(int,input().split()) ans = N%K print(ans if ans<abs(ans-K) else abs(ans-K)) main()
Python
zaydzuhri_stack_edu_python
for i in sentence begin if i in char begin set char at i = char at i + 1 end else begin set char at i = 1 end end set char_short = sorted items char key=lambda key -> key at 1 print string most repate charter is : { char_short at - 1 at 0 } times of { char_short at - 1 at 1 }
for i in sentence: if i in char: char[i] += 1 else: char[i] = 1 char_short = sorted(char.items(), key=lambda key: key[1]) print( f"most repate charter is : {char_short[-1][0]} times of {char_short[-1][1]}")
Python
zaydzuhri_stack_edu_python
function cmdloop self intro=none begin comment displays intro msg only once print intro end function
def cmdloop(self, intro=None): print(self.intro) # displays intro msg only once
Python
nomic_cornstack_python_v1
import socket import time import select set HEADER_LENGTH = 10 set IP = string 127.0.0.1 set PORT = 1234 set server = call socket AF_INET SOCK_STREAM comment Enable us to reconnect call setsockopt SOL_SOCKET SO_REUSEADDR 1 call bind tuple IP PORT call listen print string Server Listening on Port { PORT } set socket_lis...
import socket import time import select HEADER_LENGTH = 10 IP = '127.0.0.1' PORT = 1234 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Enable us to reconnect server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((IP, PORT)) server.listen() print(f'Server Listening on Port {PORT}') ...
Python
zaydzuhri_stack_edu_python
set players = list string 1charles string 2martina string 3michael string 4florence string 5eli print string The first three items in the list are: print players at slice 0 : 3 : print string Three items from the middle of the list are: print players at slice 1 : 4 : print string The last three items in the list are: p...
players = ['1charles', '2martina', '3michael', '4florence', '5eli'] print("The first three items in the list are: ") print(players[0:3]) print("Three items from the middle of the list are: ") print(players[1:4]) print("The last three items in the list are: ") print(players[-3:])
Python
zaydzuhri_stack_edu_python
import sqlite3 import datetime import re function check_postcode postcode begin set valid_postcode = false set postcode = upper postcode if match string ^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$ postcode begin set valid_postcode = true end return valid_postcode end function function correct_format postcode begin set postcode ...
import sqlite3 import datetime import re def check_postcode(postcode): valid_postcode = False postcode = postcode.upper() if re.match("^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$", postcode): valid_postcode = True return valid_postcode def correct_format(postcode): postcode = postcode.u...
Python
zaydzuhri_stack_edu_python
from lib.aoclib import AOCLib set puzzle = tuple 2018 2 comment Initialise the helper library set aoc = call AOCLib puzzle at 0 set puzzle_input = call get_puzzle_input puzzle at 1 lines_to_list set repeat_counts = dict for box_id in puzzle_input begin set letter_counts = dict for letter in box_id begin set letter_co...
from lib.aoclib import AOCLib puzzle = (2018, 2) # Initialise the helper library aoc = AOCLib(puzzle[0]) puzzle_input = aoc.get_puzzle_input(puzzle[1], AOCLib.lines_to_list) repeat_counts = {} for box_id in puzzle_input: letter_counts = {} for letter in box_id: letter_counts[letter] = letter_count...
Python
zaydzuhri_stack_edu_python
import re import sys comment check for a command line argument if length argv > 1 begin set file_name = argv at 1 end else begin print string No input file given exit end comment parse the given input file and split the setnence based on the FANBOYS conjuctions with open file_name string r as reader begin set sentence ...
import re import sys #check for a command line argument if len(sys.argv) > 1: file_name = sys.argv[1] else: print("No input file given") sys.exit() #parse the given input file and split the setnence based on the FANBOYS conjuctions with open(file_name, 'r') as reader: sentence = reader.readline() ...
Python
zaydzuhri_stack_edu_python
function zlib_compress s begin import zlib set compressed = compress string s return encode compressed string base64 end function comment return cgi.escape(s, quote=True) # escapes "<", ">", "&" "'" and '"'
def zlib_compress(s): import zlib compressed = zlib.compress(str(s)) return compressed.encode('base64') # return cgi.escape(s, quote=True) # escapes "<", ">", "&" "'" and '"'
Python
nomic_cornstack_python_v1
import cv2 import numpy as np set img = call imread string sanmarcos.jpg set tuple height width = shape at slice : 2 : set tuple start_row start_col = tuple integer height * 0.25 integer width * 0.25 set tuple end_row end_col = tuple integer height * 0.75 integer width * 0.75 set cropped = img at tuple slice start_ro...
import cv2 import numpy as np img =cv2.imread('sanmarcos.jpg') height,width=img.shape[:2] start_row,start_col=int(height*0.25),int(width*0.25) end_row,end_col=int(height*0.75),int(width*0.75) cropped=img[start_row:end_row,start_col:end_col] cv2.imshow("orginal" ,img) cv2.imshow("cropped",cropped) cv2...
Python
zaydzuhri_stack_edu_python
function kids self line begin set words = split call substitute_symbols line if length words != 1 begin print string Need an object address. return end set id = integer words at 0 call display_fancy call fetchall string select * from obj where address = :addr addr=id set ids_to_show = set list id set ids_shown = set wh...
def kids(self, line): words = self.substitute_symbols(line).split() if len(words) != 1: print("Need an object address.") return id = int(words[0]) self.display_fancy( self.fetchall( "select * from obj where address = :addr", ...
Python
nomic_cornstack_python_v1
function Clone self begin set callResult = call _Call string Clone if callResult is none begin return none end set objId = callResult set classInstance = ParameterSetMapping return call classInstance _xmlRpc objId end function
def Clone(self): callResult = self._Call("Clone", ) if callResult is None: return None objId = callResult classInstance = ParameterSetMapping return classInstance(self._xmlRpc, objId)
Python
nomic_cornstack_python_v1
function main begin comment Parse and verify the script args. if length argv != 3 begin raise call ValueError string Input and output files not specified end set work_log_path = argv at 1 if not exists path work_log_path begin raise call ValueError string File to parse not found: + work_log_path end set output_path = a...
def main(): # Parse and verify the script args. if len(sys.argv) != 3: raise ValueError("Input and output files not specified") work_log_path = sys.argv[1] if not os.path.exists(work_log_path): raise ValueError("File to parse not found: " + work_log_path) output_path = sys.argv[2] ...
Python
nomic_cornstack_python_v1
function main begin set parser = call ArgumentParser description=string Convert Thunderbird address ldif to your LDAP ldif, or the reverse. call add_argument string -b metavar=string BASE_PATH dest=string base_path default=string help=string ldap base path call add_argument string -f metavar=string FILE dest=string fn...
def main(): parser = argparse.ArgumentParser( description='Convert Thunderbird address ldif to your LDAP ldif,' ' or the reverse.') parser.add_argument('-b', metavar='BASE_PATH', dest='base_path', default='', ...
Python
nomic_cornstack_python_v1
function count_symbols sort_by_alpha=false sort_by_freq=false begin set symbol_dict = dict set args = call get_command_line_args if symbol is none begin set symb_query = string * end else begin set symb_query = call normalize string NFC symbol end set query = directory + string / + symb_query + string _*.jpg set count...
def count_symbols(sort_by_alpha=False, sort_by_freq=False): symbol_dict = {} args = DeepScribe.get_command_line_args() if args.symbol is None: symb_query = "*" else: symb_query = unicodedata.normalize('NFC', args.symbol) query = args.dir...
Python
nomic_cornstack_python_v1
from datetime import date from unittest.mock import patch from app import db from app.models import List , ListSettings , Meal from helpers import push_dummy_user , push_dummy_list , AppModelCase class DayModelCase extends AppModelCase begin decorator call object List string get_settings_for_user function test_repr_day...
from datetime import date from unittest.mock import patch from app import db from app.models import List, ListSettings, Meal from helpers import push_dummy_user, push_dummy_list, AppModelCase class DayModelCase(AppModelCase): @patch.object(List, 'get_settings_for_user') def test_repr_day(self, mock_get_setti...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class class Solution begin function maxDepth self root begin string :type root: TreeNode :rtype: int set depth = 0 set level = if expre...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ depth = 0...
Python
zaydzuhri_stack_edu_python
function analyze self event begin comment NO CUT call Fill cut_none comment TRIGGER if not HLT_IsoMu24 begin return false end call Fill cut_trig comment SELECT MUON set muons = list for muon in call Collection event string Muon begin if pt < 20 begin continue end if absolute eta > 2.4 begin continue end if absolute dz...
def analyze(self, event): # NO CUT self.cutflow.Fill(self.cut_none) # TRIGGER if not event.HLT_IsoMu24: return False self.cutflow.Fill(self.cut_trig) # SELECT MUON muons = [ ] for muon in Collection(event,'Muon'): if muon.pt<20: continue if abs(muon.eta)>2.4: c...
Python
nomic_cornstack_python_v1
comment ----------------------------------------- q1 comment def string_times(str, n): comment newStr = "" comment for i in range(n): comment newStr = newStr + str comment return newStr comment ------------------------------------------ q2 comment def front_times(str, n): comment newStr = "" comment for i in range(n): ...
#----------------------------------------- q1 #def string_times(str, n): # newStr = "" # for i in range(n): # newStr = newStr + str # return newStr #------------------------------------------ q2 #def front_times(str, n): # newStr = "" # for i in range(n): # newStr = newStr + str[:3] # r...
Python
zaydzuhri_stack_edu_python
function upload_log_file_metadata self begin if get environ string TEST_POSTJOB_NO_STATUS_UPDATE false begin return end set temp_storage_site = get job_report string temp_storage_site string unknown if temp_storage_site == string unknown begin set msg = string Temporary storage site for logs archive file not defined in...
def upload_log_file_metadata(self): if os.environ.get('TEST_POSTJOB_NO_STATUS_UPDATE', False): return temp_storage_site = self.job_report.get('temp_storage_site', 'unknown') if temp_storage_site == 'unknown': msg = "Temporary storage site for logs archive file not defined...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd from imblearn.over_sampling import SMOTE from imblearn.under_sampling import EditedNearestNeighbours from imblearn.combine import SMOTEENN string Helper function to perform one of different under/over sampling technique. Test data is separated here also. function get_sets df overs...
import numpy as np import pandas as pd from imblearn.over_sampling import SMOTE from imblearn.under_sampling import EditedNearestNeighbours from imblearn.combine import SMOTEENN """ Helper function to perform one of different under/over sampling technique. Test data is separated here also. """ def get_sets(df , ove...
Python
zaydzuhri_stack_edu_python
function procYear player kNeighbors=4 year=string begin comment load the knn clustering class object set knnObj = call knn set k = kNeighbors comment Choose CPU or GPU distance calculations set procList = list string CPU comment read fangraphs csv into dataframe comment downloaded from https://www.fangraphs.com/ set df...
def procYear(player, kNeighbors=4, year=''): ## load the knn clustering class object knnObj = knn.knn() knnObj.k = kNeighbors knnObj.procList = ['CPU'] ## Choose CPU or GPU distance calculations ## read fangraphs csv into dataframe ## downloaded from https://www.fangraphs.com/ df = pd.read...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup set url = input string Enter the URL of the website to scrape: set response = get requests url set soup = call BeautifulSoup content string html.parser set title = string print string Title of the website is: { title }
import requests from bs4 import BeautifulSoup url = input('Enter the URL of the website to scrape: ') response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') title = soup.title.string print(f'Title of the website is: {title}')
Python
flytech_python_25k
comment steps comment 1. specify how the pre processing should be done comment 2. Use the dataset to load the data --> Tabular Data (json, csv, tsv) comment 3. Construct the iterator to do batching and padding -BucketIterator from torchtext.data import Field , TabularDataset , BucketIterator import spacy import os try ...
# steps # 1. specify how the pre processing should be done # 2. Use the dataset to load the data --> Tabular Data (json, csv, tsv) # 3. Construct the iterator to do batching and padding -BucketIterator from torchtext.data import Field, TabularDataset, BucketIterator import spacy import os try: spacy_en = spacy.l...
Python
zaydzuhri_stack_edu_python
function delete_download self begin set resp = call container_check tur_arg at string container if status == 404 begin exit string The Container you want to use does not exist end set cfl = call get_object_list tur_arg at string container set tur_arg at string fc = length cfl print string Processing "%s" Objects % tur_...
def delete_download(self): resp = self.nova.container_check(self.tur_arg['container']) if resp.status == 404: sys.exit('The Container you want to use does not exist') cfl = self.nova.get_object_list(self.tur_arg['container']) self.tur_arg['fc'] = len(cfl) print('Proce...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python import sys class IT begin function __init__ self intervals arr begin set L = list set R = list set M = list set medIndex = length arr / 2 set median = arr at medIndex for loop in range length intervals begin if intervals at loop at 0 <= median and median <= intervals at loop at 1 begin ...
#! /usr/bin/env python import sys class IT: def __init__(self, intervals , arr): L = [] R = [] M = [] medIndex = (len(arr))/2 median = arr[medIndex] for loop in range(len(intervals)): if intervals[loop][0] <= median and median <= intervals[loop][1]: M.append(intervals[loop]) elif median < interv...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import os from tqdm import tqdm import argparse from utils.utils import create_tfr_files , prob_to_secondary_structure from utils.FastaMLtoSL import FastaMLtoSL import time set start = time from argparse import RawTextHelpFormatter set parser = call ArgumentParser call add_arg...
import tensorflow as tf import numpy as np import os from tqdm import tqdm import argparse from utils.utils import create_tfr_files, prob_to_secondary_structure from utils.FastaMLtoSL import FastaMLtoSL import time start = time.time() from argparse import RawTextHelpFormatter parser = argparse.ArgumentParser() parser....
Python
jtatman_500k