code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _remove_stale_models self begin comment get available upstream S3 model IDs set s3_model_names = call get_model_names set s3_model_versions = list comprehension call model_info model_name at string versions for model_name in s3_model_names set s3_model_ids = list for tuple model_name model_versions in zip s3_...
def _remove_stale_models(self) -> None: # get available upstream S3 model IDs s3_model_names = self._tree.get_model_names() s3_model_versions = [ self._tree.model_info(model_name)["versions"] for model_name in s3_model_names ] s3_model_ids = [] for model_name...
Python
nomic_cornstack_python_v1
string Data Reader This script takes in VCF, BAM, and FASTQ files and reads them to a pandas data frame. comment Importing libraries import pandas as pd import numpy as np import pysam import io from itertools import islice function read_vcf fp begin string Reads VCF file :param fp: String representing file path to VCF...
""" Data Reader This script takes in VCF, BAM, and FASTQ files and reads them to a pandas data frame. """ # Importing libraries import pandas as pd import numpy as np import pysam import io from itertools import islice def read_vcf(fp): """ Reads VCF file :param fp: String representing file path ...
Python
zaydzuhri_stack_edu_python
async function view_audit_actions self ctx begin comment handle by `cog_check` assert guild is not none if logging_info := await call typed_retrieve_query database int string SELECT BITS FROM LOGGING WHERE GUILD_ID=? tuple id begin await call send embed=call build_actions_embed call all_enabled_actions logging_info at ...
async def view_audit_actions(self, ctx: Context) -> None: assert ctx.guild is not None # handle by `cog_check` if logging_info := (await typed_retrieve_query( self.bot.database, int, 'SELECT BITS FROM LOGGING WHERE GUILD_ID=?', (ctx.guil...
Python
nomic_cornstack_python_v1
function _test_simple_mission self instr_keys mission_filename in_command_state max_wait=none begin call _set_receive_timeout if in_command_state begin set base_state = COMMAND set mission_state = MISSION_COMMAND end else begin set base_state = MONITORING set mission_state = MISSION_STREAMING end comment start everythi...
def _test_simple_mission(self, instr_keys, mission_filename, in_command_state, max_wait=None): self._set_receive_timeout() if in_command_state: base_state = PlatformAgentState.COMMAND mission_state = PlatformAgentState.MISSION_COMMAND else: base_state =...
Python
nomic_cornstack_python_v1
function _print_fields print_list begin set max_field_name_length = 0 for pair in print_list begin if max_field_name_length < length pair at 0 begin set max_field_name_length = length pair at 0 end end for pair in print_list begin print string %*s = %s % tuple max_field_name_length pair at 0 pair at 1 end end function
def _print_fields(print_list): max_field_name_length = 0 for pair in print_list: if max_field_name_length < len(pair[0]): max_field_name_length = len(pair[0]) for pair in print_list: print (" %*s = %s" % (max_field_name_length, pair[0], pair[1]))
Python
nomic_cornstack_python_v1
function get_playbook_args_tags _node _instance playbook_path begin if AVAILABLE_TAGS not in runtime_properties begin set tags = get properties string tags list if tags begin set runtime_properties at AVAILABLE_TAGS = tags end else if get properties string auto_tags false begin set tuple _ tags = call get_available_ste...
def get_playbook_args_tags(_node, _instance, playbook_path): if AVAILABLE_TAGS not in _instance.runtime_properties: tags = _node.properties.get('tags', []) if tags: _instance.runtime_properties[AVAILABLE_TAGS] = tags elif _node.properties.get('auto_tags', False): _, ...
Python
nomic_cornstack_python_v1
function contains self key begin return exists buckets at call _hash key key end function
def contains(self, key: int) -> bool: return self.buckets[self._hash(key)].exists(key)
Python
nomic_cornstack_python_v1
for score in score_list begin if score == string A begin set score_sum = score_sum + 4 end else if score == string B begin set score_sum = score_sum + 3 end else if score == string C begin set score_sum = score_sum + 2 end else if score == string D begin set score_sum = score_sum + 1 end end print score_sum / n
for score in score_list : if (score == "A") : score_sum += 4 elif (score == "B") : score_sum += 3 elif (score == "C") : score_sum += 2 elif (score == "D") : score_sum += 1 print(score_sum / n)
Python
zaydzuhri_stack_edu_python
function hysteresis_threshold_voltages r1 r2 rh vcc begin return call __hysteresis_threshold_voltages r1 r2 rh vcc hysteresis_threshold_ratios end function
def hysteresis_threshold_voltages(r1, r2, rh, vcc): return __hysteresis_threshold_voltages( r1, r2, rh, vcc, hysteresis_threshold_ratios)
Python
nomic_cornstack_python_v1
comment from random import randint comment with open('random_numbers.txt', 'w') as fil: comment num = int(input('Enter the number of random numbers to be written to the file: ')) comment for i in range(num): comment fil.write(f'{randint(1, 501)}\n') comment fil.close() set mystr = string yes set mystr = mystr + string ...
# from random import randint # with open('random_numbers.txt', 'w') as fil: # num = int(input('Enter the number of random numbers to be written to the file: ')) # for i in range(num): # fil.write(f'{randint(1, 501)}\n') # fil.close() mystr = 'yes' mystr += 'no' mystr += 'yes' print(mystr...
Python
zaydzuhri_stack_edu_python
try begin set s = decimal score end except any begin set s = - 1 end if s < 0.6 begin print string F end else if s >= 0.6 and s < 0.7 begin print string D end else if s >= 0.7 and s < 0.8 begin print string C end else if s >= 0.8 and s < 0.9 begin print string B end else if s >= 0.9 and s <= 1.0 begin print string A en...
try: s=float(score) except: s=-1 if s < 0.6: print("F") elif s >= 0.6 and s < 0.7: print("D") elif s >= 0.7 and s < 0.8: print("C") elif s >= 0.8 and s < 0.9: print("B") elif s >= 0.9 and s <= 1.0: print("A") else: print("Invalid Entry")
Python
zaydzuhri_stack_edu_python
function kebab_case_file_path original_path begin return replace replace lower original_path string string - string _ string end function
def kebab_case_file_path(original_path): return original_path.lower().replace(' ', '-').replace('_', '')
Python
nomic_cornstack_python_v1
string Python实现MD4 import struct import binascii class md4 extends object begin string 创建md4类 set A = 1732584193 set B = 4023102345 set C = 2562383102 set D = 271733878 set H = list set X = list set M = list set org = list set _lrot = lambda self x n -> x ? n ? x ? 32 - n set _F = lambda self x y z -> x ? y ? ? x ?...
"""Python实现MD4""" import struct import binascii class md4(object): """创建md4类""" A = 0x67452301 B = 0xefcbab89 C = 0x98badcfe D = 0x10325476 H = [] X = [] M = [] org = [] _lrot = lambda self, x, n: (x << n) | (x >> (32 - n)) _F = lambda self, x, y, z: ((x & y) | (~x & z)) ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd function validated_codes data pu_state_filter regional_granularity con begin string This function takes in the ranking data from each regional granularity and checks the zip, city or county codes against the codes that currently exist in LCAD. The data file is returned with a new ...
import numpy as np import pandas as pd def validated_codes(data, pu_state_filter, regional_granularity, con): ''' This function takes in the ranking data from each regional granularity and checks the zip, city or county codes against the codes that currently exist in LCAD. The data file is returned wi...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment # CS579: Project comment In this project, we will fit a text classifier to categorize product(iPhone) reviews by sentiment. comment In[2]: from collections import Counter from collections import defaultdict import glob import math import operator import hashlib import io import math import...
# coding: utf-8 # # CS579: Project # # In this project, we will fit a text classifier to categorize product(iPhone) reviews by sentiment. # In[2]: from collections import Counter from collections import defaultdict import glob import math import operator import hashlib import io import math import matplotlib.pyplot...
Python
zaydzuhri_stack_edu_python
function get_images_similar_to_image img_name indices distances k form=string df begin comment get_key(img_map, img_name) set index = call index_from_image_name img_name set distances = distances at index at slice 1 : k + 1 : set images = list comprehension string x for x in indices at index at slice 1 : k + 1 : if f...
def get_images_similar_to_image(img_name, indices, distances, k, form="df"): index = index_from_image_name(img_name)#get_key(img_map, img_name) distances = distances[index][1:k + 1] images = [str(x) for x in indices[index]][1:k + 1] if form == "df": return pd.DataFrame({"img": images, "dist": d...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment IAMarrakech.py comment Copyright Florent Madelaine, (1/12/2017) comment Ce logiciel est un programme informatique servant à jouer à Marrakech, comment un jeu de plateau de Dominique Ehrhard distribué et édité par Gigamic, comment dans le but de pouvoir...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # IAMarrakech.py # Copyright Florent Madelaine, (1/12/2017) # Ce logiciel est un programme informatique servant à jouer à Marrakech, # un jeu de plateau de Dominique Ehrhard distribué et édité par Gigamic, # dans le but de pouvoir mettre en oeuvre et tester des intelli...
Python
zaydzuhri_stack_edu_python
import math import sympy as sp call init_printing function newton f df x0 eps max_iter begin set x = x0 for n in range max_iter begin set fx = f dist x if absolute fx < eps begin print string Found solution after n string iterations. return x end set dfx = call df x if dfx == 0 begin print string Zero derivative. No so...
import math import sympy as sp sp.init_printing() def newton(f, df, x0, eps, max_iter): x = x0 for n in range(max_iter): fx = f(x) if abs(fx) < eps: print('Found solution after', n, 'iterations.') return x dfx = df(x) if dfx == 0: print('Zer...
Python
zaydzuhri_stack_edu_python
function pageList self request formatter info=0 numbered=1 paging=true hitsFrom=0 hitsInfo=0 highlight_titles=true highlight_pages=true begin call _reset request formatter set f = formatter set write = write if numbered begin set lst = lambda on -> call number_list on start=hitsFrom + 1 end else begin set lst = bullet_...
def pageList(self, request, formatter, info=0, numbered=1, paging=True, hitsFrom=0, hitsInfo=0, highlight_titles=True, highlight_pages=True): self._reset(request, formatter) f = formatter write = self.buffer.write if numbered: lst = lambda on: f.number...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys if __name__ == string __main__ begin set arr = list for _ in range 6 begin append arr list map int split right strip input end set max_sum = arr at 1 at 1 + sum arr at 0 at slice 0 : 3 : + sum arr at 2 at slice 0 : 3 : for i in range 1 5 be...
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) max_sum = arr[1][1]+ sum(arr[0][0:3]) + sum(arr[2][0:3]) for i in range(1, 5): for j in range(1,5...
Python
zaydzuhri_stack_edu_python
function test_real self begin set result = call ClustalParser real comment make sure we got three sequences assert equal length result 3 assert equal result dict string abc string GCAUGCAUGCAUGAUCGUACGUCAGCAUGCUAGACUGCAUACGUACGUACGCAUGCAUCA + string GUCGAUACGUACGUCAGUCAGUACGUCAGCAUGCAUACGUACGUCGUACGUACGU-CGAC + string ...
def test_real(self): result = ClustalParser(real) self.assertEqual(len(result), 3) #make sure we got three sequences self.assertEqual(result, { 'abc': \ 'GCAUGCAUGCAUGAUCGUACGUCAGCAUGCUAGACUGCAUACGUACGUACGCAUGCAUCA' + \ 'GUCGAUACGUACGUCAGUCAGUACGUCAGCAUGCAUACG...
Python
nomic_cornstack_python_v1
function is_prime number begin string This function should return true if the number is prime and false otherwise. if number <= 1 begin return false end for i in range 2 integer number ^ 0.5 + 1 begin if number % i == 0 begin return false end end return true end function
def is_prime(number): '''This function should return true if the number is prime and false otherwise.''' if number <= 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True
Python
jtatman_500k
function get_column self column_name begin call check_for_column column_name return drop missing data at column_name end function
def get_column(self, column_name): self.check_for_column(column_name) return self.data[column_name].dropna()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import requests import hashlib from multiprocessing.pool import ThreadPool from multiprocessing import Queue , Process import numpy as np import bs4 import sys set adress = string http://localhost:4444/ set res = post adress + string login dict string uname string foo ; string password str...
# -*- coding: utf-8 -*- import requests import hashlib from multiprocessing.pool import ThreadPool from multiprocessing import Queue, Process import numpy as np import bs4 import sys adress = "http://localhost:4444/" res = requests.post(adress + "login", {"uname": "foo", "password": "bar"}, allow_redirects=False) de...
Python
zaydzuhri_stack_edu_python
function send_update_info self begin call write_message dict string type string update ; string data dict string pit_temp call get_temp ; string food_temp list comprehension call get_temp for probe in settings at string probes at string food ; string setpoint call get_setpoint ; string food_alarms settings at string fo...
def send_update_info(self): self.write_message({ 'type': 'update', 'data': { 'pit_temp': self.application.settings['probes']['pit'].get_temp(), 'food_temp': [probe.get_temp() for probe in self.application.settings['probes']['food']], 'setpo...
Python
nomic_cornstack_python_v1
import os import pandas as pd from src.databases.sources import paths class DBs extends object begin string DBs class ensures that each database is loaded maximum once, and keeps a reference to that instance. set _loaded_dbs = dict function load self path begin comment if database file doesn't exist if not exists path...
import os import pandas as pd from src.databases.sources import paths class DBs(object): """ DBs class ensures that each database is loaded maximum once, and keeps a reference to that instance. """ _loaded_dbs = {} def load(self, path): # if database file doesn't exist if not os.p...
Python
zaydzuhri_stack_edu_python
import numpy as np from db.controller.status_controller import StatusController from db.controller.scan_controller import ScanController from db.controller.rectangle_controller import RectangleController from util.senser_util import receive , irradiate class Senser begin function __init__ self status_controller scan_co...
import numpy as np from db.controller.status_controller import StatusController from db.controller.scan_controller import ScanController from db.controller.rectangle_controller import RectangleController from .util.senser_util import receive, irradiate class Senser: def __init__( self, status_co...
Python
zaydzuhri_stack_edu_python
function camel_case_to_name name begin string Used to convert a classname to a lowercase name function convert_func val begin return string _ + lower call group 0 end function return lower name at 0 + sub string ([A-Z]) convert_func name at slice 1 : : end function
def camel_case_to_name(name): """ Used to convert a classname to a lowercase name """ def convert_func(val): return "_" + val.group(0).lower() return name[0].lower() + re.sub(r'([A-Z])', convert_func, name[1:])
Python
jtatman_500k
comment longest paalindrome subsequence function findLPS s startIndex endIndex begin if startIndex > endIndex begin return 0 end else if startIndex == endIndex begin return 1 end else if s at startIndex == s at endIndex begin return 2 + call findLPS s startIndex + 1 endIndex - 1 end else begin set op1 = call findLPS s ...
# longest paalindrome subsequence def findLPS(s, startIndex, endIndex): if startIndex > endIndex: return 0 elif startIndex == endIndex: return 1 elif s[startIndex] == s[endIndex]: return 2 + findLPS(s, startIndex+1, endIndex-1) else: op1 = findLPS(s, startIndex, endIndex...
Python
zaydzuhri_stack_edu_python
string By Farrokh ... General usage functions ... import datetime , shutil function DATETIME_GetNowStr begin return string format time now string %Y-%m-%d_%H:%M:%S end function function OS_IsDirectory FolderAddress begin return is directory path FolderAddress end function function FILE_CheckFileExists fname begin retur...
""" By Farrokh ... General usage functions ... """ import datetime , shutil; def DATETIME_GetNowStr(): return datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") ; def OS_IsDirectory (FolderAddress): return shutil.os.path.isdir (FolderAddress) def FILE_CheckFileExists (fname): return shutil.os.path...
Python
zaydzuhri_stack_edu_python
function _get_index self orb sz=none begin if orb >= n_orbitals begin raise call IndexError string requested orbital index outside of the hilbert space end set spin_idx = call _spin_index sz return spin_idx * n_orbitals + orb end function
def _get_index(self, orb: int, sz: float = None): if orb >= self.n_orbitals: raise IndexError("requested orbital index outside of the hilbert space") spin_idx = self._spin_index(sz) return spin_idx * self.n_orbitals + orb
Python
nomic_cornstack_python_v1
function getFeatures self gameState action begin set features = counter set features at string successorScore = call getScore gameState return features end function
def getFeatures(self, gameState, action): features = util.Counter() features['successorScore'] = self.getScore(gameState) return features
Python
nomic_cornstack_python_v1
function solve_2x2 self begin assert call get_number 1 1 == 0 msg string zero tile should be at row 1, col 1 assert call row1_invariant 1 msg string tiles to right and below incorrectly ordered comment Moves the zero tile to (0,0). call update_puzzle string lu comment Repositions the upper left 2x2 part up to 3 times, ...
def solve_2x2(self): assert self.get_number(1,1) == 0, "zero tile should be at row 1, col 1" assert self.row1_invariant(1), "tiles to right and below incorrectly ordered" # Moves the zero tile to (0,0). self.update_puzzle("lu") # Repositions the upper left 2x2 ...
Python
nomic_cornstack_python_v1
function testWord passPhrase begin set micToCompare = call generateMic passPhrase end function
def testWord(passPhrase): micToCompare = generateMic(passPhrase)
Python
nomic_cornstack_python_v1
string Construct a program in Python that finds the nth prime number comment A function used to calculate whether a given number is prime function is_prime n begin comment Corner cases if n <= 1 begin return false end if n <= 3 begin return true end comment This is checked so that we can skip comment middle five number...
""" Construct a program in Python that finds the nth prime number """ # A function used to calculate whether a given number is prime def is_prime(n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in b...
Python
jtatman_500k
for i in range length y begin set z = ordinal phrase at i if z + x <= 90 begin set phrase at i = character z + x end else begin set sum = x + z while sum > 90 begin set sum = sum - 26 end set phrase at i = character sum end print phrase at i end=string end print string set ans = input string Do you want to do decryptio...
for i in range(len(y)): z = ord(phrase[i]) if z + x <= 90: phrase[i] = chr(z + x) else: sum = x + z while sum > 90: sum = sum -26 phrase[i] = chr(sum) print(phrase[i],end='') print('\n') ans = input("Do you want to do decryption again ? ") if ans == 'y': ...
Python
zaydzuhri_stack_edu_python
string 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. from sys import argv set tuple ...
""" 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. """ from sys import argv script_n...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import re comment BeautifulSoup comment https://cuiqingcai.com/1319.html set html = string <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and t...
from bs4 import BeautifulSoup import re # BeautifulSoup # https://cuiqingcai.com/1319.html html=''' <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a h...
Python
zaydzuhri_stack_edu_python
comment Recursive helper function _build_without_gui self level i begin comment center = 7i+1 comment north = 7i+2 comment south = 7i+3 comment northaast = 7i+4 comment southeast = 7i+5 comment northwest = 7i+6 comment southwest = 7i+7 if level > 0 begin comment center comment 0 signifies no canvas id set nodes at 7 * ...
def _build_without_gui(self, level,i): # Recursive helper #center = 7i+1 #north = 7i+2 #south = 7i+3 #northaast = 7i+4 #southeast = 7i+5 #northwest = 7i+6 #southwest = 7i+7 if level > 0: #center self.nodes[7*i+1] = Routers.IPRouter(7*i+1, 0, self.gui_boolean) # 0 signifies no canvas id ...
Python
nomic_cornstack_python_v1
function _find_udm_objects self module_s filter_s base begin comment type: (str, str, str) -> List[Any] set module = call _get_module module_s comment TODO: check if the first parameter is needed (Config, from univention.admin.config) return call lookup none lo filter_s=filter_s base=base end function
def _find_udm_objects(self, module_s, filter_s, base): # type: (str, str, str) -> List[Any] module = self._get_module(module_s) # TODO: check if the first parameter is needed (Config, from univention.admin.config) return module.lookup(None, self.lo, filter_s=filter_s, base=base)
Python
nomic_cornstack_python_v1
import webapp2 from google.appengine.ext import ndb import logging import yaml import datetime comment Node transitions class Transition extends object begin function __init__ self to_node begin assert is instance to_node basestring msg string to_node should be a string, was %s % type to_node set to_node = to_node end ...
import webapp2 from google.appengine.ext import ndb import logging import yaml import datetime # Node transitions class Transition(object): def __init__(self, to_node): assert isinstance(to_node, basestring), "to_node should be a string, was %s" % type(to_node) self.to_node = to_node def execu...
Python
zaydzuhri_stack_edu_python
function execute_sql self query begin return execute call SqlExecute spark logger query end function
def execute_sql(self, query): return SqlExecute(self.spark, self.logger) \ .execute(query)
Python
nomic_cornstack_python_v1
import numpy as np from math import sqrt import warnings import matplotlib.pyplot as plt from matplotlib import style from collections import Counter call use string fivethirtyeight set dataset = dict string k list list 1 2 list 2 3 list 3 1 ; string r list list 6 5 list 7 7 list 8 6 set new_features = list 5 7 comment...
import numpy as np from math import sqrt import warnings import matplotlib.pyplot as plt from matplotlib import style from collections import Counter style.use('fivethirtyeight') dataset = {'k':[[1,2],[2,3],[3,1]],'r':[[6,5],[7,7],[8,6]]} new_features = [5,7] # for i in dataset: # for ii in dataset[i]: # plt.scat...
Python
zaydzuhri_stack_edu_python
function _run self full_params begin print string Executing: %s % tuple join string full_params set process = popen full_params stdout=PIPE return communicate process end function
def _run(self, full_params): print("Executing: %s" % (' '.join(full_params),)) process = Popen(full_params, stdout=PIPE) return process.communicate()
Python
nomic_cornstack_python_v1
import pytest from pytest_demo.utils import booleanify , make_hashable set booleanify_test_data = list tuple string false false tuple false true tuple string FaLse false tuple string 0 false tuple string true true tuple string tRuE true tuple string 1 true tuple string cat true tuple true true set booleanify_ids = list...
import pytest from pytest_demo.utils import booleanify, make_hashable booleanify_test_data = [ ('false', False), (False, True), ('FaLse', False), ('0', False), ('true', True), ('tRuE', True), ('1', True), ('cat', True), (True, True), ] booleanify_ids = [ 'false_string', '...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Dec 16 09:36:40 2019 @author: jsyi import pandas as pd import matplotlib.pyplot as plt import nltk from nltk.corpus import stopwords from collections import Counter import networkx as nx import re from nltk.tokenize import RegexpTokenizer set filename = string data/ka...
# -*- coding: utf-8 -*- """ Created on Mon Dec 16 09:36:40 2019 @author: jsyi """ import pandas as pd import matplotlib.pyplot as plt import nltk from nltk.corpus import stopwords from collections import Counter import networkx as nx import re from nltk.tokenize import RegexpTokenizer filename="data/kalsec-2019.tx...
Python
zaydzuhri_stack_edu_python
string 计算圆的基础面积 comment 半径 r set r = 2 comment 圆周率 pi set pi = 3.14 comment 圆的面积 area set area = pi * r ^ 2 set area = r * r * 3.14 print string area的面积是: print area
""" 计算圆的基础面积 """ # 半径 r r = 2 # 圆周率 pi pi = 3.14 # 圆的面积 area area = pi * r ** 2 area = r*r*3.14 print('area的面积是:') print(area)
Python
zaydzuhri_stack_edu_python
function with_color_stripped f begin decorator wraps f function colored_len s begin set s2 = sub COLOR_BEGIN_RGX + string (.*?) + COLOR_END_RGX lambda m -> sub COLOR_BEGIN_RGX string call group 1 s if search COLOR_BEGIN_RGX s2 begin raise call UnterminatedColorError s end return f dist sub COLOR_END_RGX string s2 end...
def with_color_stripped(f: Callable[[str], T]) -> Callable[[str], T]: @wraps(f) def colored_len(s: str) -> T: s2 = re.sub( COLOR_BEGIN_RGX + "(.*?)" + COLOR_END_RGX, lambda m: re.sub(COLOR_BEGIN_RGX, "", m.group(1)), s, ) if re.search(COLOR_BEGIN_RGX,...
Python
nomic_cornstack_python_v1
comment ============================================================================= from PIL import Image import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import task2_batch import task3_net import os import pandas as pd comment ===============================================================...
# ============================================================================= from PIL import Image import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import task2_batch import task3_net import os import pandas as pd # ======================================================================= # 获...
Python
zaydzuhri_stack_edu_python
import numpy as np from multiprocessing import Process , Pipe from multiprocessing import Value import RPi.GPIO as GPIO import time import cv2 set HIGH = true set LOW = false comment setup GPIO pins comment set GPIO numbering mode call setmode BCM call setwarnings false set IR_RIGHT_PIN = 27 set IR_LEFT_PIN = 22 set IR...
import numpy as np from multiprocessing import Process, Pipe from multiprocessing import Value import RPi.GPIO as GPIO import time import cv2 HIGH = True LOW = False # setup GPIO pins GPIO.setmode(GPIO.BCM) # set GPIO numbering mode GPIO.setwarnings(False) IR_RIGHT_PIN = 27 IR_LEFT_PIN = 22 IR_LINE_RIGHT_PIN = 19 I...
Python
zaydzuhri_stack_edu_python
function define_project_advancement project_id begin comment Gather information set deliverables = filter project=project_id set project = get objects id=project_id comment Gather all deliverable status set deliverables_status = list for deliverable in deliverables begin append deliverables_status status end comment I...
def define_project_advancement(project_id): # Gather information deliverables = Deliverable.objects.filter(project=project_id) project = Project.objects.get(id=project_id) # Gather all deliverable status deliverables_status = [] for deliverable in deliverables: deliverables_status.appen...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Apr 21 13:30:49 2021 @author: Avinash comment WordCloud comment pip install WordCloud from wordcloud import WordCloud , STOPWORDS import matplotlib.pyplot as plt with open string C:\Users\Avinash\Documents\iphone_11.txt string r as ip begin set iphone = read ip end se...
# -*- coding: utf-8 -*- """ Created on Wed Apr 21 13:30:49 2021 @author: Avinash """ # WordCloud # pip install WordCloud from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt with open("C:\\Users\\Avinash\\Documents\\iphone_11.txt","r") as ip: iphone = ip.read() other_stopwo...
Python
zaydzuhri_stack_edu_python
function process_multiple_files self filepaths email_col=string EMAIL min_size=100 threshold=0.05 begin set new_paths = list for f in filepaths begin set df = read csv f set df = call pre_process_frame df col=email_col set orig_size = size set FLAG = true if orig_size < min_size begin pass end else begin print format ...
def process_multiple_files(self, filepaths, email_col='EMAIL',min_size=100, threshold=0.05): new_paths = [] for f in filepaths: df = pd.read_csv(f) df = self.pre_process_frame(df, col=email_col) orig_size = df.index.size FLAG = True if o...
Python
nomic_cornstack_python_v1
function getFriendsStatus self id=none user_id=none screen_name=none page=string 1 begin if authenticated is true begin set apiURL = string if id is not none begin set apiURL = string http://twitter.com/statuses/friends/%s.json % id end end end function
def getFriendsStatus(self, id = None, user_id = None, screen_name = None, page = "1"): if self.authenticated is True: apiURL = "" if id is not None: apiURL = "http://twitter.com/statuses/friends/%s.json" % id
Python
nomic_cornstack_python_v1
from tkinter import * import pymysql import hotel_base set db = call connect string localhost string root string cs631 string hrs function viewhotels begin set root = call Tk set text = call Text root set hotel_data = call hotel_database db for row in hotel_data begin set line = join string list comprehension string i...
from tkinter import * import pymysql import hotel_base db = pymysql.connect("localhost","root","cs631","hrs") def viewhotels(): root = Tk() text = Text(root) hotel_data=hotel_base.hotel_database(db) for row in hotel_data: line=' '.join([str(i) for i in row])+'\n' ...
Python
zaydzuhri_stack_edu_python
import time class Profiler begin function __init__ self begin set start_time = time set end_time = time end function function start_tracking self begin set start_time = time end function function end_tracking self begin set end_time = time end function function get_time_delta_message self begin return string Consumed: ...
import time class Profiler: def __init__(self): self.start_time = time.time() self.end_time = time.time() def start_tracking(self): self.start_time = time.time() def end_tracking(self): self.end_time = time.time() def get_time_delta_message(self): return 'Con...
Python
zaydzuhri_stack_edu_python
import csv from keras.callbacks import ModelCheckpoint from keras.engine.saving import load_model import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import precision_score , accuracy_score , recall_score , f1_score , classification_report import seaborn as sn from sklearn import...
import csv from keras.callbacks import ModelCheckpoint from keras.engine.saving import load_model import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import precision_score, accuracy_score, recall_score, f1_score, classification_report import seaborn as sn from sklearn import me...
Python
zaydzuhri_stack_edu_python
class ScoreOutOfRangeError extends Exception begin pass end class function print_score score begin try begin if score < 0 or score > 100 begin raise call ScoreOutOfRangeError string Score is out of range end set name = string John Doe print string The score is { score } print string Name: { name } end except ZeroDivisi...
class ScoreOutOfRangeError(Exception): pass def print_score(score): try: if score < 0 or score > 100: raise ScoreOutOfRangeError("Score is out of range") name = "John Doe" print(f'The score is {score}') print(f'Name: {name}') except ZeroDivisionError as zde: ...
Python
jtatman_500k
function remove_bucket_from_config_file args begin set sanitised_group = replace group string / string - set expected_path = format string /etc/ugr/conf.d/{}.conf sanitised_group if not exists path expected_path begin return 1 end set remaining_config = false with open expected_path string r as f begin set lines = read...
def remove_bucket_from_config_file(args): sanitised_group = args.group.replace('/', '-') expected_path = "/etc/ugr/conf.d/{}.conf".format(sanitised_group) if not os.path.exists(expected_path): return 1 remaining_config = False with open(expected_path, "r") as f: lines = f.readline...
Python
nomic_cornstack_python_v1
function log self _object_type _key_object _change_op _payload begin call run_query string select log.log_change( {version}, {username}, {object_type}, {key_object}, {change_op}, {payload} ); version=version username=username object_type=_object_type key_object=_key_object change_op=_change_op payload=_payload end func...
def log(self, _object_type, _key_object, _change_op, _payload): self.run_query( "select log.log_change( {version}, {username}, {object_type}, {key_object}, {change_op}, {payload} );", version=self.version, username=self.username, object_type=_object_type, key_object=_key_obje...
Python
nomic_cornstack_python_v1
function checkpoint request tmp_path begin set checkpoint_fs_type = param set checkpoint_path = tmp_path / string ckpt_dir make directory checkpoint_path exist_ok=true call write_text string dummy if checkpoint_fs_type == string local begin yield call from_directory string checkpoint_path end else if checkpoint_fs_type...
def checkpoint(request, tmp_path): checkpoint_fs_type = request.param checkpoint_path = tmp_path / "ckpt_dir" checkpoint_path.mkdir(exist_ok=True) (checkpoint_path / _CHECKPOINT_CONTENT_FILE).write_text("dummy") if checkpoint_fs_type == "local": yield Checkpoint.from_directory(str(checkpoi...
Python
nomic_cornstack_python_v1
function spectrum self photon_energy begin set outspecene = call _validate_ene photon_energy from scipy.special import cbrt function Gtilde x begin string AKP10 Eq. D7 Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.) set gt1 = 1.808 * call cbrt x / square root 1 + 3.4 * call cbrt x ^ 2.0 set gt2 = 1 + 2.21 *...
def spectrum(self, photon_energy): outspecene = _validate_ene(photon_energy) from scipy.special import cbrt def Gtilde(x): """ AKP10 Eq. D7 Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.) """ gt1 = 1.808 * cbrt(x) / np.s...
Python
nomic_cornstack_python_v1
function k_cross_validate k data classify_ftn classes begin comment number of samples set n = call shape data at 0 comment array of indices set idx = range n comment randomize indices shuffle idx comment partition the shuffled data into k units set d = split data at idx k comment iterate through each partition and dete...
def k_cross_validate(k, data, classify_ftn, classes): n = shape(data)[0] # number of samples idx = range(n) # array of indices shuffle(idx) # randomize indices d = split(data[idx], k) # partition the shuffled data into k units # iterate through each partition...
Python
nomic_cornstack_python_v1
function dep_attention_RNN encoder_inputs encoder_extra_inputs decoder_inputs cell num_encoder_symbols num_decoder_symbols word_embedding_size batch_size task sequence_length=none loop_function=none bidirectional_rnn=false context_win_size=1 train_embeddings=true dtype=float32 begin assert length encoder_inputs == leng...
def dep_attention_RNN(encoder_inputs, encoder_extra_inputs, decoder_inputs, cell, num_encoder_symbols, num_decoder_symbols, word_embedding_size, batch_size, ...
Python
nomic_cornstack_python_v1
function convert input type begin string Converts input value to request type :param input: input value :param type: type to cast :return: converted value try begin if not input begin if type == TYPE_STRING begin return string end else begin return none end end if type == TYPE_STRING begin if is instance input date be...
def convert(input, type): """ Converts input value to request type :param input: input value :param type: type to cast :return: converted value """ try: if not input: if type == Types.TYPE_STRING: return '' ...
Python
jtatman_500k
function walk_storage_from_command command filesystem begin return walk storage_folder filesystem branch leaf end function
def walk_storage_from_command(command: instances.FilesRelatedCommand, filesystem: Filesystem ) -> Iterator[Tuple[str, str, str]]: return walk(command.storage_folder, filesystem, command.branch, command.leaf)
Python
nomic_cornstack_python_v1
comment import random library import random comment All of the fortune tellers response set response = list string Working on something will focus your thoughts. string Look on google, there the answer will lie. string Ask someone you know. string Let your mind wander. string New hobbies will occupy your time. string N...
# import random library import random # All of the fortune tellers response response = ['Working on something will focus your thoughts.', 'Look on google, there the answer will lie.', 'Ask someone you know.', 'Let your mind wander.', 'New hobbies will occupy your time.', ...
Python
zaydzuhri_stack_edu_python
import xlrd import os from public.globalpath import readdata_path from public.log import Log set log = log string ReadData class ReadData begin function __init__ self begin pass end function comment 从excel读取测试数据,返回列表 function read_excel self filename sheet_name begin set list = list set path = readdata_path + filename...
import xlrd import os from public.globalpath import readdata_path from public.log import Log log = Log("ReadData") class ReadData: def __init__(self): pass # 从excel读取测试数据,返回列表 def read_excel(self,filename,sheet_name): list = [] path = readdata_path + filename + ".xls" try:...
Python
zaydzuhri_stack_edu_python
comment Time : O(N); Space: O(1) comment @tag : Arrays comment @by : Shaikat Majumdar comment @date: Aug 27, 2020 comment ************************************************************************** comment 179. Largest Number comment Given a list of non negative integers, arrange them such that they form the largest num...
# # Time : O(N); Space: O(1) # @tag : Arrays # @by : Shaikat Majumdar # @date: Aug 27, 2020 # ************************************************************************** # 179. Largest Number # # Given a list of non negative integers, arrange them such that they form the largest number. # # Example 1: # # Input: [10,2]...
Python
zaydzuhri_stack_edu_python
from pip._vendor.distlib.compat import raw_input comment string print string please enter two numbers below: set a = call raw_input set b = call raw_input set c = a + b print string total c comment int print string please enter two numbers below: set a = integer call raw_input set b = integer call raw_input set c = a +...
from pip._vendor.distlib.compat import raw_input #string print('please enter two numbers below:') a = raw_input() b = raw_input() c = a + b print('total', c) #int print('\nplease enter two numbers below:') a = int(raw_input()) b = int(raw_input()) c = (a + b) print (c)
Python
zaydzuhri_stack_edu_python
function display_word word guesses begin comment start with a variable with nothing in it. this will be new each time. comment go through each letters in word comment if letter is in guesses: .append the letter comment if letter is not in guesses: add the letter as '_' comment add letter/'_' of the word in sequence wit...
def display_word(word, guesses): # start with a variable with nothing in it. this will be new each time. # go through each letters in word # if letter is in guesses: .append the letter # if letter is not in guesses: add the letter as '_' # add letter/'_' of the word in sequence with a space # r...
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup from urllib import request import urllib.parse import urllib.error from urllib.request import urlopen from urllib.error import HTTPError as e function make_soup url begin set html = read url open url return call BeautifulSoup html string html.parser end function function get_images url beg...
from bs4 import BeautifulSoup from urllib import request import urllib.parse import urllib.error from urllib.request import urlopen from urllib.error import HTTPError as e def make_soup(url): html = urlopen(url).read() return BeautifulSoup(html, "html.parser") def get_images(url): soup = make_soup...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import sqlite3 as lite import sys set f = open string ../raw_data/w2_.txt string r set con = call connect string hashtags.db with con and f begin set cur = call cursor end
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import sys f = open ('../raw_data/w2_.txt','r') con = lite.connect('hashtags.db') with con and f: cur = con.cursor()
Python
zaydzuhri_stack_edu_python
function principle self begin call message bg=string navy fg=string ivory width=400 font=string Helvetica 10 bold text=string The pieces in this game each have one white and one black side. When you click on a piece, all 8 adjacent pieces turn over. The game consists of trying to turn them all over. If the exercise is ...
def principle(self): self.main_window.message( bg="navy", fg="ivory", width=400, font="Helvetica 10 bold", text="The pieces in this game each have one white and one black" " side. When you click on a piece, all 8 adjacent pieces turn" " over.\nThe game c...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Wed Jun 13 10:54:17 2018 @author: philip comment 구매생명주기 v2.0 ########## comment 모듈 로드 import pandas as pd comment import numpy as np comment 1. csv 파일 로드 및 전처리 comment : 구매상품TR을 제휴사별로 나눈 csv 파일(finalA_c, finalB_c, finalC_c, finalD_c) comment ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 13 10:54:17 2018 @author: philip """ #################################### ########## 구매생명주기 v2.0 ########## #################################### ### 모듈 로드 import pandas as pd #import numpy as np ### 1. csv 파일 로드 및 전처리 ### : 구매상품TR을 제휴사별로 나눈 ...
Python
zaydzuhri_stack_edu_python
function test_repr self cosmo_cls cosmo begin call test_repr self cosmo_cls cosmo comment test eliminated Ode0 from parameters assert string Ode0 not in call repr cosmo end function
def test_repr(self, cosmo_cls, cosmo): FLRWSubclassTest.test_repr(self, cosmo_cls, cosmo) # test eliminated Ode0 from parameters assert "Ode0" not in repr(cosmo)
Python
nomic_cornstack_python_v1
function __enter__ self begin set tid = call threadID if tid != tid begin set conn = call openDB set tid = tid end open return self end function
def __enter__(self): tid = threadID() if self.tid != tid: self.conn = self.database.openDB() self.tid = tid self.open() return self
Python
nomic_cornstack_python_v1
function annotations self begin return get pulumi self string annotations end function
def annotations(self) -> Optional[Sequence[Any]]: return pulumi.get(self, "annotations")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from array import array import pytest decorator fixture function SimpleClass CrossinterpreterBaseClass begin class SimpleClass extends CrossinterpreterBaseClass begin pass end class return SimpleClass end function function test_interpreter_dependent_instanciation CrossinterpreterBaseClass ...
# -*- coding: utf-8 -*- from array import array import pytest @pytest.fixture def SimpleClass(CrossinterpreterBaseClass): class SimpleClass(CrossinterpreterBaseClass): pass return SimpleClass def test_interpreter_dependent_instanciation(CrossinterpreterBaseClass, ...
Python
zaydzuhri_stack_edu_python
function equivalent first second begin string Compare two objects for equivalence (identity or equality), using array_equiv if either object is an ndarray comment TODO: refactor to avoid circular import from import duck_array_ops if is instance first ndarray or is instance second ndarray begin return call array_equiv ...
def equivalent(first: T, second: T) -> bool: """Compare two objects for equivalence (identity or equality), using array_equiv if either object is an ndarray """ # TODO: refactor to avoid circular import from . import duck_array_ops if isinstance(first, np.ndarray) or isinstance(second, np.ndarra...
Python
jtatman_500k
from copy import deepcopy import curses from random import randint from logging import debug import logging import os remove os string debug.log call basicConfig format=string %(message)s level=DEBUG filename=string debug.log set WHITE = COLOR_WHITE set BLACK = COLOR_BLACK set RED = COLOR_RED set BLUE = COLOR_BLUE set ...
from copy import deepcopy import curses from random import randint from logging import debug import logging import os os.remove('debug.log') logging.basicConfig(format='%(message)s', level=logging.DEBUG, filename='debug.log') WHITE = curses.COLOR_WHITE BLACK = curses.COLOR_BLACK RED = curses.COLOR...
Python
zaydzuhri_stack_edu_python
function _check_open begin set socket = call TSocket heavydb_host 6274 set transport = call TBufferedTransport socket try begin open return true end except TTransportException begin return false end end function
def _check_open(): socket = TSocket.TSocket(heavydb_host, 6274) transport = TTransport.TBufferedTransport(socket) try: transport.open() return True except TTransportException: return False
Python
nomic_cornstack_python_v1
function ConvertFileName cls infile band begin try begin import os end except any begin raise call ImportError string Can not find module os end end function
def ConvertFileName(cls,infile,band): try: import os except: raise ImportError("Can not find module os")
Python
nomic_cornstack_python_v1
import json set f = open string normalize-500-50-nor.json string r set f1 = open string properties.txt string r set p = list for line in read lines f1 begin set line = strip line string append p line end set property = list for line in read lines f begin set dics = loads line for i in range length dics begin if is in...
import json f = open('normalize-500-50-nor.json', 'r') f1 = open('properties.txt', 'r') p = [] for line in f1.readlines(): line = line.strip('\n') p.append(line) property = [] for line in f.readlines(): dics = json.loads(line) for i in range(len(dics)): if isinstance(dics[i], dict): ...
Python
zaydzuhri_stack_edu_python
for a in reversed sp begin append np a end for else begin print np print length sp end
for a in reversed(sp): np.append(a) else: print(np) print(len(sp))
Python
zaydzuhri_stack_edu_python
function index begin if method == string POST begin if call has_key string phone and call valid_phone form at string phone begin set session at string phone = form at string phone set code = call gen_code set session at string confirmation_code = code call create to=session at string phone _from=APP_NUMBER body=string ...
def index(): if request.method == 'POST': if (request.form.has_key('phone') and valid_phone(request.form['phone'])): session['phone'] = request.form['phone'] code = gen_code() session['confirmation_code'] = code twilio_client.messages.create(to...
Python
nomic_cornstack_python_v1
function set_steps_to_1_or_quit self signum frame begin if not received_sigint begin set total_steps = 1 set received_sigint = true critical string Received SIGINT, will finish this training step and then conclude training. critical string Send another SIGINT to immediately interrupt the process. end else begin critica...
def set_steps_to_1_or_quit(self, signum, frame): if not self.received_sigint: self.total_steps = 1 self.received_sigint = True logger.critical("\nReceived SIGINT, will finish this training step and then conclude training.") logger.critical("Send another SIGINT to ...
Python
nomic_cornstack_python_v1
comment coding: utf8 string 将ascii的word2vec 数据,转化为numpy格式的二进制数据. 示例: python script/build_term_emb_binary.py -i vocab/term.emb -o ${DEST_DIR}/term.emb.np import numpy as np import argparse import sys set parser = call ArgumentParser call add_argument string -i string --input help=string input multiple dict, split by ","...
#coding: utf8 """ 将ascii的word2vec 数据,转化为numpy格式的二进制数据. 示例: python script/build_term_emb_binary.py -i vocab/term.emb -o ${DEST_DIR}/term.emb.np """ import numpy as np import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="input multiple dict, split by \",\"", default=No...
Python
zaydzuhri_stack_edu_python
function main begin call basicConfig format=string %(asctime)s %(levelname)-5.5s %(message)s stream=stdout level=DEBUG comment Parse options set parser = call ArgumentParser description=string Generate a Commander decklist call add_argument string --layout help=string Which layout to use default=string fish call add_ar...
def main(): logging.basicConfig(format="%(asctime)s %(levelname)-5.5s %(message)s", stream=sys.stdout, level=logging.DEBUG) # Parse options parser = argparse.ArgumentParser(description='Generate a Commander decklist') parser.add_argument("--layout", help=...
Python
nomic_cornstack_python_v1
function test_condense_function self begin from collections import namedtuple set Measurement = named tuple string Measurement list string timestamp string value set tuple mid_minutes end_minutes = tuple 5 10 set datetime1 = now set datetime2 = datetime1 + time delta minutes=mid_minutes set datetime3 = datetime1 + time...
def test_condense_function(self): from collections import namedtuple Measurement = namedtuple('Measurement', ['timestamp', 'value']) mid_minutes, end_minutes = 5, 10 datetime1 = datetime.datetime.now() datetime2 = datetime1 + datetime.timedelta(minutes=mid_minutes) datet...
Python
nomic_cornstack_python_v1
string This computes Tantimoto distance based on SensEmbed vectors (They also have T* which includes a graph vicinity factor that needs to be tuned so I'm just using T for now) set INPUT = string ../sensembed/babelfy_vectors set VOCAB = string ./all/vocab.txt set OUTPUT = string ./all/sim_ssembed.txt from collections i...
""" This computes Tantimoto distance based on SensEmbed vectors (They also have T* which includes a graph vicinity factor that needs to be tuned so I'm just using T for now) """ INPUT = "../sensembed/babelfy_vectors" VOCAB = "./all/vocab.txt" OUTPUT = "./all/sim_ssembed.txt" from collections import defaultdict impor...
Python
zaydzuhri_stack_edu_python
function PosToPDB Pos L file begin comment Handle periodicity using minimum image convention set Pos = call MinImage Pos L * L comment Open target file to append set ofile = open file string a for atomnum in range length Pos begin set line = string %-6s%5s%5s %3s A 1 %8.3f%8.3f%8.3f % tuple string ATOM string atomnum s...
def PosToPDB( Pos, L, file): #Handle periodicity using minimum image convention Pos = MinImage(Pos, L)*L ofile = open(file, 'a') #Open target file to append for atomnum in range(len(Pos)): line = '%-6s%5s%5s %3s A 1 %8.3f%8.3f%8.3f\n' % ( 'ATOM', str(atomnum), 'C', 'MOL', Pos[atomnum][0],...
Python
nomic_cornstack_python_v1
function model_score_for_data self begin set data = call __preparing_data set model = linear regression set HP = data at string HP set level = data at string level set level_reshape = reshape array level - 1 1 fit model level_reshape HP comment predicted = model.predict(level_reshape) return score model level_reshape H...
def model_score_for_data(self): data = self.__preparing_data() model = sklearn.linear_model.LinearRegression() HP = data['HP'] level = data['level'] level_reshape = np.array(level).reshape(-1, 1) model.fit(level_reshape, HP) #predicted = model.predict(l...
Python
nomic_cornstack_python_v1
function get_oscillatedspectra self t E flavor_xform begin set initialspectra = call get_initialspectra t E set oscillatedspectra = dict set oscillatedspectra at NU_E = call prob_ee t E * initialspectra at NU_E + call prob_ex t E * initialspectra at NU_X set oscillatedspectra at NU_X = call prob_xe t E * initialspectr...
def get_oscillatedspectra(self, t, E, flavor_xform): initialspectra = self.get_initialspectra(t, E) oscillatedspectra = {} oscillatedspectra[Flavor.NU_E] = \ flavor_xform.prob_ee(t, E) * initialspectra[Flavor.NU_E] + \ flavor_xform.prob_ex(t, E) * initialspectra[Fl...
Python
nomic_cornstack_python_v1
string function reusable step1. define, create step2. call a function comment step1.define function myfunc1 begin print string hello print string python function end function comment function body comment step2. call call myfunc1 comment y = x function mathfunc1 x begin set y = x return y end function set x = 2 set res...
""" function reusable step1. define, create step2. call a function """ # step1.define def myfunc1(): print("hello") print("python function") # function body # step2. call myfunc1() # y = x def mathfunc1(x): y = x return y x = 2 result = mathfunc1(x) print("x={}, for y=x, result: y = {}".form...
Python
zaydzuhri_stack_edu_python
import sqlite3 set db = call connect string queue.db set cursor = call cursor execute cursor string SELECT * FROM queue set all = call fetchall
import sqlite3 db = sqlite3.connect('queue.db') cursor = db.cursor() cursor.execute(''' SELECT * FROM queue ''') all=cursor.fetchall()
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template comment import matplotlib.pyplot as plt comment import seaborn as sns comment import numpy as np comment from pyecharts import options as opts comment from pyecharts.charts import Pie set app = call Flask __name__ decorator call route string /bim comment def generate_matplotlib...
from flask import Flask, render_template # import matplotlib.pyplot as plt # import seaborn as sns # import numpy as np # from pyecharts import options as opts # from pyecharts.charts import Pie app = Flask(__name__) # def generate_matplotlib_png(): # """使用matplotlib绘图,生成图片""" # x = np.linspace(-5, 5, 100) #...
Python
zaydzuhri_stack_edu_python
function filtered_preorder_iterator node select=none ignore=none begin if ignore and call ignore node begin return end if select is none or select node begin yield node end for child in children begin yield from call filtered_preorder_iterator child select ignore end end function
def filtered_preorder_iterator(node, select=None, ignore=None): if ignore and ignore(node): return if select is None or select(node): yield node for child in node.children: yield from filtered_preorder_iterator(child, select, ignore)
Python
nomic_cornstack_python_v1
function adjust_detection im_ms cloud_mask im_labels im_ref_buffer image_epsg georef settings date satname buffer_size_pixels begin set sitename = settings at string inputs at string sitename set filepath_data = settings at string inputs at string filepath comment subfolder where the .jpg file is stored if the user acc...
def adjust_detection(im_ms, cloud_mask, im_labels, im_ref_buffer, image_epsg, georef, settings, date, satname, buffer_size_pixels): sitename = settings['inputs']['sitename'] filepath_data = settings['inputs']['filepath'] # subfolder where the .jpg file is stored if the user accepts t...
Python
nomic_cornstack_python_v1
function polynomial_fitting strain stress lower_window upper_window begin for i in range length strain begin if strain at i > lower_window begin set si = i break end pass end for i in range length strain begin if strain at i > upper_window begin set sf = i break end pass end comment sig = A eps^n : fitting polynomial f...
def polynomial_fitting(strain, stress, lower_window, upper_window): for i in range(len(strain)): if strain[i]>lower_window: si=i;break pass for i in range(len(strain)): if strain[i]>upper_window: sf=i;break pass # sig = A eps^n : fitting polynomial function # ln(s...
Python
nomic_cornstack_python_v1