code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function expiration_seconds self begin return get pulumi self string expiration_seconds end function
def expiration_seconds(self) -> Optional[int]: return pulumi.get(self, "expiration_seconds")
Python
nomic_cornstack_python_v1
function glob_list self l begin function glob_item_re item begin if string * not in item and string ? not in item begin return call escape item end return join string list comprehension if expression c == string * then string .* else if expression c == string ? then string . else call escape c for c in item end functi...
def glob_list(self, l): def glob_item_re(item): if '*' not in item and '?' not in item: return re.escape(item) return ''.join([ '.*' if c == '*' else '.' if c == '?' else re.escape(c) for c in item ...
Python
nomic_cornstack_python_v1
comment Crescimento da população brasileira 1980 - 2016 comment DataSus database do governo import matplotlib.pyplot as plt set dados = read lines open string dataScience\BrazilianPopulation\populacao_brasileira.csv string r set years = list set population = list for i in range length dados begin if i != 0 begin set ...
#Crescimento da população brasileira 1980 - 2016 #DataSus database do governo import matplotlib.pyplot as plt dados = open("dataScience\BrazilianPopulation\populacao_brasileira.csv", "r").readlines() years = [] population = [] for i in range(len(dados)): if i != 0 : linha = dados[i].split(";") y...
Python
zaydzuhri_stack_edu_python
comment for loop for fruit in fruits begin print fruit end comment while loop set i = 0 while i < length fruits begin print fruits at i set i = i + 1 end
# for loop for fruit in fruits: print(fruit) # while loop i = 0 while i<len(fruits): print(fruits[i]) i =i+1
Python
zaydzuhri_stack_edu_python
function col_means x na_rm=false begin comment dims: int = 1, comment weights = None, comment freq = None, comment n = None return call agg mean na_rm=na_rm end function
def col_means( x: DataFrame, na_rm: bool = False, # dims: int = 1, # weights = None, # freq = None, # n = None ) -> Iterable[NumericType]: return x.agg(mean, na_rm=na_rm)
Python
nomic_cornstack_python_v1
function get_members self groupName begin set route = string wiki/rest/api/group/ { groupName } /member return get self route=route end function
def get_members(self, groupName): route = f"wiki/rest/api/group/{groupName}/member" return self.get(route=route)
Python
nomic_cornstack_python_v1
function sort_sentence sentence begin set words = call break_words sentence return call sort_words words end function
def sort_sentence(sentence): words = break_words(sentence) return sort_words(words)
Python
nomic_cornstack_python_v1
import numpy as np set filename = string iris.data comment Read in data set data = call genfromtxt filename dtype=none names=list string slength string swidth string plength string pwidth string class delimiter=string , comment Generate test set randomly from data, then remove those elements from data set test_i = rand...
import numpy as np filename='iris.data' #Read in data data = np.genfromtxt(filename, dtype=None, names = ['slength','swidth','plength','pwidth','class'], delimiter=",") #Generate test set randomly from data, then remove those elements from data test_i = np.random.choice(range(len(data)),size=10,replace=False) test =...
Python
zaydzuhri_stack_edu_python
function n self begin if not table begin return 0 end return max omega + 1 end function
def n(self): if not self.table: return 0 return max(self.omega) + 1
Python
nomic_cornstack_python_v1
with open string sequence.nucleotide.fasta string r as fr begin for line in fr begin if starts with line string > begin set title = line end else begin set seq = seq + strip line end end end set sequence_reversed = join string reversed seq set sequence_ATGC = dict string A string T ; string T string A ; string G strin...
with open("sequence.nucleotide.fasta","r") as fr: for line in fr: if line.startswith(">"): title = line else: seq += line.strip() sequence_reversed = ''.join(reversed(seq)) sequence_ATGC = {"A":"T", "T":"A", "G":"C", "C":"...
Python
zaydzuhri_stack_edu_python
comment encoding=utf-8 from selenium import webdriver import time from selenium.webdriver import ActionChains set driver = call Firefox set web_url = string https://www.jd.com get driver web_url sleep 5 call maximize_window comment 获取一组分类子元素 set el_list = call find_elements_by_class_name string cate_menu_item for el in...
#encoding=utf-8 from selenium import webdriver import time from selenium.webdriver import ActionChains driver=webdriver.Firefox() web_url="https://www.jd.com" driver.get(web_url) time.sleep(5) driver.maximize_window() #获取一组分类子元素 el_list=driver.find_elements_by_class_name("cate_menu_item") for el in el_list: ...
Python
zaydzuhri_stack_edu_python
import sys import boto3 import argparse import os import csv from botocore.exceptions import ClientError set client = call client string dynamodb set dynamodb = call resource string dynamodb function main begin set parser = call ArgumentParser description=string delete evidence in environment specified. call add_argume...
import sys import boto3 import argparse import os import csv from botocore.exceptions import ClientError client = boto3.client('dynamodb') dynamodb = boto3.resource('dynamodb') def main(): parser = argparse.ArgumentParser(description= 'delete evidence in environm...
Python
zaydzuhri_stack_edu_python
function activation x begin return 1.0 / 1.0 + exp - 5 * x end function
def activation(x): return 1.0 / (1.0 + K.exp(-5 * x))
Python
nomic_cornstack_python_v1
function x_to_rad self x begin set x = x + KICKER_OFFSET set d = x - 2160.0 * pi * 2 / 3840 if d > pi begin set d = d - pi * 2 end if d < - pi begin set d = d + pi * 2 end return d end function
def x_to_rad(self, x): x += self.KICKER_OFFSET d = (x-2160.0)*(math.pi*2)/(3840) if d > math.pi: d -= math.pi * 2 if d < -math.pi: d += math.pi * 2 return d
Python
nomic_cornstack_python_v1
string Assigment #1 The Student Life Simulator starter code. You should complete every incomplete function, and add more functions and variables as needed. Also add comments as required. Note that incomplete functions have 'pass' as the first statement: pass is a Python keyword; it is a statement that does nothing. Thi...
""" Assigment #1 The Student Life Simulator starter code. You should complete every incomplete function, and add more functions and variables as needed. Also add comments as required. Note that incomplete functions have 'pass' as the first statement: pass is a Python keyword; it is a statement that does nothing. This ...
Python
zaydzuhri_stack_edu_python
function check_genera begin set genera = get args string genera set genera_dat = execute db string SELECT * FROM genera WHERE genera =:genera genera=genera if length genera > 1 and length genera_dat != 0 begin return call jsonify true end else begin return call jsonify false end end function
def check_genera(): genera = request.args.get("genera") genera_dat = db.execute("SELECT * FROM genera WHERE genera =:genera", genera=genera) if len(genera) > 1 and len(genera_dat) != 0: return jsonify(True) else: return jsonify(False)
Python
nomic_cornstack_python_v1
import uos from machine import Pin import machine import utime set sensor_temp = call ADC 4 set conversion_factor = 3.3 / 65535 set led = call Pin 25 OUT while true begin call value 1 set f = open string data.txt string a set reading = call read_u16 * conversion_factor set temperature = 27 - reading - 0.706 / 0.001721 ...
import uos from machine import Pin import machine import utime sensor_temp = machine.ADC(4) conversion_factor = 3.3 / (65535) led = Pin(25, Pin.OUT) while True: led.value(1) f = open('data.txt', 'a') reading = sensor_temp.read_u16() * conversion_factor temperature = 27 - (reading - 0.706)/0.001721 ...
Python
zaydzuhri_stack_edu_python
function calc_stacked df ngroups nsubgroups begin set tuple x y = tuple columns at 0 columns at 1 set tuple df grp_cnt_stats largest_grps = call _calc_groups df x ngroups set fin_df = call DataFrame for grp in largest_grps begin set df_grp = df at df at x == grp set df_res = call nlargest n=nsubgroups / length df_grp *...
def calc_stacked( df: dd.DataFrame, ngroups: int, nsubgroups: int, ) -> Tuple[pd.DataFrame, Dict[str, int]]: x, y = df.columns[0], df.columns[1] df, grp_cnt_stats, largest_grps = _calc_groups(df, x, ngroups) fin_df = pd.DataFrame() for grp in largest_grps: df_grp = df[df[x] == grp] ...
Python
nomic_cornstack_python_v1
function getColorModel self begin return call getColorModel end function
def getColorModel(self): return self.getModel().getColorModel()
Python
nomic_cornstack_python_v1
function test_without_matches self begin set match_column_1 = 1 set match_column_2 = 1 set input_data_1 = TESTS_DATA_1 set input_data_2 = TESTS_DATA_2 set result = match assert equal string Activated result at 0 at 0 assert equal string Money result at 0 at 1 assert equal string Name result at 0 at 4 assert equal 1 len...
def test_without_matches(self): self.matcher.match_column_1 = 1 self.matcher.match_column_2 = 1 self.matcher.input_data_1 = self.TESTS_DATA_1 self.matcher.input_data_2 = self.TESTS_DATA_2 result = self.matcher.match() self.assertEqual('Activated', result[0][0]) se...
Python
nomic_cornstack_python_v1
comment coding: utf-8 try begin set namefile = input string Файл-Оболочка: with open namefile string rb as file1 begin set read1 = read file1 end end except FileNotFoundError begin print string [x] Файл: ' + string namefile + string 'Не найден! raise SystemExit end try begin set zipfile = input string Zip-Файл: with op...
#coding: utf-8 try: namefile= input("Файл-Оболочка: ") with open(namefile, 'rb') as file1: read1=file1.read() except FileNotFoundError: print("[x] Файл: '"+str(namefile)+ "'Не найден!") raise SystemExit try: zipfile=input("Zip-Файл: ") with open(zipfile, 'rb') as file2: read2=file2.read() except F...
Python
zaydzuhri_stack_edu_python
import torch as t from HW1.utils import variable import numpy as np from torch.nn import Sigmoid import torchtext from torchtext.vocab import Vectors , GloVe function vectorize text TEXT vdim=300 begin set tuple length batch_size = shape return mean t call cat list comprehension view vectors at transpose data 0 1 at i ...
import torch as t from HW1.utils import variable import numpy as np from torch.nn import Sigmoid import torchtext from torchtext.vocab import Vectors, GloVe def vectorize(text, TEXT, vdim=300): length, batch_size = text.data.numpy().shape return t.mean(t.cat([TEXT.vocab.vectors[text.long().data.transpose(0,1)...
Python
zaydzuhri_stack_edu_python
string import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(10, 10)) ax.set(xlim=(-3, 3), ylim=(-1, 1)) x = np.linspace(-3, 3, 91) t = np.linspace(0, 900, 900) y = np.linspace(-3, 3, 91) X3, Y3, T3 = np.meshgrid(x, y, t...
"""import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(10, 10)) ax.set(xlim=(-3, 3), ylim=(-1, 1)) x = np.linspace(-3, 3, 91) t = np.linspace(0, 900, 900) y = np.linspace(-3, 3, 91) X3, Y3, T3 = np.meshgrid(x, y, t) ...
Python
zaydzuhri_stack_edu_python
function count_genomic_region_plot self begin string Generate the SnpEff Counts by Genomic Region plot comment Sort the keys based on the total counts set keys = snpeff_section_totals at string # Count by genomic region set sorted_keys = sorted keys reverse=true key=get comment Make nicer label names set pkeys = ordere...
def count_genomic_region_plot(self): """ Generate the SnpEff Counts by Genomic Region plot """ # Sort the keys based on the total counts keys = self.snpeff_section_totals['# Count by genomic region'] sorted_keys = sorted(keys, reverse=True, key=keys.get) # Make nicer label name...
Python
jtatman_500k
import sys from PyQt5.QtSql import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * function initializeModel model begin call setTable string Assets call setEditStrategy OnFieldChange select model call setHeaderData 0 Horizontal string ID call setHeaderData 1 Horizontal string name c...
import sys from PyQt5.QtSql import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * def initializeModel(model): model.setTable('Assets') model.setEditStrategy(QSqlTableModel.OnFieldChange) model.select() model.setHeaderData(0,Qt.Horizontal,'ID') model.setHeaderD...
Python
zaydzuhri_stack_edu_python
from trainRO import load_embedding , load_data , preprocess_dataset from trainEN import load_data_sen from settings import DATA_FILE_RO , EMBEDDINGS_FILE_RO , OBJ_FILE_EN , SUBJ_FILE_EN , EMBEDDINGS_FILE_EN import matplotlib.pyplot as plt from collections import Counter set ENGLISH = 0 function test_above limit sentenc...
from trainRO import load_embedding, load_data, preprocess_dataset from trainEN import load_data_sen from settings import DATA_FILE_RO, EMBEDDINGS_FILE_RO, OBJ_FILE_EN, SUBJ_FILE_EN, EMBEDDINGS_FILE_EN import matplotlib.pyplot as plt from collections import Counter ENGLISH = 0 def test_above(limit, sentences): a...
Python
zaydzuhri_stack_edu_python
string you are given Alexnet network with pre-trained weights (alexnet.py uses bvlx-alexnet.npy). use it for inference of animal images. from helper import read_images , print_output from alexnet import AlexNet import tensorflow as tf set tuple im1 im2 = call read_images string poodle.png string weasel.png comment Alex...
""" you are given Alexnet network with pre-trained weights (alexnet.py uses bvlx-alexnet.npy). use it for inference of animal images. """ from helper import read_images, print_output from alexnet import AlexNet import tensorflow as tf im1, im2 = read_images('poodle.png', 'weasel.png') # Alexnet requires (227,277,3) x ...
Python
zaydzuhri_stack_edu_python
function list_iam_policy_assignments status=none namespace=string default account_id=none boto3_session=none begin set args : Dict at tuple str Any = dict string func_name string list_iam_policy_assignments ; string attr_name string IAMPolicyAssignments ; string account_id account_id ; string boto3_session boto3_sessio...
def list_iam_policy_assignments( status: Optional[str] = None, namespace: str = "default", account_id: Optional[str] = None, boto3_session: Optional[boto3.Session] = None, ) -> List[Dict[str, Any]]: args: Dict[str, Any] = { "func_name": "list_iam_policy_assignments", "attr_name": "IA...
Python
nomic_cornstack_python_v1
function __init__ self parent panel=none begin comment sheet.CSheet.__init__(self, parent) comment The following is the __init__ from CSheet. ########################## comment We re-write it here because the class is broken in wx 3.0, comment such that the cell editor is not able to receive the right comment number of...
def __init__(self, parent, panel=None): #sheet.CSheet.__init__(self, parent) # The following is the __init__ from CSheet. ########################## # We re-write it here because the class is broken in wx 3.0, # such that the cell editor is not able to receive the right # number...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- from Tkinter import * class Window extends Frame begin function __init__ self master=none begin call __init__ self master set master = master set wod_select = call IntVar set 0 set user_name = call Entry self set age = call Entry self set sex = call IntVar call Ne...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from Tkinter import * class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.wod_select = IntVar() self.wod_select.set(0) self.user_name = Entry(self) ...
Python
zaydzuhri_stack_edu_python
import sys call setrecursionlimit 4100000 import math set INF = 10 ^ 9 function main begin set n = integer input set a = integer input if n % 500 <= a begin print string Yes end else begin print string No end end function if __name__ == string __main__ begin call main end
import sys sys.setrecursionlimit(4100000) import math INF = 10**9 def main(): n = int(input()) a = int(input()) if n%500 <= a: print('Yes') else: print('No') if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from keras.utils import to_categorical import time class MNISTClassifier begin function __init__ self X_train X_test y_train y_test features_size begin set X_train = X_train set X_test = X_test set y_train ...
import numpy as np from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from keras.utils import to_categorical import time class MNISTClassifier(): def __init__(self, X_train, X_test, y_train, y_test, features_size): self.X_train = X_train self.X_test = X...
Python
zaydzuhri_stack_edu_python
function store_mapping mapping outdir prefix begin set fh = open outdir + string / + prefix + string _mapping.txt string w for tuple key valuelist in call iteritems begin write fh string %s: % key for v in valuelist begin write fh string %s % v end write fh string end close fh end function
def store_mapping(mapping, outdir, prefix): fh = open(outdir + "/" + prefix + "_mapping.txt", "w") for (key, valuelist) in mapping.iteritems(): fh.write("%s:" % key) for v in valuelist: fh.write("\t%s" % v) fh.write("\n") fh.close()
Python
nomic_cornstack_python_v1
string 1.随机生成1000个整数 2.范围[20,100] 3.升序输出所有不同的数字及其每个数字重复的次数 import random set num_dirc = dict comment 统计数字及对应的次数 for i in range 1000 begin set num_key = random integer 20 100 if num_key in num_dirc begin set num_dirc at num_key = num_dirc at num_key + 1 end else begin set num_dirc at num_key = 1 end end comment 排序,便历输出...
''' 1.随机生成1000个整数 2.范围[20,100] 3.升序输出所有不同的数字及其每个数字重复的次数 ''' import random num_dirc = {} #统计数字及对应的次数 for i in range (1000): num_key = random.randint(20,100) if num_key in num_dirc: num_dirc[num_key] += 1 else: num_dirc[num_key] = 1 ##排序,便历输出 for i in sorted(num_dirc.keys()):...
Python
zaydzuhri_stack_edu_python
comment 作者 ljc set tuple user passwd = tuple string ljc string 123 function dec_login login_type begin print string longtype login_type function outer_wapper func begin function wrapper *args **kwargs begin print string ss *args keyword kwargs set username = input string please input name set password = input string pl...
# 作者 ljc user, passwd = "ljc", "123" def dec_login(login_type): print("longtype",login_type) def outer_wapper(func): def wrapper(*args, **kwargs): print("ss",*args,**kwargs) username = input("please input name") password = input("please input password") ...
Python
zaydzuhri_stack_edu_python
function sieve top begin set flags = list comprehension true for _ in range top + 1 set flags at 0 = false set flags at 1 = false for i in range length flags begin if flags at i begin for j in range i + 1 length flags begin if flags at j and j % i == 0 begin set flags at j = false end end end end return list comprehens...
def sieve(top): flags = [True for _ in range(top + 1)] flags[0] = flags[1] = False for i in range(len(flags)): if flags[i]: for j in range(i + 1, len(flags)): if flags[j] and j % i == 0: flags[j] = False return [i for i, f in enumerate(flags) if f...
Python
zaydzuhri_stack_edu_python
import fresh_tomatoes import media comment import the necessary files required set thupaki = string https://upload.wikimedia.org/wikipedia/en/b/be/Thuppakki_poster.jpg set magadhera = string http://photos.filmibeat.com/ph-big/2012/01/1325845008613892.jpg set viveegam = string https://upload.wikimedia.org/wikipedia/en/b...
import fresh_tomatoes import media # import the necessary files required thupaki = "https://upload.wikimedia.org/wikipedia/en/b/be/Thuppakki_poster.jpg" magadhera = "http://photos.filmibeat.com/ph-big/2012/01/1325845008613892.jpg" viveegam = "https://upload.wikimedia.org/wikipedia/en/b/be/Vivegam_poster.jpg" Mr =...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import string function reactive_units begin set forward = set list comprehension string { char } { upper char } for char in list ascii_lowercase set backward = set list comprehension string { char } { lower char } for char in list ascii_uppercase return union forward backward end...
#!/usr/bin/env python import sys import string def reactive_units(): forward = set([f'{char}{char.upper()}' for char in list(string.ascii_lowercase)]) backward = set([f'{char}{char.lower()}' for char in list(string.ascii_uppercase)]) return forward.union(backward) def react(molecule, reactive_units): ...
Python
zaydzuhri_stack_edu_python
comment array[Axes] function axes_active self begin return flat at slice : n_plots : end function
def axes_active(self) -> np.ndarray: # array[Axes] return self.axes.flat[:self.n_plots]
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import sys import requests from selenium import webdriver import time import csv set driver = call Firefox set url = string https://www.industrybuying.com/ call maximize_window get driver url sleep 5 set content = strip encode page_source string utf-8 set soup = call BeautifulSoup content ...
from bs4 import BeautifulSoup import sys import requests from selenium import webdriver import time import csv driver = webdriver.Firefox() url = 'https://www.industrybuying.com/' driver.maximize_window() driver.get(url) time.sleep(5) content = driver.page_source.encode('utf-8').strip() soup = BeautifulSoup(content,...
Python
zaydzuhri_stack_edu_python
import scipy.linalg import numpy as np from tqdm import tqdm function gibbs_sample G M num_iters begin string Gibbs sample player skills. Accepts: G - Game array G[i, 0] is winner of game i G[i, 1] is loser M - number of players num_iters - number of Gibbs iterations Returns: skill_samples - skill_samples[i, j] is samp...
import scipy.linalg import numpy as np from tqdm import tqdm def gibbs_sample(G, M, num_iters): """ Gibbs sample player skills. Accepts: G - Game array G[i, 0] is winner of game i G[i, 1] is loser M - number of players num_iters - number of Gibbs iterations Returns: skill_samples...
Python
zaydzuhri_stack_edu_python
function stop self begin info string sending stop signal to all hardware for waveform output with _async begin for tuple d n in reversed sorted_device_list begin call _async d string stop end end debug string sent stop signal to all hardware for waveform output call _clean_pyro_cache end function
def stop(self): logging.info( 'sending stop signal to all hardware for waveform output' ) with self._async: for d, n in reversed(self.sorted_device_list): self._async(d, 'stop') logging.debug( 'sent stop signal to all hardware for waveform output' ) self._clean_pyro_cache()
Python
nomic_cornstack_python_v1
comment coding: utf-8 from utlis.GetFileContent import * import re function MatchRule matchData begin string 匹配模板并返回结果 :param matchData: query set dataList = call GetData string ../generationData/dicarRule comment dataList = ['是否是时间 {{时间段}} 有'] set dataLength = length dataList set count = 0 for i in dataList begin set ...
# coding: utf-8 from utlis.GetFileContent import * import re def MatchRule(matchData): """ 匹配模板并返回结果 :param matchData: query """ dataList = GetFileContent.GetData('../generationData/dicarRule') # dataList = ['是否是时间 {{时间段}} 有'] dataLength = len(dataList) count = 0 for i in dataLis...
Python
zaydzuhri_stack_edu_python
function attack self other begin call is_attacked strength end function
def attack(self, other): other.is_attacked(self.strength)
Python
nomic_cornstack_python_v1
function hillclimber timetable iterations *args begin set scores = list comment Iterates over a specified range. for i in range iterations begin comment Apply optional added functions. for function in args at 0 begin call function timetable end score timetable append scores objective_score end return scores end functi...
def hillclimber(timetable, iterations, *args): scores = [] # Iterates over a specified range. for i in range(iterations): # Apply optional added functions. for function in args[0]: function(timetable) timetable.score() scores.append(timetable.objective_score) ...
Python
nomic_cornstack_python_v1
class Solution extends object begin function removeDuplicates self nums begin set tuple i j = tuple 0 1 while j < length nums - 1 begin if nums at i == nums at j + 1 begin del nums at j continue end set i = i + 1 set j = j + 1 end return length nums end function end class
class Solution(object): def removeDuplicates(self, nums): i,j=0,1 while j<len(nums)-1: if nums[i]==nums[j+1]: del nums[j] continue i+=1 j+=1 return len(nums)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Temperature Sensor Script. This python script is used to read temperature sensors on the 1wire bus of the raspberry pi and send the data to a mysql db import MySQLdb import os import glob import logging import time import threading import shutil import signal set __kill__ = false fun...
#!/usr/bin/env python """ Temperature Sensor Script. This python script is used to read temperature sensors on the 1wire bus of the raspberry pi and send the data to a mysql db """ import MySQLdb import os import glob import logging import time import threading import shutil import signal __kill__ = False def safe...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment michael a.g. aïvázis comment california institute of technology comment (c) 1998-2012 all rights reserved import pyre from Functor import Functor class Gaussian extends component begin string An implementation of the normal distribution with mean #@$\mu$@ and variance #@$\sigma^2$@...
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # california institute of technology # (c) 1998-2012 all rights reserved # import pyre from .Functor import Functor class Gaussian(pyre.component, family="gauss.functor.gaussian", implements=Functor): """ An implementation of the normal distribu...
Python
zaydzuhri_stack_edu_python
function parse_node_results sess_time kernel_time_only=false threshold=0 begin set node_name_list = list set node_time = dict set node_freq = dict set node_provider = dict set total = 0 for item in sess_time begin if item at string cat == string Node and string dur in item and string args in item and string op_name...
def parse_node_results(sess_time, kernel_time_only=False, threshold=0): node_name_list = [] node_time = {} node_freq = {} node_provider = {} total = 0 for item in sess_time: if item["cat"] == "Node" and "dur" in item and "args" in item and "op_name" in item["args"]: node_name...
Python
nomic_cornstack_python_v1
import turtle import pandas set screen = call Screen title screen string U.S. States game call addshape string blank_states_img.gif call shape string blank_states_img.gif set guessed_states = list while length guessed_states < 50 begin set answer = title call textinput title=string { length guessed_states } /50 States...
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States game") screen.addshape("blank_states_img.gif") turtle.shape("blank_states_img.gif") guessed_states = [] while len(guessed_states) < 50: answer = screen.textinput(title=f"{len(guessed_states)}/50 States Correct", prompt="Pass another sta...
Python
zaydzuhri_stack_edu_python
while k < num begin set j = num - k set i = i * j set k = k + 1 end set s = list string i set k = 0 for i in s begin set k = k + integer i end
while k < num: j = num - k i = i * j k = k + 1 s = list(str(i)) k = 0 for i in s: k = k + int(i)
Python
zaydzuhri_stack_edu_python
function generate_tree_helper self file begin set command = list string iqtree string -s file string -m string LG+R7 string -B string 1000 string -T string AUTO string -seed string 3333 run command end function
def generate_tree_helper(self, file): command = [ 'iqtree', '-s', file, '-m', 'LG+R7', '-B', '1000', '-T', 'AUTO', '-seed', '3333', ] subprocess.run(command)
Python
nomic_cornstack_python_v1
import numpy as np class Diem begin function __init__ self filename M=5 begin set filename = filename set char_frequency = dictionary set char2id = dictionary set id2char = dictionary set vocab_size = 0 set char_embedding_size = 0 set char_embeddings = none set M = M set word2id = dictionary set id2word = dictionary se...
import numpy as np class Diem(): def __init__(self, filename, M=5): self.filename = filename self.char_frequency = dict() self.char2id = dict() self.id2char = dict() self.vocab_size = 0 self.char_embedding_size = 0 self.char_embeddings = None self.M ...
Python
zaydzuhri_stack_edu_python
function reorderedAttribute self index begin pass end function
def reorderedAttribute(self, index): pass
Python
nomic_cornstack_python_v1
function test_set_non_numeric self begin set pp = call PhysicalProperty assert raises TypeError __set__ MockClassEmpty string not a number end function
def test_set_non_numeric(self): pp = PhysicalProperty() self.assertRaises(TypeError, pp.__set__, MockClassEmpty, "not a number")
Python
nomic_cornstack_python_v1
comment encoding=utf-8 from SockClient import SockClient import logging import random from STATIC_DATA import ADDR , TEAM_NAME from AI import algorithm from Tools import get_treasure_map call basicConfig level=DEBUG format=string %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s datefmt=string %a, %d ...
# encoding=utf-8 from SockClient import SockClient import logging import random from STATIC_DATA import ADDR, TEAM_NAME from AI import algorithm from Tools import get_treasure_map logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', ...
Python
zaydzuhri_stack_edu_python
function menu_item_description self begin if _is_vegetarian is true begin return string Food item %s with menu index of %s added on %s with the price of %s, containing %s calories has a country origin of %s and its main ingredient is %s . Portion size is %s and the food is vegetarian % tuple _menu_item_name _menu_item_...
def menu_item_description(self): if self._is_vegetarian is True: return "Food item ""%s"" with menu index of %s added on %s with the price of %s, containing %s calories has a country origin of %s and its main ingredient is %s . Portion size is %s and the food is vegetarian" % (self._menu_item_name...
Python
nomic_cornstack_python_v1
from game_files.const import * class Character begin string class for character creation function __init__ self my_maze begin comment character sprites set character = call convert_alpha comment character position in cases and pixels set case_x = 0 set case_y = 0 set _x = 0 set _y = 0 comment default image direction se...
from game_files.const import * class Character: '''class for character creation''' def __init__(self, my_maze): #character sprites self.character = py.image.load(ICON_MACGYVER).convert_alpha() #character position in cases and pixels self.case_x = 0 self.case_y = 0 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Filename:changeEncode.py import sys import os import chardet function print_usage begin print string 功能:将指定文件或目录下的[指定编码方式]的文件转换为另一种编码 格式:changeEncode [file|directory] [charset] [match_charset] [file|directory]:文件/目录 [charset]:指定的字符集,默认为utf-8 [match_charset]...
#!/usr/bin/python # -*- coding: utf-8 -*- #Filename:changeEncode.py import sys import os import chardet def print_usage(): print('''功能:将指定文件或目录下的[指定编码方式]的文件转换为另一种编码   格式:changeEncode [file|directory] [charset] [match_charset]   [file|directory]:文件/目录 [charset]:指定的字符集,默认为utf-8   [match_charset]:期望转换的文件的字符集,若...
Python
zaydzuhri_stack_edu_python
comment DFS(Depth-First Search) function dfs graph v visited begin set visited at v = true print v end=string for i in graph at v begin if not visited at i begin call dfs graph i visited end end end function set graph = list list list 2 3 8 list 1 7 list 1 4 5 list 3 5 list 3 4 list 7 list 2 6 8 list 1 7 set visited =...
# DFS(Depth-First Search) def dfs(graph, v, visited): visited[v] = True print(v, end=' ') for i in graph[v]: if not visited[i]: dfs(graph, i, visited) graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [False] * len(graph) dfs(graph, 1, vi...
Python
zaydzuhri_stack_edu_python
function bruteForceTransport cows limit begin set cowWeight = sorted values cows reverse cowWeight end function
def bruteForceTransport(cows,limit): cowWeight = sorted(cows.values()) cowWeight.reverse()
Python
nomic_cornstack_python_v1
function forward self x mask begin comment Compute the parameters for the Bernoulli set embeddings = call compute_embedding x set dist_params = call predict_distribution embeddings set dist_params = squeeze dist_params comment Sample set sampler = call Bernoulli probs=dist_params set actions = random sample comment Com...
def forward(self, x, mask): # Compute the parameters for the Bernoulli embeddings = self.compute_embedding(x) dist_params = self.predict_distribution(embeddings) dist_params = dist_params.squeeze() # Sample sampler = dist.Bernoulli(probs=dist_params) actions = sa...
Python
nomic_cornstack_python_v1
import sys function solution A begin set ending_here = list 0 * length A set starting_here = list 0 * length A for idx in range 1 length A begin set ending_here at idx = max 0 ending_here at idx - 1 + A at idx end for idx in reversed range length A - 1 begin set starting_here at idx = max 0 starting_here at idx + 1 + A...
import sys def solution(A): ending_here = [0] * len(A) starting_here = [0] * len(A) for idx in range(1, len(A)): ending_here[idx] = max(0, ending_here[idx-1] + A[idx]) for idx in reversed(range(len(A)-1)): starting_here[idx] = max(0, starting_here[idx+1] + A[idx]) ...
Python
zaydzuhri_stack_edu_python
function importmodules package_or_toc ignore=none recurse=false silent=none begin string Imports all the sub-modules of a package, a useful technique for developing plugins. By default, this method will walk the directory structure looking for submodules and packages. You can also specify a __toc__ attribute on the pac...
def importmodules(package_or_toc, ignore=None, recurse=False, silent=None): """ Imports all the sub-modules of a package, a useful technique for developing plugins. By default, this method will walk the directory structure looking for submodules and packages. You can also specify a __toc__ attribute ...
Python
jtatman_500k
function key_class updates image_strip image_rects is_white_key=true begin comment Naming convention: Variables used by the Key class as part of a comment closure start with 'c_'. comment State logic and shadows: comment A key may cast a shadow upon the key to its left. A black key casts a comment shadow on an adjacent...
def key_class(updates, image_strip, image_rects, is_white_key=True): # Naming convention: Variables used by the Key class as part of a # closure start with 'c_'. # State logic and shadows: # # A key may cast a shadow upon the key to its left. A black key casts a # shadow on an adjacent white k...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment _*_ coding:utf-8 _*_ from court import Court class Court_book extends object begin function __init__ self begin string 初始化 set court_id = tuple string A string B string C string D set court = call fromkeys court_id set input_error_msg = string Error: the booking is invalid! set book...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ from court import Court class Court_book(object): def __init__(self): """ 初始化 """ self.court_id = ('A', 'B', 'C', 'D') self.court = {}.fromkeys(self.court_id) self.input_error_msg = "Error: the booking is invalid!" ...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function solveSudoku self board begin string :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. function isValid x y begin set temp = board at x at y set board at x at y = string r for i in range 9 begin if board at i at y == temp begin r...
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def isValid(x, y): temp = board[x][y] board[x][y] = 'r' for i in range(9): ...
Python
zaydzuhri_stack_edu_python
from collections import deque import sys set read = readline set tuple n m = map int split right strip read set queue = deque range 1 n + 1 set josephus = list while queue begin if m > 1 begin for _ in range m - 1 begin comment n-1개는 밑으로 보낸다. append queue call popleft end end append josephus call popleft end comment p...
from collections import deque import sys read = sys.stdin.readline n, m = map(int,read().rstrip().split()) queue = deque(range(1,n+1)) josephus = [] while queue: if m > 1: for _ in range(m-1): # n-1개는 밑으로 보낸다. queue.append(queue.popleft()) josephus.append(queue.poplef...
Python
zaydzuhri_stack_edu_python
comment David Snider comment 3/8/16 set data = split input set already = list set out = list for w in data begin if w in already begin if w in out begin pass end else begin append out w end end else begin append already w end end sort out for item in out begin print item end=string end
#David Snider #3/8/16 data = input().split() already = [] out = [] for w in data: if w in already: if w in out: pass else: out.append(w) else: already.append(w) out.sort() for item in out: print(item,end=' ')
Python
zaydzuhri_stack_edu_python
string This script pulls sequence information from the (few) pages that contain the html versions of them for various programs.. it also populates the Program table and SequenceDetails table import pycurl import re comment this is because common LISP has corrupted me function cdr somelist begin set newList = somelist r...
""" This script pulls sequence information from the (few) pages that contain the html versions of them for various programs.. it also populates the Program table and SequenceDetails table """ import pycurl import re #this is because common LISP has corrupted me def cdr(somelist): newList = somelist newList.r...
Python
zaydzuhri_stack_edu_python
import unittest from solution import Solution , TreeNode class TestSolution extends TestCase begin function setUp self begin set s = call Solution end function function test_empty self begin set exp = none set act = call invertTree none assert equal act exp end function function test_one self begin set exp = call TreeN...
import unittest from solution import Solution, TreeNode class TestSolution(unittest.TestCase): def setUp(self): self.s = Solution() def test_empty(self): exp = None act = self.s.invertTree(None) self.assertEqual(act, exp) def test_one(self): exp = TreeNode(4, Tre...
Python
zaydzuhri_stack_edu_python
import sqlite3 string A utility class to serve connection to the Database class Connection begin function __init__ self begin set database = string app.db set conn = call connect database set row_factory = Row end function function get_db_connection self begin return conn end function end class
import sqlite3 """ A utility class to serve connection to the Database """ class Connection: def __init__(self): self.database = "app.db" self.conn = sqlite3.connect(self.database) self.conn.row_factory = sqlite3.Row def get_db_connection(self): return self.conn
Python
zaydzuhri_stack_edu_python
class CoffeeMachine begin function __init__ self begin set resources = resources set money = 0 end function function check_resources self order begin for tuple ingredient amount in items MENU at order at string ingredients begin if resources at ingredient < amount begin return ingredient end end return true end functio...
class CoffeeMachine: def __init__(self): self.resources = resources self.money = 0 def check_resources(self, order): for ingredient, amount in MENU[order]["ingredients"].items(): if resources[ingredient] < amount: return ingredient return True de...
Python
zaydzuhri_stack_edu_python
comment programa q leia 5 valores numéricos e guarde-os em uma lista. Mostre qual foi o maior e o menor valor digitado e as comment suas respectivas posições na lista string #solucao incompleta, para fzer um loop q qndo houver mais de um numero igual imprima tdas as posições lista = [] cont = 0 for numero in range(0,5)...
# programa q leia 5 valores numéricos e guarde-os em uma lista. Mostre qual foi o maior e o menor valor digitado e as # suas respectivas posições na lista """ #solucao incompleta, para fzer um loop q qndo houver mais de um numero igual imprima tdas as posições lista = [] cont = 0 for numero in range(0,5): numeros =...
Python
zaydzuhri_stack_edu_python
function plot_tracks_3D trackDF polyline_df_xy polyline_df_yz output_fig_path=none plot_style=string white line_color=none fig_width=3 fig_height=3 fig_dpi=300 plot_xy_polylines=false plot_yz_polylines=false track_list=none tracks_highlight=none uniform_line_width=false elevation=45 azimuth=60 axis_off=false centering=...
def plot_tracks_3D(trackDF, polyline_df_xy, polyline_df_yz, output_fig_path=None, plot_style='white', line_color=None, fig_width=3, fig_height=3, fig_dpi=300, plot_xy_polylines=False, plot_yz_polylines=False, track_list=None, tracks_highlight=N...
Python
nomic_cornstack_python_v1
function connectionLost self reason begin pass end function
def connectionLost(self,reason): pass
Python
nomic_cornstack_python_v1
function update_hit title_url begin if call validate_json == string Bad JSON begin return call wrong_data string JSON has an error end comment get hit filtered by the title_url set query_hit = filter by query title_url=title_url comment get hit filtered by the title_url try begin set hit = get query id end except Index...
def update_hit(title_url): if validate_json() == "Bad JSON": return wrong_data("JSON has an error") # get hit filtered by the title_url query_hit = Hits.query.filter_by(title_url=title_url) # get hit filtered by the title_url try: hit = Hits.query.get(query_hit[0].id) except Inde...
Python
nomic_cornstack_python_v1
import json import nltk import collections function snippet termids termlist begin set returnstring = string for id in termids begin set returnstring = returnstring + string ... set surr_list = list if id in termlist begin set index = index termlist id for i in range index - 3 index + 3 begin if i >= 0 and i < length...
import json import nltk import collections def snippet(termids, termlist: list): returnstring = '' for id in termids: returnstring += '...' surr_list = [] if id in termlist: index = termlist.index(id) for i in range(index-3,index+3): i...
Python
zaydzuhri_stack_edu_python
function remove_vowels s begin comment pass set s_list = list s set result = list set vowels = string aiueoAIUEO for i in range length s_list begin if s_list at i not in vowels begin append result s_list at i end end set s_str = join string result return s_str end function
def remove_vowels(s: str): # pass s_list = list(s) result = [] vowels = "aiueoAIUEO" for i in range(len(s_list)): if s_list[i] not in vowels: result.append(s_list[i]) s_str = ''.join(result) return s_str
Python
nomic_cornstack_python_v1
function sravnenie *args begin set a = integer input string Введите первое число set b = integer input string Введите второе число if a > b begin return string a>b end else if a < b begin return string a<b end else if a == b begin return string a==b end end function print call sravnenie
def sravnenie(*args): a=int(input("Введите первое число ")) b=int(input("Введите второе число ")) if a>b: return "a>b" elif a<b: return "a<b" elif a==b: return "a==b" print(sravnenie())
Python
zaydzuhri_stack_edu_python
function is_uppercase_letter char begin if length char != 1 begin return false end set ascii_value = ordinal char return 65 <= ascii_value <= 90 end function
def is_uppercase_letter(char): if len(char) != 1: return False ascii_value = ord(char) return 65 <= ascii_value <= 90
Python
jtatman_500k
comment 被动产生 function demo begin 1 + 1 comment 未获取到想要的数据,或者函数没有return,默认返回None print call demo end function
#被动产生 def demo(): 1+1 print(demo()) #未获取到想要的数据,或者函数没有return,默认返回None
Python
zaydzuhri_stack_edu_python
function tempimagepath mode=string w+b suffix=string .png begin set fob = named temporary file mode=mode suffix=suffix delete=false set fname = name close fob return fname end function
def tempimagepath(mode='w+b', suffix='.png'): fob = tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, delete=False) fname = fob.name fob.close() return fname
Python
nomic_cornstack_python_v1
function dataset_download_file self dataset file_name path=none force=false quiet=true begin if string / in dataset begin call validate_dataset_string dataset set dataset_urls = split dataset string / set owner_slug = dataset_urls at 0 set dataset_slug = dataset_urls at 1 end else begin set owner_slug = call get_config...
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): if '/' in dataset: self.validate_dataset_string(datase...
Python
nomic_cornstack_python_v1
function has_tag lst tag begin if not is instance lst list begin set lst = list lst end for l in lst begin if tag == tag begin return true end end for else begin return false end end function
def has_tag(lst, tag): if not isinstance(lst, list): lst = [lst] for l in lst: if l.tag == tag: return True else: return False
Python
nomic_cornstack_python_v1
set tuple A B C = sorted list comprehension integer x for x in split strip input print A * B * C % 2
A, B, C = sorted([int(x) for x in input().strip().split()]) print(A * B * (C % 2))
Python
zaydzuhri_stack_edu_python
function get_size bytes suffix=string B begin set factor = 1024 for unit in list string string K string M string G string T string P begin if bytes < factor begin return string { bytes } { unit } { suffix } end set bytes = bytes / factor end end function
def get_size(bytes, suffix="B"): factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor
Python
nomic_cornstack_python_v1
function get_input self begin return pop input_value 0 end function
def get_input(self): return self.input_value.pop(0)
Python
nomic_cornstack_python_v1
function find_peaks data begin set peaks = list for tuple i datum in enumerate data begin if 0 < i < length data - 1 begin if data at i - 1 < datum > data at i + 1 begin append peaks i end end end return peaks end function function find_valleys data begin set valleys = list for tuple i datum in enumerate data begin i...
def find_peaks(data): peaks = [] for i, datum in enumerate(data): if 0 < i < len(data)-1: if data[i-1] < datum > data[i+1]: peaks.append(i) return peaks def find_valleys(data): valleys = [] for i, datum in enumerate(data): if 0 < i < len(data)-1: ...
Python
zaydzuhri_stack_edu_python
import numpy as np class Line begin string Diese Klasse gepräsentiert das geometrische Objekt Line mit Startpunkt (p1) und Endpunkt (p2). function __init__ self p1xy p2xy begin string Konstruktor für das Line-Objekt. :param p1xy: Startpunkt als Tuple (x, y) :param p2xy: Endpunkt als Tuple end function comment HIER KOMM...
import numpy as np class Line: """ Diese Klasse gepräsentiert das geometrische Objekt Line mit Startpunkt (p1) und Endpunkt (p2). """ def __init__(self, p1xy, p2xy): """ Konstruktor für das Line-Objekt. :param p1xy: Startpunkt als Tuple (x, y) :param p2xy: Endpunkt als ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np string # 필터링 : bool형의 시퀀스를 지정하여 True인 것만 추출하여 칠터링 수행 set data = dict string fruits list string apple string orange string banana string strawberry string kiwifruit ; string time list 1 4 5 6 3 ; string year list 2001 2002 2001 2008 2006 set df = call DataFrame data print df commen...
import pandas as pd import numpy as np ''' # 필터링 : bool형의 시퀀스를 지정하여 True인 것만 추출하여 칠터링 수행 ''' data = {'fruits':['apple','orange','banana','strawberry','kiwifruit'], 'time':[1, 4, 5, 6, 3], 'year':[2001, 2002, 2001, 2008, 2006]} df = pd.DataFrame(data) print(df) # fru...
Python
zaydzuhri_stack_edu_python
function create_similarity_over_time decades begin comment sort decades from smallest to largest (earliest to last) comment base model is the largest sort decades key=lambda tup -> tup at 0 comment remove pre 1470 and post 1700 set decades = list comprehension d for d in decades if integer d at 0 < 1710 and integer d a...
def create_similarity_over_time(decades): # sort decades from smallest to largest (earliest to last) # base model is the largest decades.sort(key=lambda tup: tup[0]) # remove pre 1470 and post 1700 decades = [d for d in decades if int(d[0]) < 1710 and int(d[0]) > 1460] ## compute alignments ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 comment -*- coding: utf-8 -*- string Created on Sat Dec 9 23:52:39 2017 @author: apple string Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold addit...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Dec 9 23:52:39 2017 @author: apple """ """ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional ele...
Python
zaydzuhri_stack_edu_python
import unittest comment 1. 继承自unittest.TestCase comment 2. case均以test开头 class Mytest extends TestCase begin comment test fixture comment 每个用例开始 function setUp self begin print string start... end function comment test case function test_001 self begin print string 001 end function comment self.assertEquals("1","1") 断言 ...
import unittest #1. 继承自unittest.TestCase #2. case均以test开头 class Mytest(unittest.TestCase): #test fixture def setUp(self): #每个用例开始 print("start...") #test case def test_001(self): print("001") # self.assertEquals("1","1") 断言 #test case def test_00...
Python
zaydzuhri_stack_edu_python
function assign_to_specs self builders begin for builder in builders begin set spec_match = call _best_matching_spec builder if spec_match is none begin add _unmatched_builders builder end else begin add spec_match builder end end end function
def assign_to_specs(self, builders): for builder in builders: spec_match = self._best_matching_spec(builder) if spec_match is None: self._unmatched_builders.add(builder) else: spec_match.add(builder)
Python
nomic_cornstack_python_v1
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button class MyW extends Widget begin set counter = 0 function on_touch_down self touch begin if button == string left begin call add_widget call Button text=string pos pos=pos id=string counter set counter = counter + 1 end else if...
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button class MyW(Widget): counter = 0 def on_touch_down(self, touch): if touch.button == 'left': self.add_widget(Button(text=str(touch.pos), pos=touch.pos, id = str(self.counter))) self.cou...
Python
zaydzuhri_stack_edu_python
function read_file filename begin string Opens and reads a file, then returns a nested list with the elements of the file. with open filename as file begin set file_list = list comprehension split lines string , for lines in call splitlines end return file_list end function function write_file filename nestedlist begin...
def read_file(filename): ''' Opens and reads a file, then returns a nested list with the elements of the file. ''' with open(filename) as file: file_list = [lines.split(',') for lines in file.read().splitlines()] return file_list def write_file(filename, nestedlist): ''' Rewrites t...
Python
zaydzuhri_stack_edu_python
function _water_balance awc pet precip begin comment flatten timeseries to a 1-D array set pet = flatten pet set precip = flatten precip set total_months = shape at 0 comment allocate arrays for the water balance values set ET = zeros tuple total_months set PR = zeros tuple total_months set R = zeros tuple total_months...
def _water_balance(awc, pet, precip): # flatten timeseries to a 1-D array pet = pet.flatten() precip = precip.flatten() total_months = pet.shape[0] # allocate arrays for the water balance values ET = np.zeros((total_months,)) PR = np.zeros((total_months,)) R = np.zeros((total_months,)...
Python
nomic_cornstack_python_v1
from typing import Iterable import logging from config_injection import get_and_cast , global_config , _log set logger = call getLogger __name__ function inject_statics_from_config section begin string Inject config options into static variables of class. If you want injection into actual instance variables, use inject...
from typing import Iterable import logging from config_injection import get_and_cast, global_config, _log logger = logging.getLogger(__name__) def inject_statics_from_config(section: str): """ Inject config options into static variables of class. If you want injection into actual instance variables, use ...
Python
zaydzuhri_stack_edu_python
comment Aadiba Haque comment 4/24/2020 comment Lab 12 Q5 function add_entry contacts name number begin if name not in contacts begin if length number == 10 begin set valid = true for num in number begin if not is digit num begin set valid = false end end if valid begin set contacts at name = number end end end end func...
#Aadiba Haque #4/24/2020 #Lab 12 Q5 def add_entry(contacts, name, number): if name not in contacts: if len(number) == 10: valid = True for num in number: if not num.isdigit(): valid = False if valid: contacts[...
Python
zaydzuhri_stack_edu_python