code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function run_drg model_file ignition_conditions psr_conditions flame_conditions error_limit species_targets species_safe phase_name=string threshold_upper=none num_threads=1 path=string begin set solution = call Solution model_file phase_name assert species_targets msg string Need to specify at least one target specie...
def run_drg(model_file, ignition_conditions, psr_conditions, flame_conditions, error_limit, species_targets, species_safe, phase_name='', threshold_upper=None, num_threads=1, path='' ): solution = ct.Solution(model_file, phase_name) assert species_targets, 'Need to specify ...
Python
nomic_cornstack_python_v1
comment !python3.6.1 comment -*- coding: utf-8 -*- comment author: https://github.com/vinlinch comment 第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」, comment 就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。 comment 步骤 comment 1.使用xlrd读取excel文件内容到json类型对象 comment 2.使用 xlm ...
#!python3.6.1 # -*- coding: utf-8 -*- # author: https://github.com/vinlinch # 第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段,点击「查询」按钮,查询结果页面的最下方,点击「导出」, # 就会生成类似于 2014年10月01日~2014年10月31日通话详单.xls 文件。写代码,对每月通话时间做个统计。 # 步骤 # 1.使用xlrd读取excel文件内容到json类型对象 # 2.使用 xlm minidom创建xlmnode,常规文件write保存 import xlrd import ...
Python
zaydzuhri_stack_edu_python
function ColorIdentityIs colours begin return call And call ColorIdentityHas colours call ColorIdentityOnly colours end function comment return And( And(*(search(field='colorIdentity', method=IN, value=c) comment for c in colours)), comment Not(*(search(field='colorIdentity', method=IN, value=c) comment for c in notcol...
def ColorIdentityIs(colours): return And(ColorIdentityHas(colours), ColorIdentityOnly(colours)) # return And( And(*(search(field='colorIdentity', method=IN, value=c) # for c in colours)), # Not(*(search(field='colorIdentity', method=IN, value=c) # for ...
Python
nomic_cornstack_python_v1
function pc_nproduced self begin return call atsc_ds_to_softds_sptr_pc_nproduced self end function
def pc_nproduced(self): return _atsc_swig.atsc_ds_to_softds_sptr_pc_nproduced(self)
Python
nomic_cornstack_python_v1
function istidy num begin set s = string num set lastdig = none for sdig in s begin set dig = integer sdig if lastdig != none and dig < lastdig begin return false end set lastdig = dig end return true end function function lasttidy_simple num begin while not call istidy num begin set num = num - 1 end return num end fu...
def istidy(num: int): s = str(num) lastdig = None for sdig in s: dig = int(sdig) if lastdig != None and dig < lastdig: return False lastdig = dig return True def lasttidy_simple(num): while not istidy(num): num -= 1 return num def ...
Python
zaydzuhri_stack_edu_python
string Урок 4 Задание 1 Проанализировать скорость и сложность одного любого алгоритма, разработанных в рамках домашнего задания первых трех уроков. Примечание: попробуйте написать несколько реализаций алгоритма и сравнить их import math from timeit import timeit , default_timer function time_it func begin string Обертк...
""" Урок 4 Задание 1 Проанализировать скорость и сложность одного любого алгоритма, разработанных в рамках домашнего задания первых трех уроков. Примечание: попробуйте написать несколько реализаций алгоритма и сравнить их """ import math from timeit import timeit, default_timer def time_it(func): """ Обертка...
Python
zaydzuhri_stack_edu_python
while n != 0 begin set m = n % 10 if m > answer begin set answer = m end set n = n // 10 end print string Самая большая цифра: integer answer
while n != 0: m = n % 10 if m > answer: answer = m n //= 10 print("Самая большая цифра: ", int(answer))
Python
zaydzuhri_stack_edu_python
import pandas as pd from sklearn.ensemble import RandomForestClassifier , RandomForestRegressor from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split , RandomizedSearchCV import numpy as np from sklearn.model_selection import GridSearchCV from sklearn.pipeline import P...
import pandas as pd from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, RandomizedSearchCV import numpy as np from sklearn.model_selection import GridSearchCV from sklearn.pipeline impo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python class TruncatedMessage extends Exception begin pass end class function decode_dict msg begin assert msg at 0 == string { msg call repr msg set msg = msg at slice 1 : : set d = dict while msg != string and msg at 0 != string } begin set tuple k msg = decode msg set tuple v msg = decode m...
#!/usr/bin/env python class TruncatedMessage(Exception): pass def decode_dict(msg): assert msg[0] == "{",repr(msg) msg=msg[1:] d={} while msg!="" and msg[0] != "}": k,msg = decode(msg) v,msg = decode(msg) d[k]=v if msg=="": raise TruncatedMessage() return d,msg[1:] def decode_str(msg): assert msg[0] ...
Python
zaydzuhri_stack_edu_python
function clean_str string begin set string = sub string [^A-Za-z0-9(),!?\'\`] string string set string = sub string \'s string 's string set string = sub string \'ve string 've string set string = sub string n\'t string n't string set string = sub string \'re string 're string set string = sub string \'d string 'd str...
def clean_str(string): string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) s...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[3]: import csv import os import numpy as np import pandas as pd import csv change directory string C:/Users/saksh/Desktop/Rotman/TD hackathon/hackathon_data/company_prices_returns set curr_path = get current directory set files = list directory curr_path set...
#!/usr/bin/env python # coding: utf-8 # In[3]: import csv import os import numpy as np import pandas as pd import csv os.chdir("C:/Users/saksh/Desktop/Rotman/TD hackathon/hackathon_data/company_prices_returns") curr_path = os.getcwd() files = os.listdir(curr_path) csv_files = [f for f in files if f[-3:] == 'csv'] ...
Python
zaydzuhri_stack_edu_python
comment make sure you've installed this! import requests comment this is the last file we made import RiotConstants as RC class RiotAPI extends object begin comment can change this to any region function __init__ self api_key region=REGIONS at string north_america begin set api_key = api_key set region = region end fun...
import requests #make sure you've installed this! import RiotConstants as RC #this is the last file we made class RiotAPI(object): def __init__(self, api_key, region=RC.REGIONS['north_america']): #can change this to any region self.api_key = api_key self.region = region def _request(s...
Python
zaydzuhri_stack_edu_python
import collections from collections import defaultdict from collections import Counter import sys set od = ordered dictionary from collections import OrderedDict set f = string s.txt set f = open f string r set wordcount = counter split read f close f set f = string s.txt set f = open f string r set wc2 = dict for wor...
import collections from collections import defaultdict from collections import Counter import sys od = collections.OrderedDict() from collections import OrderedDict f = "s.txt" f = open(f, "r") wordcount = Counter(f.read().split()) f.close() f = "s.txt" f = open(f, "r") wc2={} for word in f.read().split(): if ...
Python
zaydzuhri_stack_edu_python
function create_roles apps schema_editor begin string Create the enterprise roles if they do not already exist. set EnterpriseFeatureRole = call get_model string enterprise string EnterpriseFeatureRole call update_or_create name=ENTERPRISE_CATALOG_ADMIN_ROLE call update_or_create name=ENTERPRISE_DASHBOARD_ADMIN_ROLE ca...
def create_roles(apps, schema_editor): """Create the enterprise roles if they do not already exist.""" EnterpriseFeatureRole = apps.get_model('enterprise', 'EnterpriseFeatureRole') EnterpriseFeatureRole.objects.update_or_create(name=ENTERPRISE_CATALOG_ADMIN_ROLE) EnterpriseFeatureRole.objects.update_or_...
Python
jtatman_500k
import tensorflow as tf from tensorflow.python import debug as tf_debug import numpy as np import gym import matplotlib.pyplot as plt from arm_env import ArmEnv function to_cat a n begin return array list comprehension if expression a == i then 1 else 0 for i in range n end function function discount_and_norm_rewards e...
import tensorflow as tf from tensorflow.python import debug as tf_debug import numpy as np import gym import matplotlib.pyplot as plt from arm_env import ArmEnv def to_cat(a, n): return np.array([1 if a == i else 0 for i in range(n)]) def discount_and_norm_rewards(episode_rewards, gamma): discounted_episode_...
Python
zaydzuhri_stack_edu_python
string 《邢不行-2020新版|Python数字货币量化投资课程》 无需编程基础,助教答疑服务,专属策略网站,一旦加入,永续更新。 课程详细介绍:https://quantclass.cn/crypto/class 邢不行微信: xbx9025 本程序作者: 邢不行/西蒙斯 # 课程内容 - 基本函数的定义 - 调用函数 - 函数的返回值 - 函数的重要意义 功能:本程序主要介绍python的函数。希望以后大家只要看这个程序,就能回想起相关的基础知识。 string 函数是编程当中最常用的概念,其目的是将一段功能完整的代码封装起来,方便之后的反复使用。 comment ===== 基本函数的定义 function print_...
""" 《邢不行-2020新版|Python数字货币量化投资课程》 无需编程基础,助教答疑服务,专属策略网站,一旦加入,永续更新。 课程详细介绍:https://quantclass.cn/crypto/class 邢不行微信: xbx9025 本程序作者: 邢不行/西蒙斯 # 课程内容 - 基本函数的定义 - 调用函数 - 函数的返回值 - 函数的重要意义 功能:本程序主要介绍python的函数。希望以后大家只要看这个程序,就能回想起相关的基础知识。 """ """ 函数是编程当中最常用的概念,其目的是将一段功能完整的代码封装起来,方便之后的反复使用。 """ # ===== 基本函数的定义 def print_two_...
Python
zaydzuhri_stack_edu_python
function check_line filename line n begin comment Strip the terminal newline. set line = line at slice : - 1 : end function
def check_line(filename, line, n): # Strip the terminal newline. line = line[:-1]
Python
nomic_cornstack_python_v1
import socket from IPy import IP print string while true begin function scan target begin set converted_ip = call check_ip target print string + string [Scanning.....] + string target print string for port in range 0 100 begin call scan_port converted_ip port end end function function check_ip ip begin try begin call ...
import socket from IPy import IP print("") while True: def scan(target): converted_ip = check_ip(target) print('\n' + '[Scanning.....] ' + str(target)) print("") for port in range(0,100): scan_port(converted_ip, port) def check_ip(ip): try: ...
Python
zaydzuhri_stack_edu_python
function get_files self regexp full_path=false begin if full_path begin set files = list comprehension f for f in files if match regexp f end else begin set files = list comprehension base name path f for f in files if match regexp f end return files end function
def get_files(self, regexp, full_path=False): if full_path: files = [f for f in self.files if re.match(regexp, f)] else: files = [os.path.basename(f) for f in self.files if re.match(regexp, f)] return files
Python
nomic_cornstack_python_v1
function is_valid passphrase begin set words_seen = set for word in split passphrase begin if word in words_seen begin return false end add words_seen word end return true end function function main begin with open string passphrases.txt as f begin print sum generator expression call is_valid strip line for line in f e...
def is_valid(passphrase): words_seen = set() for word in passphrase.split(): if word in words_seen: return False words_seen.add(word) return True def main(): with open("passphrases.txt") as f: print(sum(is_valid(line.strip()) for line in f)) if __name__ == "__main...
Python
zaydzuhri_stack_edu_python
function remove self name begin set init = call _get_implementation name call _assert_service_installed init name info string Removing %s service %s... init_system name call stop call uninstall info string Service removed end function
def remove(self, name): init = self._get_implementation(name) self._assert_service_installed(init, name) logger.info('Removing %s service %s...', self.init_system, name) init.stop() init.uninstall() logger.info('Service removed')
Python
nomic_cornstack_python_v1
import media import fresh_tomatoes comment create movies set departed = call Movie string Departed string Cops or Criminals string http://upload.wikimedia.org/wikipedia/en/5/50/Departed234.jpg string https://www.youtube.com/watch?v=auYbpnEwBBg set superbad = call Movie string The Hangover string Some guys just can't ha...
import media import fresh_tomatoes #create movies departed = media.Movie("Departed", "Cops or Criminals", "http://upload.wikimedia.org/wikipedia/en/5/50/Departed234.jpg", "https://www.youtube.com/watch?v=auYbpnEwBBg") superbad = media.Movie("The Hangov...
Python
zaydzuhri_stack_edu_python
import time import RandomArray function Quicksort A p r begin if p < r begin set q = call Partition A p r call Quicksort A p q - 1 call Quicksort A q + 1 r end end function function Partition A p r begin comment pivot set x = A at r set i = p - 1 for j in range p r begin if A at j <= x begin set i = i + 1 set tuple A a...
import time import RandomArray def Quicksort(A, p, r): if p < r: q = Partition(A, p, r) Quicksort(A, p, q-1) Quicksort(A,q+1, r) def Partition(A, p, r): x = A[r] #pivot i = p-1 for j in range(p,r): if A[j] <= x: i = i+1 A[i], A[j] = A[j], A[i] ...
Python
zaydzuhri_stack_edu_python
function extract self variable_idx begin string Extract a specific varaible set branch = call _define_branch variable_idx set label = replace profiles at variable_idx string string set label at variable_idx = label set data at variable_idx = list list list with open abspath as fobj begin for line in read lines fobj ...
def extract(self, variable_idx): """ Extract a specific varaible """ branch = self._define_branch(variable_idx) label = self.profiles[variable_idx].replace("\n", "") self.label[variable_idx] = label self.data[variable_idx] = [[], []] with open(self...
Python
jtatman_500k
function draw_first_line stream textbox text_overflow block_ellipsis x y angle=0 begin comment Don’t draw lines with only invisible characters if not strip text begin return list end set font_size = style at string font_size comment Default float precision used by pydyf if font_size < 1e-06 begin return list end call...
def draw_first_line(stream, textbox, text_overflow, block_ellipsis, x, y, angle=0): # Don’t draw lines with only invisible characters if not textbox.text.strip(): return [] font_size = textbox.style['font_size'] if font_size < 1e-6: # Default float precision used by pydyf ...
Python
nomic_cornstack_python_v1
function update_action_choices self latest_macro_actions_seen begin set grammar_calculator = call k_Sequitur k=hyperparameters at string sequitur_k end_of_episode_symbol=end_of_episode_symbol print string latest_macro_actions_seen latest_macro_actions_seen set tuple _ _ _ rules_episode_appearance_count = call generate_...
def update_action_choices(self, latest_macro_actions_seen): grammar_calculator = k_Sequitur(k=self.config.hyperparameters["sequitur_k"], end_of_episode_symbol=self.end_of_episode_symbol) print("latest_macro_actions_seen ", latest_macro_actions_seen) _, _, ...
Python
nomic_cornstack_python_v1
function predict_outputs sample_sheet=none sample_sheet_file=none begin comment Set up linter set linter = call SampleSheetLinter sample_sheet=sample_sheet sample_sheet_file=sample_sheet_file comment Do checks set close_names = call close_project_names comment Generate prediction report set prediction = list set title...
def predict_outputs(sample_sheet=None,sample_sheet_file=None): # Set up linter linter = SampleSheetLinter(sample_sheet=sample_sheet, sample_sheet_file=sample_sheet_file) # Do checks close_names = linter.close_project_names() # Generate prediction report prediction ...
Python
nomic_cornstack_python_v1
import csv import numpy as np import sklearn.tree as model set i = 0 set j = 0 set train_data = list set train_labels = list set test_data = list set test_labels = list for line in open string ./../../dataset/train.csv begin if i == 0 begin set i = i + 1 continue end set each_data_point = split line string , pop ea...
import csv import numpy as np import sklearn.tree as model i = 0 j = 0 train_data = [] train_labels = [] test_data = [] test_labels = [] for line in open("./../../dataset/train.csv"): if i == 0: i = i + 1 continue; each_data_point = line.split(',') each_data_point.pop(0) if i % 4 == 0: label = each_data_poi...
Python
zaydzuhri_stack_edu_python
function rss_md5 string begin if not is instance string basestring begin try begin set string = decode string string utf8 string replace end except any begin pass end end set md5 = md5 update md5 encode string string utf8 return hex digest md5 end function
def rss_md5(string): if not isinstance(string, basestring): try: string = string.decode('utf8','replace') except: pass md5 = hashlib.md5() md5.update(string.encode('utf8')) return md5.hexdigest()
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt set file_address = string logs/user2.txt set file_output_address = string np/ + file_address at slice index file_address string / : : set output_file = open file_output_address string w with open file_address as f begin set titles = split replace read line f string ...
import numpy as np import matplotlib.pyplot as plt file_address = 'logs/user2.txt' file_output_address = 'np/' + file_address[file_address.index('/'):] output_file = open(file_output_address, 'w') with open(file_address) as f: titles = f.readline().replace(" ", "").split(",")[1:] for line in f: output...
Python
zaydzuhri_stack_edu_python
comment wxGlade: DAQPanel.<event_handler> function on12Lead self event begin comment self.lead12_button.Enable(False) set CreateDialog2 = call Lead12Dialog2 self self call ShowModal end function
def on12Lead(self, event): # wxGlade: DAQPanel.<event_handler> #self.lead12_button.Enable(False) CreateDialog2 = Lead12Dialog2(self, self) CreateDialog2.ShowModal()
Python
nomic_cornstack_python_v1
function GetItemIndex self x y begin set col = x - _tBorder / _tWidth + _tBorder if col >= _cols begin set col = _cols - 1 end set row = - 1 set y = y - _tBorder while y > 0 begin set row = row + 1 set y = y - _tHeight + _tBorder + call GetCaptionHeight row end if row < 0 begin set row = 0 end set index = row * _cols +...
def GetItemIndex(self, x, y): col = (x - self._tBorder)/(self._tWidth + self._tBorder) if col >= self._cols: col = self._cols - 1 row = -1 y = y - self._tBorder while y > 0: row = row + 1 y = y - (self._...
Python
nomic_cornstack_python_v1
import sqlite3 function new_password begin comment connect to db set connect_to_db = call connect string database.db set c = call cursor set website = input string Enter website name: set username = input string Enter your username or e-mail: set password = input string Enter your password: execute c string INSERT INTO...
import sqlite3 def new_password(): # connect to db connect_to_db = sqlite3.connect('database.db') c = connect_to_db.cursor() website = input("Enter website name: ") username = input("Enter your username or e-mail: ") password = input("Enter your password: ") c.execute("""INSERT INTO pa...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment -------------------------------------------------------------------------- comment Copyright (c) Microsoft Corporation. All rights reserved. comment Licensed under the MIT License. See License.txt in the project root for license information. comment Code generated by Microsoft (R) AutoRest ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
Python
jtatman_500k
function _launchAgentProcess self begin return popen list executable join path path at 0 string agentProcess.py string _processPid stdin=PIPE stdout=PIPE end function
def _launchAgentProcess( self ): return subprocess.Popen( [ sys.executable, os.path.join( sys.path[0], 'agentProcess.py' ), str( _processPid ) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE )
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- set __auth__ = string christian string A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies. A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, B...
# -*- coding:utf-8 -*- __auth__ = 'christian' ''' A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies. A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphor...
Python
zaydzuhri_stack_edu_python
function slack_factor self begin return get pulumi self string slack_factor end function
def slack_factor(self) -> Optional[float]: return pulumi.get(self, "slack_factor")
Python
nomic_cornstack_python_v1
function solution arr begin set i = 1 while i < length arr begin if absolute arr at i - arr at i - 1 % 2 != 0 begin return string NO end set i = i + 1 end return string YES end function for _ in range integer input begin set n = integer input set A = list map int split input print call solution A end
def solution(arr): i = 1 while i < len(arr): if abs(arr[i] - arr[i-1])%2 != 0: return "NO" i += 1 return "YES" for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) print(solution(A))
Python
zaydzuhri_stack_edu_python
from decimal import Decimal class Worker begin function __init__ self name surname position wage bonus begin set name = name set surname = surname set position = position set _income = dict string wage wage ; string bonus bonus end function end class class Position extends Worker begin function get_full_name self begin...
from decimal import Decimal class Worker: def __init__(self, name, surname, position, wage, bonus): self.name = name self.surname = surname self.position = position self._income = { 'wage': wage, 'bonus': bonus } class Position(Worker): def get...
Python
zaydzuhri_stack_edu_python
from time import sleep function open_file begin try begin set file = open string your_path string r print string File opened with success! Path: { name } end except FileNotFoundError as error begin print string ERROR! { error } set opt = upper input string Do you want create the file? if opt == string YES begin try beg...
from time import sleep def open_file(): try: file = open('your_path', 'r') print(f'File opened with success!\nPath: {file.name}') except FileNotFoundError as error: print(f'ERROR! {error}') opt = input('Do you want create the file? ').upper() if opt == 'YES': try: creat...
Python
zaydzuhri_stack_edu_python
function test_msf_spider self begin set msf_spider = call MSFSpider set res = call save_pdf pdf_response assert true res assert true string foo == res at string title end function
def test_msf_spider(self): msf_spider = MSFSpider() res = msf_spider.save_pdf(self.pdf_response) self.assertTrue(res) self.assertTrue('foo' == res['title'])
Python
nomic_cornstack_python_v1
function vc_to_dict column begin set vc = value counts column set index = as type index str return call to_dict end function
def vc_to_dict(column): vc = column.value_counts() vc.index = vc.index.astype(str) return vc.to_dict()
Python
nomic_cornstack_python_v1
import backtrader import datetime from BacktraderStrategies import TestStrategy set cerebro = call Cerebro call set_cash 1000000 set data = call YahooFinanceCSVData dataname=string oracle.csv fromdate=call datetime 2000 1 1 todate=call datetime 2000 12 31 reverse=false comment Do not pass values before this date commen...
import backtrader import datetime from BacktraderStrategies import TestStrategy cerebro = backtrader.Cerebro() cerebro.broker.set_cash(1000000) data=backtrader.feeds.YahooFinanceCSVData( dataname='oracle.csv', #Do not pass values before this date fromdate=datetime.datetime(2000,1,1), #Do not pass valu...
Python
zaydzuhri_stack_edu_python
function _arglist self begin set arglist = list second if is instance first ApplicationExpression begin extend arglist call _arglist end return arglist end function
def _arglist(self): arglist = [self.second] if isinstance(self.first, ApplicationExpression): arglist.extend(self.first._arglist()) return arglist
Python
nomic_cornstack_python_v1
function update_direction self ele direction begin if direction is not none begin set ele at string object at string direction = direction set ele at string object at string orientation = direction end end function
def update_direction(self, ele, direction): if direction is not None: ele['object']['direction'] = direction ele['object']['orientation'] = direction
Python
nomic_cornstack_python_v1
import re , collections set P0 = compile string rotate (right|left) (\d+) steps set P1 = compile string swap position (\d+) with position (\d+) set P2 = compile string reverse positions (\d+) through (\d+) set P3 = compile string move position (\d+) to position (\d+) set P4 = compile string rotate based on position of ...
import re, collections P0 = re.compile("rotate (right|left) (\d+) steps") P1 = re.compile("swap position (\d+) with position (\d+)") P2 = re.compile("reverse positions (\d+) through (\d+)") P3 = re.compile("move position (\d+) to position (\d+)") P4 = re.compile("rotate based on position of letter ([a-z])") P5 = re.co...
Python
zaydzuhri_stack_edu_python
function parse_args begin set len_args = length argv if len_args < 2 begin exit warning string Usage: python ssh.py <app_name> <optional_ssh_key> end else if len_args == 2 begin if argv at 1 == string --help or argv at 1 == string -h begin exit info string Usage: python ssh.py <app_name> <optional_ssh_key> end else beg...
def parse_args(): len_args = len(sys.argv) if len_args < 2: sys.exit(logging.warning( "Usage: python ssh.py <app_name> <optional_ssh_key>")) elif len_args == 2: if sys.argv[1] == "--help" or sys.argv[1] == "-h": sys.exit(logging.info( "Usage: python ss...
Python
nomic_cornstack_python_v1
function rearrange A begin for i in range length A begin comment sorted sorts the array segment, reverse key sorts desc or asc based on boolean (true/false) comment in this case if i is even, reverse the order of the sort comment print(sorted(A[i:i+2], reverse=i%2)) set A at slice i : i + 2 : = sorted A at slice i : i...
def rearrange(A): for i in range(len(A)): # sorted sorts the array segment, reverse key sorts desc or asc based on boolean (true/false) # in this case if i is even, reverse the order of the sort # print(sorted(A[i:i+2], reverse=i%2)) A[i:i+2] = sorted(A[i:i+2], reverse=i%2) rearrang...
Python
zaydzuhri_stack_edu_python
function walk config override begin call basicConfig format=string %(levelname)s %(funcName)s %(message)s level=INFO for tuple override_key override_value in items override begin comment If the value is another dictionary go deeper if is instance override_value dict begin if call key_exists override_key config begin co...
def walk(config, override): logging.basicConfig( format="%(levelname)s %(funcName)s %(message)s", level=logging.INFO ) for override_key, override_value in override.items(): # If the value is another dictionary go deeper if isinstance(override_value, dict): if key_exists...
Python
nomic_cornstack_python_v1
function headers begin return dict string Authorization string token_secure end function
def headers(): return {'Authorization': 'token_secure'}
Python
nomic_cornstack_python_v1
function set_direction self right_or_left begin if right_or_left == string r begin set __direction = __direction - 7 end else if right_or_left == string l begin set __direction = __direction + 7 end end function
def set_direction(self, right_or_left): if right_or_left == "r": self.__direction = self.__direction - 7 elif right_or_left == "l": self.__direction = self.__direction + 7
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: UTF-8 -*- comment Python 模块 comment Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。 comment 模块让你能够有逻辑地组织你的 Python 代码段。 comment 把相关的代码分配到一个模块里能让你的代码更好用,更易懂。 comment 模块能定义函数,类和变量,模块里也能包含可执行的代码。 comment 模块的引入 import test call print_func string aaa from hello1...
#!/usr/bin/python # -*- coding: UTF-8 -*- # Python 模块 # Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。 # 模块让你能够有逻辑地组织你的 Python 代码段。 # 把相关的代码分配到一个模块里能让你的代码更好用,更易懂。 # 模块能定义函数,类和变量,模块里也能包含可执行的代码。 # 模块的引入 import test test.print_func("aaa") from hello1 import linlufeng linlufeng('abc') ''' from…impo...
Python
zaydzuhri_stack_edu_python
with open string in.txt as fh begin set current_elf = 0 for line in fh begin if line == string begin append elfs current_elf set current_elf = 0 end else begin set calories = integer strip line set current_elf = current_elf + calories end end end append elfs current_elf print sum sorted elfs at slice - 3 : :
with open('in.txt') as fh: current_elf = 0 for line in fh: if line == '\n': elfs.append(current_elf) current_elf = 0 else: calories = int(line.strip()) current_elf += calories elfs.append(current_elf) print(sum(sorted(elfs)[-3:]))
Python
zaydzuhri_stack_edu_python
function create_registry begin return call HookBasedRegistry end function
def create_registry() -> Registry: return HookBasedRegistry()
Python
nomic_cornstack_python_v1
function condition self evidence begin set ax = tuple list comprehension if expression v in evidence then evidence at v else call slice none for v in v set cvars = list comprehension v for v in v if v in evidence comment forces table copy in constructor return call Factor v - cvars t at ax end function
def condition(self, evidence): ax = tuple([ evidence[v] if v in evidence else slice(None) for v in self.v ]) cvars = [ v for v in self.v if v in evidence ] return Factor(self.v - cvars, self.t[ax]) # forces table copy in constructor
Python
nomic_cornstack_python_v1
string listings add amenities import re set unique_amen = list set uni_counts = list set amen = call tolist for a in amen begin comment print(a) if type a == str begin set coun = split a string , set lis = list comprehension sub string ["{}] string i for i in coun for l in lis begin append unique_amen l end append u...
''' listings add amenities ''' import re unique_amen=[] uni_counts=[] amen=listings['amenities'].values.tolist() for a in amen: #print(a) if type(a)==str: coun=a.split(",") lis=[re.sub('["{}]','',i) for i in coun] for l in lis: unique_amen.append(l) ...
Python
zaydzuhri_stack_edu_python
function xy82xyvec xy8 begin set vs = xy8 at tuple slice : : slice 2 : 4 : - xy8 at tuple slice : : slice : 2 : set xs = 0.5 * xy8 at tuple slice : : 0 + xy8 at tuple slice : : 4 set ys = 0.5 * xy8 at tuple slice : : 1 + xy8 at tuple slice : : 5 set xyvec = stack list xs ys xs + vs at tuple slice ...
def xy82xyvec(xy8): vs = xy8[:, 2:4] - xy8[:, :2] xs = 0.5*(xy8[:, 0] + xy8[:, 4]) ys = 0.5*(xy8[:, 1] + xy8[:, 5]) xyvec = torch.stack([xs, ys, xs+vs[:,0], ys+vs[:,1]], dim=1) return xyvec
Python
nomic_cornstack_python_v1
function btop2cigar btopString concise=false aa=false begin string Convert a BTOP string to a CIGAR string. @param btopString: A C{str} BTOP sequence. @param concise: If C{True}, use 'M' for matches and mismatches instead of the more specific 'X' and '='. @param aa: If C{True}, C{btopString} will be interpreted as thou...
def btop2cigar(btopString, concise=False, aa=False): """ Convert a BTOP string to a CIGAR string. @param btopString: A C{str} BTOP sequence. @param concise: If C{True}, use 'M' for matches and mismatches instead of the more specific 'X' and '='. @param aa: If C{True}, C{btopString} will be ...
Python
jtatman_500k
function cycle_file source_plaintext_filename begin string Encrypts and then decrypts a file under a custom static master key provider. :param str source_plaintext_filename: Filename of file to encrypt comment Create a static random master key provider set key_id = call urandom 8 set master_key_provider = call StaticRa...
def cycle_file(source_plaintext_filename): """Encrypts and then decrypts a file under a custom static master key provider. :param str source_plaintext_filename: Filename of file to encrypt """ # Create a static random master key provider key_id = os.urandom(8) master_key_provider = StaticRandom...
Python
jtatman_500k
function unify_document_title title begin comment Remove all spaces and convert to lowercase set unified_title = lower replace title string string comment Now remove all these unneeded ugly symbols set unified_title = sub string [-_.,:;\|/\{\}\(\)\[\]'"\+] string unified_title set trimmed_unified_title = unified_titl...
def unify_document_title(title: str) -> (str, str): # Remove all spaces and convert to lowercase unified_title = title.replace(" ","").lower() # Now remove all these unneeded ugly symbols unified_title = re.sub('[-_.,:;\|/\{\}\(\)\[\]\'\"\+]','', unified_title) trimmed_unified_title = unified_title...
Python
nomic_cornstack_python_v1
function sum_naturals n begin set total = 0 for num in range n + 1 begin set total = total + num end return total end function
def sum_naturals(n): total = 0 for num in range(n + 1): total += num return total
Python
jtatman_500k
comment using range function comment use for loops with the rnage funciton comment good for genrating a range of numbers to loop through comment for number in range(a, b): comment print(number) comment DOES NOT INCLUDE END OF THE RANGE comment for number in range(1, 10): comment print(number) comment out puts 1-9 comme...
# using range function # use for loops with the rnage funciton # good for genrating a range of numbers to loop through # for number in range(a, b): # print(number) # DOES NOT INCLUDE END OF THE RANGE # for number in range(1, 10): # print(number) # out puts 1-9 # if wanted all, would have to make it 1...
Python
zaydzuhri_stack_edu_python
comment Example: How to hook an object into __main__.py class MyClass begin function __init__ self name begin set name = name end function function say_name self begin return end function end class
## # Example: How to hook an object into __main__.py # class MyClass(): def __init__(self, name): self.name = name def say_name(self): return
Python
zaydzuhri_stack_edu_python
function _backtrace self address begin set push = call GetOpnd address 0 set arg = call parseOperand push set purpose = call GPRPurpose push set currentAddress = call PrevHead address set dism = call GetDisasm currentAddress set funcStart = call GetFunctionAttr address FUNCATTR_START while currentAddress >= funcStart b...
def _backtrace(self, address): push = self.ida_proxy.GetOpnd(address, 0) arg = self.parseOperand(push) purpose = self.GPRPurpose(push) currentAddress = self.ida_proxy.PrevHead(address) dism = self.ida_proxy.GetDisasm(currentAddress) funcStart = self.ida_proxy.GetFunctio...
Python
nomic_cornstack_python_v1
function plot_btime key btimes thresh_ns=25 ignore_ns=0.5 xlim=tuple 0 25 ylim=tuple 1 2.5 starson=false begin set tuple fig axs = call subplots figsize=tuple 12 3 ncols=2 nrows=1 subplot_kw=dict string xlim xlim gridspec_kw=dict string wspace 0.25 print key set data = btimes at key set data_masked = data at data at st...
def plot_btime(key, btimes, thresh_ns=25, ignore_ns=0.5, xlim=(0, 25), ylim=(1, 2.5), starson=False): fig, axs = plt.subplots(figsize=(12, 3), ncols=2, nrows=1, subplot_kw={ 'xlim': xlim}, gridspec_kw={'wspace': 0.25}) print(key) data = btimes[key] data_masked = data[dat...
Python
nomic_cornstack_python_v1
function test_invalid_grid self begin comment create a new grid set state = dictionary GRID set grid_square = tuple 1 9 with assert raises KeyError begin call assign_to_grid grid_square 1 state end end function
def test_invalid_grid(self): state = dict(grid8.GRID) # create a new grid grid_square = (1, 9,) with self.assertRaises(KeyError): grid8.assign_to_grid(grid_square, 1, state)
Python
nomic_cornstack_python_v1
comment !/bin/python comment deadscrape.py comment author: dead1 comment Scrape Emails From Webpages import re import sys from requests_html import HTMLSession comment add ability to crawl full webpage comment multi threaded print string [*] Dead1's Webpage Email Scraper v1.1 if length argv > 1 begin set url = argv at ...
#!/bin/python # deadscrape.py # author: dead1 # Scrape Emails From Webpages import re import sys from requests_html import HTMLSession # add ability to crawl full webpage # multi threaded print("[*] Dead1's Webpage Email Scraper v1.1") if len(sys.argv) > 1: url = sys.argv[1] print("[*] Scraping Webpage: " + url) els...
Python
zaydzuhri_stack_edu_python
function get_user_input n begin set user_input = string set valid_inputs = list comprehension x for x in range 1 n set invalid_input = string Invalid input while not user_input begin try begin set user_input = integer input string Select a number: end except any begin print invalid_input end try else begin if user_inp...
def get_user_input(n): user_input = "" valid_inputs = [x for x in range(1, n)] invalid_input = "Invalid input" while not user_input: try: user_input = int(input("Select a number: ")) except: print(invalid_input) else: if user_input not in valid...
Python
nomic_cornstack_python_v1
comment Used sources: terokarvinen.com and his course "Python Web Service From Idea to Production" from flask import Flask , render_template , redirect from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms.ext.sqlalchemy.orm import model_form set app = call Flask __name__ set secret_key =...
# Used sources: terokarvinen.com and his course "Python Web Service From Idea to Production" from flask import Flask, render_template, redirect from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms.ext.sqlalchemy.orm import model_form app = Flask(__name__) app.secret_key = "CohlahT9chie...
Python
zaydzuhri_stack_edu_python
function zoobot_subject_assistant_export_to_kade self export_id access_token begin print string [Subject Assistant] Exporting to KaDE Zoobot Prediction Service try begin set export = get objects pk=export_id set target_filename = string catalogues/ { call env_string } /zoobot-subject-assistant- { subject_set_id } -expo...
def zoobot_subject_assistant_export_to_kade( self, export_id, access_token, ): print('[Subject Assistant] Exporting to KaDE Zoobot Prediction Service') try: export = KadeSubjectAssistantExport.objects.get(pk=export_id) target_filename = f'catalogues/{kade_service.env_string()}/zoob...
Python
nomic_cornstack_python_v1
function __init__ self path=string pkb_matrix_sept2013-2 begin set db = call loadDB path call reset set termsToProc = list end function
def __init__(self, path='pkb_matrix_sept2013-2'): self.db = self.loadDB(path) self.reset() self.termsToProc = []
Python
nomic_cornstack_python_v1
comment coding=utf-8 comment This Source Code Form is subject to the terms of the Mozilla Public comment License, v. 2.0. If a copy of the MPL was not distributed with this comment file, You can obtain one at http://mozilla.org/MPL/2.0/. import shutil import mock import pytest from callee import Contains from conftest ...
# coding=utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import shutil import mock import pytest from callee import Contains from .conftest import git_out, search...
Python
jtatman_500k
function kill_thread coro begin comment Collect all coroutines in the delegation stack. set coros = list coro while is instance threads at coro Delegated begin set coro = child append coros coro end comment Complete each coroutine from the top to the bottom of the comment stack. for coro in reversed coros begin call co...
def kill_thread(coro): # Collect all coroutines in the delegation stack. coros = [coro] while isinstance(threads[coro], Delegated): coro = threads[coro].child coros.append(coro) # Complete each coroutine from the top to the bottom of the # stack. ...
Python
nomic_cornstack_python_v1
function workers_ready self qty=none begin set agents = call agents_status if any list comprehension a at string state != string RUNNING for a in agents begin return false end if qty and length agents != qty begin return false end return true end function
def workers_ready(self, qty=None): agents = self.agents_status() if any([a['state'] != 'RUNNING' for a in agents]): return False if qty and len(agents) != qty: return False return True
Python
nomic_cornstack_python_v1
comment Using a custom pyaudio library: comment https://github.com/intxcc/pyaudio_portaudio import pyaudio import audioop import time class AudioReader begin comment device 17 is default for me function __init__ self device_id=17 chunk=1024 begin set p = call PyAudio set _device_id = device_id set _chunk = chunk set _d...
# Using a custom pyaudio library: # https://github.com/intxcc/pyaudio_portaudio import pyaudio import audioop import time class AudioReader(): def __init__(self, device_id=17, chunk=1024): # device 17 is default for me p = pyaudio.PyAudio() self._device_id = device_id self._chunk = chunk...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- import cv2 as cv import numpy as np from matplotlib import pyplot as plt comment 读取图像 comment img = cv.imread("Pillow\\test.jpg") set img = call imread string Opencv/openImg.jpg comment print(img) comment 获取行列处的 B G R 值 grey返回灰度值 set px = img at tuple 100 100 co...
#!/usr/bin/env python # -*- coding:utf-8 -*- import cv2 as cv import numpy as np from matplotlib import pyplot as plt # 读取图像 # img = cv.imread("Pillow\\test.jpg") img = cv.imread("Opencv/openImg.jpg") # print(img) # 获取行列处的 B G R 值 grey返回灰度值 px = img[100, 100] # 单独获取RGB值 blue = img[100, 100, 0] green = img[100, 100, ...
Python
zaydzuhri_stack_edu_python
function get_name_error_sugg type_ value frame begin assert is subclass type_ NameError assert length args == 1 set tuple error_msg = args set error_re = if expression is subclass type_ UnboundLocalError then UNBOUNDERROR_RE else NAMENOTDEFINED_RE set match = match error_re error_msg if match begin set tuple name = cal...
def get_name_error_sugg(type_, value, frame): assert issubclass(type_, NameError) assert len(value.args) == 1 error_msg, = value.args error_re = UNBOUNDERROR_RE if issubclass(type_, UnboundLocalError) \ else NAMENOTDEFINED_RE match = re.match(error_re, error_msg) if match: name, ...
Python
nomic_cornstack_python_v1
string num line goes from -inf to inf bunch of segs come in at random seg = ---- 0-4 seg2 = -- 1-3 seg3 = --- 6-9 is there a way to ensure 4-6 doesn't come in segs = [[0,4],[5,9],[6,9][8,13],[14,16]] sort and then update boundaries as i process segs this will work, but what can i change? Dissect the parts and see where...
''' num line goes from -inf to inf bunch of segs come in at random seg = ---- 0-4 seg2 = -- 1-3 seg3 = --- 6-9 is there a way to ensure 4-6 doesn't come in segs = [[0,4],[5,9],[6,9][8,13],[14,16]] sort and then update boundaries as i process segs this will work, but what can i change? Dissect the parts and see whe...
Python
zaydzuhri_stack_edu_python
function push self data queues create=true verify=true expand=false begin comment Wrap the queues for queue iteration if is instance queues str begin set queues = list queues end comment Verify that the user args are correct if verify begin comment Check queues arg type call _verify_queue_arg queues comment Check for m...
def push(self, data, queues: (str, list, tuple), create: bool = True, verify: bool = True, expand: bool = False) -> None: # Wrap the queues for queue iteration if isinstance(queues, str): queues = [queues] # Verify tha...
Python
nomic_cornstack_python_v1
class Solution begin function eraseOverlapIntervals self intervals begin set intervals = sorted intervals key=lambda x -> x at 1 set num = 0 set cur_end = decimal string -inf for i in range length intervals begin if intervals at i at 0 >= cur_end begin set num = num + 1 set cur_end = intervals at i at 1 end end return ...
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals = sorted(intervals, key=lambda x: x[1]) num = 0 cur_end = float('-inf') for i in range(len(intervals)): if intervals[i][0] >= cur_end: num += 1 cu...
Python
zaydzuhri_stack_edu_python
function sigma G corpus featureset_name B=none **kwargs begin string Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_) for all of the nodes in a :class:`.GraphCollection`\. You can set parameters for burstness estimation using ``kwargs``: ========= ================================================...
def sigma(G, corpus, featureset_name, B=None, **kwargs): """ Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_) for all of the nodes in a :class:`.GraphCollection`\. You can set parameters for burstness estimation using ``kwargs``: ========= ================================...
Python
jtatman_500k
function _resolve_join_columns left_table right_table indices begin return list comprehension call merge_columns columns at li columns at ri for tuple li ri in indices end function
def _resolve_join_columns(left_table, right_table, indices): return [ merge_columns(left_table.columns[li], right_table.columns[ri]) for li, ri in indices ]
Python
nomic_cornstack_python_v1
function predict_density model Xtest feature=0 data_gen_fun=none mean=false density=false burnin=0 MC=none save=none begin try begin import matplotlib.pyplot as plt end except any begin raise call ImportError string cannot import matplotlib end set boundl = min y at tuple slice : : feature set boundu = max y at tupl...
def predict_density(model, Xtest, feature=0, data_gen_fun=None, mean=False, density=False, burnin=0, MC=None, save=None): try: import matplotlib.pyplot as plt except: raise ImportError('cannot import matplotlib') boundl = np.min(model.y[:, feature]) boundu = np.max(model.y[:, feature]) ...
Python
nomic_cornstack_python_v1
import statistics from statistics import mean , stdev set scores = list 97 83 64 29 59 28 84 72 set mean_score = mean scores set standard_deviation = call stdev scores function standard_score x begin return 50 + 10 * x - mean_score / standard_deviation end function for i in range 10 100 10 begin print call standard_sco...
import statistics from statistics import mean, stdev scores = [97, 83, 64, 29, 59, 28, 84, 72] mean_score = mean(scores) standard_deviation = stdev(scores) def standard_score(x): return 50 + 10 * (x - mean_score)/standard_deviation for i in range(10, 100, 10): print(standard_score(i))
Python
zaydzuhri_stack_edu_python
function extract fileobj keywords comment_tags options begin comment this should be an array of objects {"name" : "Theme Name"} set theme_settings = load json fileobj for theme_obj in theme_settings begin comment we need to yield lineno, message, comments yield tuple 0 string theme_obj at string name list end end func...
def extract(fileobj, keywords, comment_tags, options): # this should be an array of objects {"name" : "Theme Name"} theme_settings = json.load(fileobj); for theme_obj in theme_settings: # we need to yield lineno, message, comments yield 0, "", theme_obj['name'], list()
Python
nomic_cornstack_python_v1
from numpy import sqrt import time class Node begin function __init__ self data parent gScore hScore begin set data = data set size = integer square root length data set parent = parent set gScore = gScore set fScore = hScore end function function generateChildren self begin set emptyTileIndex = index data 0 comment -s...
from numpy import sqrt import time class Node: def __init__(self,data,parent,gScore,hScore): self.data = data self.size = int(sqrt(len(data))) self.parent = parent self.gScore = gScore self.fScore = hScore def generateChildren(self): emptyTileIndex = self.data.i...
Python
zaydzuhri_stack_edu_python
import sys function fix line time begin set result = join string : generator expression string %02d % integer t for t in split time string : if strip result != strip time begin write lines stderr time end return result end function if __name__ == string __main__ begin for line in open argv at 1 string r begin set split...
import sys def fix(line, time): result = ':'.join( '%02d' % (int(t,)) for t in time.split(':') ) if result.strip() != time.strip(): sys.stderr.writelines(time) return result if __name__ == "__main__": for line in open(sys.argv[1], 'r'): split_line = line.split('\t')
Python
zaydzuhri_stack_edu_python
function onet_process self image boxes height width begin set data = call __padding image boxes height width return data end function
def onet_process(self, image, boxes, height, width): data = self.__padding(image, boxes, height, width) return data
Python
nomic_cornstack_python_v1
function defineMenu begin from import Menu_MC_pp_v7 from TriggerMenu.l1.Lvl1Flags import Lvl1Flags call defineMenu set thresholds = thresholds + list set items = items + list string L1_RD2_BGRP14 string L1_RD3_BGRP15 comment for running high rate tests in secondary CTP partitions comment -----------------------------...
def defineMenu(): from . import Menu_MC_pp_v7 from TriggerMenu.l1.Lvl1Flags import Lvl1Flags Menu_MC_pp_v7.defineMenu() Lvl1Flags.thresholds += [ ] Lvl1Flags.items += [ # for running high rate tests in secondary CTP partitions 'L1_RD2_BGRP14', 'L1_RD3_BGRP15', ...
Python
nomic_cornstack_python_v1
function indexes self begin return call FeatureCoverage_indexes self end function
def indexes(self): return _ilwisobjects.FeatureCoverage_indexes(self)
Python
nomic_cornstack_python_v1
comment min and max in a list set l = list 2 3 4 5 - 1 222 sort l print l at 0 string min print l at - 1 string max
#min and max in a list l=[2,3,4,5,-1,222] l.sort() print(l[0],"min") print(l[-1],"max")
Python
zaydzuhri_stack_edu_python
function read_txt INPUT begin set raw = open INPUT string r set reader = reader raw set allRows = list comprehension row for row in reader set data = list comprehension i at 0 for i in allRows return data end function
def read_txt(INPUT): raw = open(INPUT, "r") reader = csv.reader(raw) allRows = [row for row in reader] data = [i[0] for i in allRows] return data
Python
nomic_cornstack_python_v1
function multivar_pca x create_plots=true begin string Validate Gaussian distribution of input vars using chi² tests from scipy.stats import chisquare , chi2 from sklearn.decomposition import pca from math import pi for x_line in range shape at 1 begin set tuple hist_x bins_x = call histogram x at tuple slice : : x_...
def multivar_pca(x, create_plots=True): ''' Validate Gaussian distribution of input vars using chi² tests ''' from scipy.stats import chisquare, chi2 from sklearn.decomposition import pca from math import pi for x_line in range(x.shape[1]): hist_x, bins_x = histogram(x[:, x_line], False) ...
Python
nomic_cornstack_python_v1
comment cython: language_level=3 set test = lambda x -> x * 2 print string resultat: call test 5
#cython: language_level=3 test = lambda x: x*2 print("resultat:", test(5))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on 2016. 10. 9. Input Format https://www.hackerrank.com/challenges/maximize-it comment ,, set input_lists = list list 1 2 list 3 4 5 list 6 7 print string classic Method input_lists comment pick_list set out_list = list for layer in range 0 length input_lists begin set work...
# -*- coding: utf-8 -*- ''' Created on 2016. 10. 9. Input Format https://www.hackerrank.com/challenges/maximize-it ''' #,, input_lists = [[1,2],[3,4,5],[6,7]] print('classic Method',input_lists) #pick_list out_list = [] for layer in range(0,len(input_lists)): work_list = [] if...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self val=none children=none begin set val = val set children = children or list end function end class function postorder root begin set result = list if not root begin return result end set stk = list root while stk begin set current = pop stk append result val for child in childre...
class Node: def __init__(self, val=None, children=None): self.val = val self.children = children or [] def postorder(root): result = [] if not root: return result stk = [root] while stk: current = stk.pop() result.append(current.val) ...
Python
jtatman_500k
from sympy import var , simplify , S , bernoulli , binomial , zoo , Rational , factor , factor_list , numer , denom variance string p function Vt x t=variance string p begin string Computes the t-adic valuation of a polynomial x if x == 0 begin return 99999 end for L in call factor_list x at 1 begin if L at 0 == t begi...
from sympy import var, simplify, S, bernoulli, binomial, zoo, Rational, factor, factor_list, numer, denom var('p') def Vt(x, t=var('p')): """ Computes the t-adic valuation of a polynomial x""" if x == 0: return 99999 for L in factor_list(x)[1]: if L[0] == t: return L[1] retu...
Python
zaydzuhri_stack_edu_python
import sys import shlex import csv function quote_aware_space_split inLine begin comment is there a clean way to to it? if version_info >= tuple 3 0 begin return split shlex strip inLine end return list comprehension decode item string utf-8 for item in split shlex encode strip inLine string utf-8 end function function...
import sys import shlex import csv def quote_aware_space_split(inLine): if sys.version_info >= (3, 0): # is there a clean way to to it? return shlex.split(inLine.strip()) return [item.decode('utf-8') for item in shlex.split(inLine.strip().encode('utf-8'))] def quote_aware_comma_split(string): if...
Python
zaydzuhri_stack_edu_python
from __future__ import annotations import uuid function wrap_tuple x begin string Convierte a tuplas if is instance x tuple begin return x end return tuple x end function function unwrap_tuple x begin string Si tiene un solo elemento, retorna ese elemento, caso contrario retornas la tupla if length x == 1 begin return ...
from __future__ import annotations import uuid def wrap_tuple(x: float | tuple[float]) -> tuple[float]: """ Convierte a tuplas """ if isinstance(x, tuple): return x return (x,) def unwrap_tuple(x: float | tuple[float]) -> float: """ Si tiene un solo elemento, retorna ese elemento...
Python
zaydzuhri_stack_edu_python
function score self begin return _score end function
def score(self): return self._score
Python
nomic_cornstack_python_v1