code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Node begin function __init__ self value parent=none begin set _value = value set _parent = parent set _left = none set _right = none set _traverse_func = lambda v -> print string Node value: { v } end function function set_parent self parent begin set _parent = parent set _traverse_func = _traverse_func end funct...
class Node: def __init__(self, value, parent=None): self._value = value self._parent = parent self._left = None self._right = None self._traverse_func = lambda v: print(f'Node value: {v}') def set_parent(self, parent): self._parent = parent self._traverse...
Python
zaydzuhri_stack_edu_python
function _list self uri obj_class=none list_all=false begin string Handles the communication with the API when getting a full listing of the resources managed by this class. set tuple resp resp_body = call _retry_get uri if obj_class is none begin set obj_class = resource_class end set data = resp_body at plural_respon...
def _list(self, uri, obj_class=None, list_all=False): """ Handles the communication with the API when getting a full listing of the resources managed by this class. """ resp, resp_body = self._retry_get(uri) if obj_class is None: obj_class = self.resource_clas...
Python
jtatman_500k
import os import pandas as pd import win32com.client as win32 from datetime import datetime class PathBuilder extends object begin function __init__ self folder file begin set folder = folder set file = file end function function build self begin set current_path = directory name path absolute path path __file__ set fi...
import os import pandas as pd import win32com.client as win32 from datetime import datetime class PathBuilder(object): def __init__(self, folder, file) -> None: self.folder = folder self.file = file def build(self): current_path = os.path.dirname(os.path.abspath(__file__)) fil...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment ------------------------------- comment projects/collatz/TestCollatz.py comment Copyright (C) 2011 comment Glenn P. Downing comment ------------------------------- string To test the program: % python TestCollatz.py > TestCollatz.py.out % chmod ugo+x TestCollatz.py % TestCollatz.py ...
#!/usr/bin/env python # ------------------------------- # projects/collatz/TestCollatz.py # Copyright (C) 2011 # Glenn P. Downing # ------------------------------- """ To test the program: % python TestCollatz.py > TestCollatz.py.out % chmod ugo+x TestCollatz.py % TestCollatz.py > TestCollatz.py.out """ ...
Python
zaydzuhri_stack_edu_python
function extractHiddenFormElts self formBody begin set hiddenFldRE = compile string <input.*?type="hidden".*?> M ? I ? S set hiddenFldNameRE = compile string name="(.*?)"[ >] M ? I set hiddenFldValueRE = compile string value="(.*?)"[ >] M ? I comment find each hidden element set hiddenFldTags = find all formBody set hi...
def extractHiddenFormElts(self, formBody): hiddenFldRE = re.compile('<input.*?type="hidden".*?>', re.M|re.I|re.S) hiddenFldNameRE = re.compile('name="(.*?)"[ >]', re.M|re.I) hiddenFldValueRE = re.compile('value="(.*?)"[ >]', re.M|re.I) # find each hidden element hiddenFldT...
Python
nomic_cornstack_python_v1
function ingest_project project_id version=none begin set container_path = project_id if version begin set container_path = format string {}v{} container_path string version end call fedora_post container_path set project_meta = call format_metadata_for_fedora project_id version=version set res = call fedora_update con...
def ingest_project(project_id, version=None): container_path = project_id if version: container_path = '{}v{}'.format(container_path, str(version)) fedora_post(container_path) project_meta = format_metadata_for_fedora(project_id, version=version) res = fedora_update(container_path, project_m...
Python
nomic_cornstack_python_v1
function tom_text_rendering begin comment turn the file-specific rendering on set g_tom_text_rendering at string on = true comment we need latex and unicode to be safe call rc string text usetex=true string make the normal font Helvetica : stackoverflow.com/questions/11367736/matplotlib-consistent-font-using-latex set ...
def tom_text_rendering(): # turn the file-specific rendering on g_tom_text_rendering['on'] = True # we need latex and unicode to be safe mpl.rc('text', usetex=True) """ make the normal font Helvetica : stackoverflow.com/questions/11367736/matplotlib-consistent-font-using-latex """ ...
Python
nomic_cornstack_python_v1
function _get_compile_components self compile_obj accelerators=tuple begin comment get includes set includes = call _get_includes includes accelerators set inc_flags = call _insert_prefix_to_list includes string -I comment Get dependencies (.o/.a) set m_code = call _get_dependencies extra_modules accelerators comment G...
def _get_compile_components(self, compile_obj, accelerators = ()): # get includes includes = self._get_includes(compile_obj.includes, accelerators) inc_flags = self._insert_prefix_to_list(includes, '-I') # Get dependencies (.o/.a) m_code = self._get_dependencies(compile_obj.ext...
Python
nomic_cornstack_python_v1
function generateBirthDates np begin for i in range 0 100 10 begin set rng = string i + string - + string i + 10 - 1 set perc = ageRange at rng for j in range 0 round perc * np / 100 begin set year = random choice range 2014 - i + 10 2014 - i set month = random choice range 1 13 set day = random choice range 1 29 set b...
def generateBirthDates (np) : for i in range(0, 100, 10) : rng = str(i)+"-"+str(i+10-1) perc = ageRange[rng] for j in range (0, round((perc*np)/100)) : year = random.choice(range(2014-(i+10), 2014-i)) month = random.choice(range(1, 13)) day = random.choice...
Python
nomic_cornstack_python_v1
function compile_relax database mod target params begin comment pylint: disable=import-outside-toplevel from tvm.relax.transform import BindParams , MetaScheduleApplyDatabase from tvm.relax import build as relax_build comment pylint: enable=import-outside-toplevel if not is instance target Target begin set target = cal...
def compile_relax( database: Database, mod: IRModule, target: Union[Target, str], params: Optional[Dict[str, NDArray]], ) -> "relax.Executable": # pylint: disable=import-outside-toplevel from tvm.relax.transform import BindParams, MetaScheduleApplyDatabase from tvm.relax import build as rela...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment countasync.py string Take the code from wait_n and alter it into a new function task_wait_n. The code is nearly identical to wait_n except task_wait_random is being called. import asyncio import random from typing import List set task_wait_random = task_wait_random async function t...
#!/usr/bin/env python3 # countasync.py """ Take the code from wait_n and alter it into a new function task_wait_n. The code is nearly identical to wait_n except task_wait_random is being called. """ import asyncio import random from typing import List task_wait_random = __import__('3-tasks').task_wait_random async de...
Python
zaydzuhri_stack_edu_python
function clearModel self begin set cells = zeros tuple 50 86 set aliveCells = sum cells == 1 set generation = 0 return cells end function
def clearModel(self): self.cells = np.zeros((50,86)) self.aliveCells = np.sum(self.cells == 1) self.generation = 0 return self.cells
Python
nomic_cornstack_python_v1
comment This is a bot for scraping text data from mIRC channels comment This is meant to automate the task of receiving MGRS grid data, comment Decoding the 6,8, or 10 digit MGRS into a LAT/LONG comment Encoding that LAT/LONG data in an XML string comment And finally, pushing that XML string to a socket where it can be...
# This is a bot for scraping text data from mIRC channels # This is meant to automate the task of receiving MGRS grid data, # Decoding the 6,8, or 10 digit MGRS into a LAT/LONG # Encoding that LAT/LONG data in an XML string # And finally, pushing that XML string to a socket where it can be used # To make a blip ap...
Python
zaydzuhri_stack_edu_python
string @PETER HALLDESTAM, 2020 Construction and training of a neural network. Easy to make changes to any parameters and most importantly to implements different structures. from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping , ModelCheckpoint import numpy as np import sys ...
""" @PETER HALLDESTAM, 2020 Construction and training of a neural network. Easy to make changes to any parameters and most importantly to implements different structures. """ from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint import numpy ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*-coding:utf-8-*- string 全局变量和局部变量 全局变量和局部变量同时存在的时候 选择局部变量 comment 全局变量 set name = string xiaobao function f1 begin comment 对全局变量进行一个修正 global name set name = string li print name end function call f1 comment def f2(): comment # 局部变量 comment name='admin' comment print(name) commen...
#! /usr/bin/env python #-*-coding:utf-8-*- ''' 全局变量和局部变量 全局变量和局部变量同时存在的时候 选择局部变量 ''' # 全局变量 name ='xiaobao' def f1(): # 对全局变量进行一个修正 global name name ='li' print(name) f1() # def f2(): # # 局部变量 # name='admin' # print(name) # f2()
Python
zaydzuhri_stack_edu_python
function plot_contact_maps self scaling_factor=10.0 filename=string contact_map.pdf begin import matplotlib as mpl call use string Agg import matplotlib.pylab as pl import matplotlib.gridspec as gridspec call get_number_of_residues rmf_A comment Determine the number of residues per protein set tot = 0 set nres = dict ...
def plot_contact_maps(self, scaling_factor=10., filename="contact_map.pdf"): import matplotlib as mpl mpl.use("Agg") import matplotlib.pylab as pl import matplotlib.gridspec as gridspec self.get_number_of_residues(self.rmf_A) # Determine the ...
Python
nomic_cornstack_python_v1
string cycle.py The Cycle class represents a data type for * determining whether an undirected graph has a simple cycle. * The has_cycle operation determines whether the graph has * a cycle and, if so, the cycle operation returns one. * * This implementation uses depth-first search. * The constructor takes Theta(V + E)...
""" cycle.py The Cycle class represents a data type for * determining whether an undirected graph has a simple cycle. * The has_cycle operation determines whether the graph has * a cycle and, if so, the cycle operation returns one. * * This implementation uses depth-first search. * The constructor takes Thet...
Python
zaydzuhri_stack_edu_python
comment leters and second helf in upper letters comment if the length of str not slicing in helf comment the lower letters small in one from the upper leters
# leters and second helf in upper letters #### if the length of str not slicing in helf #### the lower letters small in one from the upper leters
Python
zaydzuhri_stack_edu_python
comment Button, Tk, Entry, StringVar from tkinter import * comment globally variable set expression = string comment combine key inputs into expression then set to String Variable named equation. ref ln61/62 function press num begin comment re-define the global variable global expression comment concatenate strings se...
from tkinter import * # Button, Tk, Entry, StringVar # globally variable expression = "" # combine key inputs into expression then set to String Variable named equation. ref ln61/62 def press(num): # re-define the global variable global expression # concatenate strings expression = express...
Python
zaydzuhri_stack_edu_python
comment 这是一个稍微复杂一些的加解密算法,这套算法将不再拥有确定的规则组,替换规则将基于所关联的密码生成,不提供密码将无法解密文本。 comment 该算法安全性相对更高,但也需要更复杂的处理程序。 import random comment 将密码处理生成唯一的替换规则 function PasswordHandle password begin set replaceTextGroup = dict string 0 list ; string 1 list ; string list set passwordGroup = list set num = 0 for i in password begin se...
### # 这是一个稍微复杂一些的加解密算法,这套算法将不再拥有确定的规则组,替换规则将基于所关联的密码生成,不提供密码将无法解密文本。 # 该算法安全性相对更高,但也需要更复杂的处理程序。 ### import random def PasswordHandle(password):#将密码处理生成唯一的替换规则 replaceTextGroup = {"0":[],"1":[]," ":[]} passwordGroup = [] num = 0 for i in password: num += 1 addASCIINum = (...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jul 30 14:21:25 2015 @author: chemistry import numpy as np from matplotlib import pyplot as plt from matplotlib import mlab as mlab set data = load np string FallData/D02-S02-E99-RE10-PFAC99-500k.npz set Nice = data at string Nice set Niceoffset = data at string Niceo...
# -*- coding: utf-8 -*- """ Created on Thu Jul 30 14:21:25 2015 @author: chemistry """ import numpy as np from matplotlib import pyplot as plt from matplotlib import mlab as mlab data = np.load('FallData/D02-S02-E99-RE10-PFAC99-500k.npz') Nice = data['Nice'] Niceoffset = data['Niceoffset'] Fliq = data['Fliq'] x = da...
Python
zaydzuhri_stack_edu_python
comment vocab.py comment A class for storing vocabulary information and encoding words as integers from __future__ import print_function from __future__ import division import numpy as np from collections import Counter class Vocab extends object begin function __init__ self fn zero=none unk=none alpha=0.25 begin strin...
# vocab.py # A class for storing vocabulary information and encoding words as integers from __future__ import print_function from __future__ import division import numpy as np from collections import Counter class Vocab(object): def __init__(self, fn, zero=None, unk=None, alpha=0.25): """ fn shoul...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment coding: UTF-8 import numpy as np import matplotlib.pyplot as plt import math comment データを読み込む set f = open string iris_dataset.txt set data1 = read f close f set lines1 = split data1
#!/usr/bin/python # coding: UTF-8 import numpy as np import matplotlib.pyplot as plt import math #データを読み込む f = open('iris_dataset.txt') data1 = f.read() f.close() lines1 = data1.split()
Python
zaydzuhri_stack_edu_python
function available_selectors self begin return keys _selectors end function
def available_selectors(self): return self._selectors.keys()
Python
nomic_cornstack_python_v1
function test_reset_unknown_counter self begin set resp = put string /counters/ { TEST_COUNTER } /reset assert equal status_code HTTP_404_NOT_FOUND end function
def test_reset_unknown_counter(self): resp = self.app.put(f"/counters/{TEST_COUNTER}/reset") self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
Python
nomic_cornstack_python_v1
function _encode_multipart_formdata self fields files begin set BOUNDARY = call choose_boundary set content = list set fields = fields or dict set files = files or dict for key in fields begin append content string -- + BOUNDARY + string append content string Content-Disposition: form-data; name="%s" % key append co...
def _encode_multipart_formdata(self, fields, files): BOUNDARY = mimetools.choose_boundary() content = [] fields = fields or {} files = files or {} for key in fields: content.append('--' + BOUNDARY + '\r\n') content.append('Content-Disposition: form-data; name="%s"\r\n' % key) ...
Python
nomic_cornstack_python_v1
string @program: ProcessRGB.py @description: 利用Gamma变换处理rgb图像 @author: doubleZ @create: 2019/11/09 import matplotlib.pyplot as plt import matplotlib.image as mpimg from src.GammaTransform.GammaTransform import GammaTransform import numpy as np function process_rgb filename begin set I = call imread filename figure imag...
''' @program: ProcessRGB.py @description: 利用Gamma变换处理rgb图像 @author: doubleZ @create: 2019/11/09 ''' import matplotlib.pyplot as plt import matplotlib.image as mpimg from src.GammaTransform.GammaTransform import GammaTransform import numpy as np def process_rgb(filename): I = mpimg.imread(filename) plt.fig...
Python
zaydzuhri_stack_edu_python
function __integrity_check self begin comment type: () -> None if _cmdows_path is none begin raise call ValueError string No CMDOWS file specified! end end function
def __integrity_check(self): # type: () -> None if self._cmdows_path is None: raise ValueError('No CMDOWS file specified!')
Python
nomic_cornstack_python_v1
import random import sys from socket import * set port = integer argv at 1 set server_socket = call socket AF_INET SOCK_DGRAM comment bind() is used to associate the socket with a specific network interface and port number call bind tuple string port while true begin set rand = random integer 0 10 comment bufsize - Th...
import random import sys from socket import * port = int(sys.argv[1]) server_socket = socket(AF_INET, SOCK_DGRAM) # bind() is used to associate the socket with a specific network interface and port number server_socket.bind(('', port)) while True: rand = random.randint(0, 10) # bufsize - The number of bytes ...
Python
zaydzuhri_stack_edu_python
async function kang args begin set kang_meme = random choice KANGING_STR set user = await call get_me if not username begin set username = first_name end set message = await call get_reply_message set photo = none set emojibypass = false set is_anim = false set emoji = none if message and media begin if is instance med...
async def kang(args): kang_meme = random.choice(KANGING_STR) user = await bot.get_me() if not user.username: user.username = user.first_name message = await args.get_reply_message() photo = None emojibypass = False is_anim = False emoji = None if message and message.media: ...
Python
nomic_cornstack_python_v1
function write_info self begin call add_scalar string Loss loss epoch call add_scalar string Win Rate wins / epoch epoch call add_scalar string Move Time avg_move_time epoch call add_scalar string Number of Moves number_of_moves epoch flush writer end function
def write_info(self): self.writer.add_scalar('Loss', self.loss, self.epoch) self.writer.add_scalar('Win Rate', self.wins/self.epoch, self.epoch) self.writer.add_scalar('Move Time', self.avg_move_time, self.epoch) self.writer.add_scalar('Number of Moves', self.number_of_moves, self.epoch)...
Python
nomic_cornstack_python_v1
function yes_no_none row begin if length row at string planet_classification0 == 0 begin set val = string No end else begin set val = string Yes end return val end function
def yes_no_none(row): if len(row['planet_classification0']) == 0: val = "No" else: val = "Yes" return val
Python
nomic_cornstack_python_v1
function get_state_reward_all self tag begin set tuple p counts = call _get_cluster_distribution_all tag set reward = call _get_KL p set dist = p at 0 * diff np p at 1 set state = call tolist return list state reward counts end function
def get_state_reward_all(self, tag): p, counts = self._get_cluster_distribution_all(tag) reward = self._get_KL(p) dist = p[0] * np.diff(p[1]) state = dist.tolist() return [state, reward, counts]
Python
nomic_cornstack_python_v1
function _start_redash_query self query_id query_params begin set url_inputs = dict string redash_host redash_host ; string query_id query_id set query_url = format REDASH_SUBMIT_QUERY_ENDPOINT keyword url_inputs set resp = post query_url json=query_params headers=headers set resp_json = json resp debug string Response...
def _start_redash_query(self, query_id: int, query_params: Dict) -> Tuple[Any, bool]: url_inputs = {'redash_host': self.redash_host, 'query_id': query_id} query_url = REDASH_SUBMIT_QUERY_ENDPOINT.format(**url_inputs) resp = r.post(query_url, json=query_params, headers=self.headers) resp...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import unittest function extract data begin return list comprehension list split line at 0 integer split line at 1 for line in split data string end function function count_until_loop instructions begin set program_pointer = 0 set pointer_prev_locations = list set accumulator = 0 while pr...
#!/usr/bin/env python3 import unittest def extract(data): return [[line.split()[0], int(line.split()[1])] for line in data.split("\n")] def count_until_loop(instructions): program_pointer = 0 pointer_prev_locations = [] accumulator = 0 while program_pointer not in pointer_prev_locations: ...
Python
zaydzuhri_stack_edu_python
from src.season2021.optimizer import get_best_team_for_GP from src.season2021.config import GPs if __name__ == string __main__ begin comment Your budget at the end of last GP set budget = 103 comment The target GP set GP = string Spain comment Expectation or actual results set expectation = false comment Names of drive...
from src.season2021.optimizer import get_best_team_for_GP from src.season2021.config import GPs if __name__ == '__main__': # Your budget at the end of last GP budget = 103 # The target GP GP = "Spain" # Expectation or actual results expectation = False # Names of drivers and constructors to...
Python
zaydzuhri_stack_edu_python
from enum import Enum class SeverityCategoryCode extends int Enum begin set I : int = 10 set II : int = 7 set III : int = 4 decorator staticmethod function getMember value begin for member in SeverityCategoryCode begin if value == value begin return member end end end function end class
from enum import Enum class SeverityCategoryCode(int,Enum): I:int = 10 II:int = 7 III:int = 4 @staticmethod def getMember(value: int): for member in SeverityCategoryCode: if member.value == value: return member
Python
zaydzuhri_stack_edu_python
set idade = integer input string Digite a idade do seu carro: set resultado = if expression idade <= 3 then string Seu carro é novo else string Seu carro é velho print resultado set num = integer input string Digite um número inteiro maior que 0: print if expression num % 2 == 0 then string Par else string Ímpar
idade = int(input("Digite a idade do seu carro: ")) resultado = 'Seu carro é novo' if idade <= 3 else 'Seu carro é velho' print(resultado) num = int(input('Digite um número inteiro maior que 0: ')) print('Par' if num % 2 == 0 else 'Ímpar')
Python
zaydzuhri_stack_edu_python
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt comment plots intensity fit for MDRE model function plotIntensityFit begin with open string time_series_mdre_relaxation_oscillations.txt string r as file begin set lines = read lines file end set time = list set intensity = list f...
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt # plots intensity fit for MDRE model def plotIntensityFit (): with open("time_series_mdre_relaxation_oscillations.txt", "r") as file: lines = file.readlines() time = [] intensity = [] for line in lines: time....
Python
zaydzuhri_stack_edu_python
function _compare_job_function self sd_employment mo_engagement begin set mo_job_function_id = mo_engagement at string job_function at string user_key set sd_job_position_id = sd_employment at string Profession at string JobPositionIdentifier set is_ok = mo_job_function_id == sd_job_position_id return tuple string job_...
def _compare_job_function(self, sd_employment, mo_engagement): mo_job_function_id = mo_engagement["job_function"]["user_key"] sd_job_position_id = sd_employment["Profession"]["JobPositionIdentifier"] is_ok = mo_job_function_id == sd_job_position_id return "job_function", is_ok
Python
nomic_cornstack_python_v1
function attack self other begin print name string attacks name set damage = strenght * 1.0 - defense print string damage: damage set hp = hp - damage print name + string 's remaining health: hp print string ---------- end function
def attack(self, other): print(self.name, "attacks", other.name) damage = self.strenght*(1.-other.defense) print("damage: ", damage) other.hp -= damage print(other.name+"'s remaining health: ", other.hp,) print("----------")
Python
nomic_cornstack_python_v1
function _get_number_of_hours self begin if date_to begin set DATETIME_FORMAT = string %Y-%m-%d %H:%M:%S set from_dt = string parse time date_from DATETIME_FORMAT set to_dt = string parse time date_to DATETIME_FORMAT set timedelta = to_dt - from_dt set diff_day = decimal seconds / 3600 - break_hour set number_of_hours_...
def _get_number_of_hours(self): if self.date_to: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" from_dt = datetime.strptime(self.date_from, DATETIME_FORMAT) to_dt = datetime.strptime(self.date_to, DATETIME_FORMAT) timedelta = to_dt - from_dt diff_day =(float(ti...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import sys append path string .. from Question_01_10.q2 import Gray set channel = 3 function band_pass_filter _G ratio=0.1 ratio2=0.5 begin set tuple H W _ = shape print H W set y = reshape repeat W H - 1 set x = call tile array range W tuple H 1 comment make filter set _x = x - W // 2 set...
import cv2 import numpy as np import sys sys.path.append("..") from Question_01_10.q2 import Gray channel = 3 def band_pass_filter(_G, ratio = 0.1, ratio2 = 0.5): H, W, _ = _G.shape print(H,W) y = np.arange(H).repeat(W).reshape(H,-1) x = np.tile(np.arange(W), (H,1)) # make filter _x = x - W/...
Python
zaydzuhri_stack_edu_python
from main import db from sqlalchemy import Column , Integer , String , Float , ForeignKey , DECIMAL class Reviewer extends Model begin set __tablename__ = string reviewers set id = call Column Integer primary_key=true autoincrement=true nullable=false set first_name = call Column String nullable=false set last_name = c...
from main import db from sqlalchemy import Column, Integer, String, Float, ForeignKey, DECIMAL class Reviewer(db.Model): __tablename__ = "reviewers" id = Column(Integer, primary_key=True, autoincrement=True, nullable=False) first_name = Column(String, nullable=False) last_name = Column(String, nullabl...
Python
zaydzuhri_stack_edu_python
import plotly import plotly.graph_objs as go import numpy as np import tools.utils set ITERORBIT = 300 set ITERANIM = 300 set rmax = 249230000.0 * 1.1 class PlotManager3D begin string 3D Plot manager based on plotly due to matplotlib's poor 3D performance currently supports : - Plotting of bodies - Plotting of elliptic...
import plotly import plotly.graph_objs as go import numpy as np import tools.utils ITERORBIT = 300 ITERANIM = 300 rmax = 2.4923E+8*1.1 class PlotManager3D: """ 3D Plot manager based on plotly due to matplotlib's poor 3D performance currently supports : - Plotting of bodies - Plotting of elliptica...
Python
zaydzuhri_stack_edu_python
string Ejercicio 3.18: Lectura de los árboles de un parque Definí una función leer_parque(nombre_archivo, parque) que abra el archivo indicado y devuelva una lista de diccionarios con la información del parque especificado. La función debe devolver, en una lista un diccionario con todos los datos por cada árbol del par...
""" Ejercicio 3.18: Lectura de los árboles de un parque Definí una función leer_parque(nombre_archivo, parque) que abra el archivo indicado y devuelva una lista de diccionarios con la información del parque especificado. La función debe devolver, en una lista un diccionario con todos los datos por cada árbol del pa...
Python
zaydzuhri_stack_edu_python
import requests import json import sqlite3 comment Make a GET request to the API set response = get requests url set data = json response comment Save the data to a database set conn = call connect string data.db set c = call cursor for item in data begin execute c string INSERT INTO items VALUES (?, ?) tuple item at s...
import requests import json import sqlite3 # Make a GET request to the API response = requests.get(url) data = response.json() # Save the data to a database conn = sqlite3.connect('data.db') c = conn.cursor() for item in data: c.execute("INSERT INTO items VALUES (?, ?)", (item['id'], item['name'])) conn.commit() ...
Python
iamtarun_python_18k_alpaca
function vars self begin return list end function
def vars(self): return []
Python
nomic_cornstack_python_v1
function get_b64_from_data data begin set b64_from_data = none try begin set b64_from_data = base64 encode data end except any begin print string Could not read data to compute base64 string. end return b64_from_data end function
def get_b64_from_data(data): b64_from_data = None try: b64_from_data = base64.b64encode(data) except: print("Could not read data to compute base64 string.") return b64_from_data
Python
nomic_cornstack_python_v1
function _init_extension_classes self begin set _extension_classes = ordered dictionary list comprehension tuple ext_class call ExtensionClassMetadata self ext_class list comprehension option_id for config_option in sorted config_options key=lambda c -> key if call include_config_option_id option_id list comprehension ...
def _init_extension_classes(self): self._extension_classes = OrderedDict( [ ( ext_class, ExtensionClassMetadata( self, ext_class, [ config_optio...
Python
nomic_cornstack_python_v1
comment BUBBLE SORT comment Swap every pair iteratively till array is sorted comment O(n^2) function bubble_sort arr begin function swap i j begin set tuple arr at i arr at j = tuple arr at j arr at i end function set n = length arr set swapped = true set end = n - 1 while swapped begin set swapped = false for i in ran...
### BUBBLE SORT # Swap every pair iteratively till array is sorted # O(n^2) def bubble_sort(arr): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True end = n - 1 while swapped: swapped = False for i in range(end): j ...
Python
zaydzuhri_stack_edu_python
function get_time_bounds self begin set min_time = string %0.20f % call ex_eval string min(time) set max_time = string %0.20f % call ex_eval string max(time) return list string min_time string max_time end function
def get_time_bounds(self): min_time = "%0.20f" % self.table_join.ex_eval("min(time)") max_time = "%0.20f" % self.table_join.ex_eval("max(time)") return [str(min_time), str(max_time)]
Python
nomic_cornstack_python_v1
import nibabel as nib import numpy as np import matplotlib.pyplot as plt import skimage.measure import skimage.morphology import scipy.signal function SegmentationByTH nifty_file Imin Imax begin set img = load nib nifty_file set img_data = call get_data set in_range_values_flags = img_data > Imin ? img_data < Imax set ...
import nibabel as nib import numpy as np import matplotlib.pyplot as plt import skimage.measure import skimage.morphology import scipy.signal def SegmentationByTH(nifty_file, Imin, Imax): img = nib.load(nifty_file) img_data = img.get_data() in_range_values_flags = (img_data > Imin) & (img_data ...
Python
zaydzuhri_stack_edu_python
async function init_integration hass mock_config_entry mock_tailscale begin call add_to_hass hass await call async_setup entry_id await call async_block_till_done return mock_config_entry end function
async def init_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_tailscale: MagicMock ) -> MockConfigEntry: mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() return mock_config_entry
Python
nomic_cornstack_python_v1
function pre_emphasis signal coefficient=0.95 begin set signal = call asarray signal dtype=string float32 return append np signal at 0 signal at slice 1 : : - coefficient * signal at slice : - 1 : end function
def pre_emphasis(signal, coefficient=0.95): signal = np.asarray(signal, dtype='float32') return np.append(signal[0], signal[1:] - coefficient * signal[:-1])
Python
nomic_cornstack_python_v1
from Crypto.PublicKey import RSA from Crypto import Random set random_generator = read set key1 = call generate 1024 random_generator comment key2 = RSA.generate(1024, random_generator) set fmt = string PEM set prv_key = call exportKey fmt set pub_key = call exportKey fmt with open string private.pem string wb as f beg...
from Crypto.PublicKey import RSA from Crypto import Random random_generator = Random.new().read key1 = RSA.generate(1024, random_generator) #key2 = RSA.generate(1024, random_generator) fmt='PEM' prv_key=key1.exportKey(fmt) pub_key=key1.publickey().exportKey(fmt) with open('private.pem', 'wb') as f: f.write(prv_k...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from multiprocessing import Pool , BoundedSemaphore import sys import time import cassandra from cassandra.cluster import Cluster from cassandra.query import tuple_factory , SimpleStatement set lock = call BoundedSemaphore 6 class QueryManager extends object begin set batch_size = 10 functi...
#!/usr/bin/env python from multiprocessing import Pool, BoundedSemaphore import sys import time import cassandra from cassandra.cluster import Cluster from cassandra.query import tuple_factory, SimpleStatement lock = BoundedSemaphore(6) class QueryManager(object): batch_size = 10 def __init__(self, cluste...
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import math import os import random import re import sys comment c=current comment m=maximum or total if __name__ == string __main__ begin set n = integer input set c = 0 set m = 0 while n > 0 begin set r = n % 2 if r == 1 begin set c = c + 1 if c > m begin set m = c end end else begin set c = 0 e...
#!/bin/python3 import math import os import random import re import sys # c=current # m=maximum or total if __name__ == '__main__': n = int(input()) c=0 m=0 while(n>0): r=n%2 if(r==1): c+=1 if(c>m): m=c else: c=0 n=n/...
Python
zaydzuhri_stack_edu_python
for i in ls begin set sum = sum + i end print sum
for i in ls: sum+=i print(sum)
Python
zaydzuhri_stack_edu_python
function run_file self path all_errors_exit=true begin set path = call fixpath path with call handling_errors all_errors_exit begin set module_vars = call run_file path update vars module_vars call store string from + base name path path + string import * end end function
def run_file(self, path, all_errors_exit=True): path = fixpath(path) with self.handling_errors(all_errors_exit): module_vars = run_file(path) self.vars.update(module_vars) self.store("from " + os.path.basename(path) + " import *")
Python
nomic_cornstack_python_v1
function shared_folder_change_members_inheritance_policy_details cls val begin return call cls string shared_folder_change_members_inheritance_policy_details val end function
def shared_folder_change_members_inheritance_policy_details(cls, val): return cls('shared_folder_change_members_inheritance_policy_details', val)
Python
nomic_cornstack_python_v1
from django.db import models comment Create your models here. class CountryModel extends Model begin set Code = call CharField max_length=2 set Name = call TextField end class class TestModel extends Model begin set name = call CharField max_length=100 set test = call TextField end class class AirportModel extends Mode...
from django.db import models # Create your models here. class CountryModel(models.Model): Code = models.CharField(max_length=2) Name = models.TextField() class TestModel(models.Model): name = models.CharField(max_length=100) test = models.TextField() class AirportModel(models.Model): Id = models...
Python
zaydzuhri_stack_edu_python
function IsStrobogrammatic n begin set i = 0 set j = length n - 1 while i <= j begin if n at i == n at j begin if n at i not in list string 1 string 0 string 8 begin return false end end else if n at i != string 6 or n at j != string 9 and n at i != string 9 or n at j != string 6 begin return false end set i = i + 1 se...
def IsStrobogrammatic(n): i = 0 j = len(n) - 1 while i <= j: if n[i] == n[j]: if n[i] not in ['1', '0', '8']: return False else: if n[i] != '6' or n[j] != '9' and (n[i] != '9' or n[j] != '6'): return False i += 1 j -= 1 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment This script takes one filename as argument and opens a openwith gtk window import sys import os import subprocess import mimetypes import gi call require_version string Gtk string 3.0 from gi.repository import Gtk , Gdk comment home = os.getenv("HOME") class myWindow extends Window ...
#!/usr/bin/env python # This script takes one filename as argument and opens a openwith gtk window import sys import os import subprocess import mimetypes import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk #home = os.getenv("HOME") class myWindow(Gtk.Window): def __init__(self): ...
Python
zaydzuhri_stack_edu_python
function deallocateAllFlags self pluginName begin pass end function
def deallocateAllFlags(self, pluginName): pass
Python
nomic_cornstack_python_v1
from __future__ import absolute_import , division , print_function , unicode_literals from six.moves import zip from matplotlib.widgets import Cursor from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.ticker import NullLocator , LinearLocator from matplotlib.colors import Normalize from matplotlib....
from __future__ import (absolute_import, division, print_function, unicode_literals) from six.moves import zip from matplotlib.widgets import Cursor from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.ticker import NullLocator, LinearLocator from matplotlib.colors import Nor...
Python
zaydzuhri_stack_edu_python
function substitute str callback desc=none hints=string caller=string substitute begin function callb cond s begin return call callback s end function if caller == none begin set caller = string substitute end return call substitute2 str callb desc hints=hints caller=caller end function
def substitute(str, callback, desc=None, hints='', caller='substitute'): def callb(cond, s): return callback(s) if caller == None: caller = 'substitute' return substitute2(str, callb, desc, hints=hints, caller=caller)
Python
nomic_cornstack_python_v1
function _make_aeff_hdu cls table_energy table_theta aeff begin set table = call Table dict string ENERG_LO data * unit ; string ENERG_HI data * unit ; string THETA_LO data * unit ; string THETA_HI data * unit ; string EFFAREA data at tuple newaxis slice : : slice : : * unit set header = call Header set header at...
def _make_aeff_hdu(cls, table_energy, table_theta, aeff): table = Table( { "ENERG_LO": table_energy["ETRUE_LO"][np.newaxis, :].data * table_energy["ETRUE_LO"].unit, "ENERG_HI": table_energy["ETRUE_HI"][np.newaxis, :].data * table_energy...
Python
nomic_cornstack_python_v1
function get_topic_prob_in_timestep bow_subset lda_model topic_ID begin comment Progress print name comment Get list of topic probs for docs in this timestep set topic_probs = list comprehension call get_topic_prob bow_doc topic_ID lda_model for bow_doc in bow_subset return call Series topic_probs end function
def get_topic_prob_in_timestep(bow_subset, lda_model, topic_ID): # Progress print(multiprocessing.current_process().name) # Get list of topic probs for docs in this timestep topic_probs = [ get_topic_prob(bow_doc, topic_ID, lda_model) for bow_doc in bow_subset ] ...
Python
nomic_cornstack_python_v1
function make_checkerboard_mask column_distance row_distance column_offset=0 row_offset=0 default=0 value=1 begin string Generate chessboard/checkerboard mask. Parameters ---------- column_distance : int Column distance of the enabled pixels. row_distance : int Row distance of the enabled pixels. column_offset : int Ad...
def make_checkerboard_mask(column_distance, row_distance, column_offset=0, row_offset=0, default=0, value=1): """ Generate chessboard/checkerboard mask. Parameters ---------- column_distance : int Column distance of the enabled pixels. row_distance : int Row distance of...
Python
jtatman_500k
import cv2 as cv import numpy as np set img = call imread string OpenCv/Photos/pic2.jpg set res = call resize img dsize=tuple 500 750 interpolation=INTER_CUBIC set gray = call cvtColor res COLOR_BGR2GRAY image show string Gray gray comment canny = cv.Canny(res, 125, 125) comment cv.imshow('Canny', canny) set tuple ret ...
import cv2 as cv import numpy as np img = cv.imread('OpenCv/Photos/pic2.jpg') res = cv.resize(img, dsize=(500,750), interpolation=cv.INTER_CUBIC) gray = cv.cvtColor(res, cv.COLOR_BGR2GRAY) cv.imshow('Gray', gray) # canny = cv.Canny(res, 125, 125) # cv.imshow('Canny', canny) ret, thresh = cv.threshold(gray, 125, 255...
Python
zaydzuhri_stack_edu_python
function test_sealedbox_enc_dec test_data minion_opts begin comment Store the data with patch string salt.runners.nacl.__opts__ minion_opts create=true begin set ret = call keygen assert string pk in ret assert string sk in ret set pk = ret at string pk set sk = ret at string sk comment Encrypt with pk set encrypted_da...
def test_sealedbox_enc_dec(test_data, minion_opts): # Store the data with patch("salt.runners.nacl.__opts__", minion_opts, create=True): ret = nacl.keygen() assert "pk" in ret assert "sk" in ret pk = ret["pk"] sk = ret["sk"] # Encrypt with pk encrypted_da...
Python
nomic_cornstack_python_v1
function test_delete_pair name pref_names capacity begin set others = list comprehension call Player other list name for other in pref_names for other in others begin set player = call Player name pref_names capacity call delete_pair player other assert set pref_names == set pref_names - set list name assert pref_names...
def test_delete_pair(name, pref_names, capacity): others = [Player(other, [name]) for other in pref_names] for other in others: player = Player(name, pref_names, capacity) delete_pair(player, other) assert set(player.pref_names) == set(pref_names) - set([other.name]) assert ot...
Python
nomic_cornstack_python_v1
function run_method self function_name *parameters begin set output_buffer = none set save_to_output_buffer = true call add_queued_method function_name *parameters while output_buffer == none begin sleep PAUSE_DEBUG_WAIT_TIME end set save_to_output_buffer = false call print_message output_buffer end function
def run_method(self, function_name, *parameters): self.output_buffer = None self.save_to_output_buffer = True self.add_queued_method(function_name, *parameters) while (self.output_buffer == None): time.sleep(self.PAUSE_DEBUG_WAIT_TIME) self.save_to_output_buffer = False self.print_message(se...
Python
nomic_cornstack_python_v1
function __call__ self x begin comment Calculating the WayburnSeader's 3rd function set f = 2 / 3 * x at 0 ^ 3 - 8 * x at 0 ^ 2 + 33 * x at 0 - x at 0 * x at 1 + 5 + x at 0 - 4 ^ 2 + x at 1 - 5 ^ 2 - 4 ^ 2 return f end function
def __call__(self, x): # Calculating the WayburnSeader's 3rd function f = (2 / 3) * x[0] ** 3 - 8 * x[0] ** 2 + 33 * x[0] - x[0] * \ x[1] + 5 + ((x[0] - 4) ** 2 + (x[1] - 5) ** 2 - 4) ** 2 return f
Python
nomic_cornstack_python_v1
class Athlete begin function __init__ self name leaps avg begin set tuple _name _leaps _avg = tuple name leaps avg end function end class function calculate_avg *args begin set numbers = list comprehension decimal value for value in args return sum numbers / length numbers end function set athletes = list while true b...
class Athlete: def __init__(self, name, leaps, avg) : self._name, self._leaps, self._avg = name, leaps, avg def calculate_avg(*args): numbers = [float(value) for value in args] return sum(numbers) / len(numbers) athletes = [] while True: name = input('Atleta: ') if not name: break ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import numpy as np import pandas as pd from math import log import operator import copy import re function loadDataT begin set df = read csv string TreeData.csv set data = call tolist set data_full = data at slice : : set labels = call tolist set labels_full...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from math import log import operator import copy import re def loadDataT(): df=pd.read_csv('TreeData.csv') data=df.values[:11,1:].tolist() data_full=data[:] labels=df.columns.values[1:-1].tolist() labels_full=la...
Python
zaydzuhri_stack_edu_python
comment manhatun from numpy import * set vector1 = call mat list 2.1 2.5 3.8 set vector2 = call mat list 1.0 1.7 6.6 print sum absolute vector1 - vector2 comment 欧式距离 from numpy import * set vector1 = call mat list 2.1 2.5 3.8 set vector2 = call mat list 1.0 1.7 6.6 print square root vector1 - vector2 * T comment 切比雪夫距...
# manhatun from numpy import * vector1 = mat([2.1,2.5,3.8]) vector2 = mat([1.0,1.7,6.6]) print(sum(abs(vector1-vector2))) # 欧式距离 from numpy import * vector1 = mat([2.1,2.5,3.8]) vector2 = mat([1.0,1.7,6.6]) print(sqrt((vector1-vector2)*(vector1-vector2).T)) # 切比雪夫距离 print(abs(vector1-vector2).max) # 夹角余弦 import nump...
Python
zaydzuhri_stack_edu_python
function read_params self config begin set name = config at string name set fields = config at string fields set file = dict set manager = call get_instance for field in items fields begin set file at field at 0 = get manager field at 1 end if string order in config begin set order = list for item in config at string...
def read_params(self, config): self.name = config['name'] fields = config['fields'] self.file = {} manager = FieldManager.get_instance() for field in fields.items(): self.file[field[0]] = manager.get(field[1]) if 'order' in config: self.order = []...
Python
nomic_cornstack_python_v1
function gid exp_gid begin set gid = call getegid if gid != exp_gid or gid != 0 begin return gid end return exp_gid end function
def gid(exp_gid): gid = os.getegid() if gid != exp_gid or gid != 0: return gid return exp_gid
Python
nomic_cornstack_python_v1
function reset self begin close self set cur_item = 0 end function
def reset(self): self.close() self.cur_item = 0
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Project: Logs Analysis - Udacity comment Questions the reporting tool will answer: comment 1. What are the most popular three articles of all time? comment 2. Who are the most popular article authors of all time? comment 3. On which days did more than 1% of requests lead to errors?...
#!/usr/bin/env python3 # # Project: Logs Analysis - Udacity # # Questions the reporting tool will answer: # 1. What are the most popular three articles of all time? # 2. Who are the most popular article authors of all time? # 3. On which days did more than 1% of requests lead to errors? # # import psycopg2 ...
Python
zaydzuhri_stack_edu_python
import unittest import preprocess import utils import pandas as pd import numpy as np set DTYPE_PATH = string ./data/dtypes.csv set DATA_PATH = string ./data/output.csv set dataframe_mock = none set categoricals_mock = none function load_dataset begin set columns_dict = call load_dtypes DTYPE_PATH set columns = sorted ...
import unittest import preprocess import utils import pandas as pd import numpy as np DTYPE_PATH = "./data/dtypes.csv" DATA_PATH = "./data/output.csv" dataframe_mock = None categoricals_mock = None def load_dataset(): columns_dict = utils.load_dtypes(DTYPE_PATH) columns = sorted(columns_dict.keys()) cate...
Python
zaydzuhri_stack_edu_python
function seed self seed=none begin comment to have a different environment at each time (resolve python random problem) set tuple np_random seed1 = call np_random seed set seed2 = call hash_seed seed1 + 1 % 2 ^ 31 return list seed1 seed2 end function
def seed(self, seed=None): # to have a different environment at each time (resolve python random problem) self.np_random, seed1 = seeding.np_random(seed) seed2 = seeding.hash_seed(seed1 + 1) % 2 ** 31 return [seed1, seed2]
Python
nomic_cornstack_python_v1
import urllib.request set page = url open string https://www.flyhiee.com/ set text = decode read page string utf8 comment search for the index location of "Amit" combinationself. set where = find text string Amit set start_text = where + 0 set end_text = start_text + 17 set name = text at slice start_text : end_text : ...
import urllib.request page = urllib.request.urlopen("https://www.flyhiee.com/") text = page.read().decode("utf8") where = text.find("Amit") #search for the index location of "Amit" combinationself. start_text = where + 0 end_text = start_text + 17 name = text[start_text:end_text] #With the start and end index locat...
Python
zaydzuhri_stack_edu_python
function get_store self name=string default begin if name in stores begin return stores at name end try begin set tuple type_ options = store_infos at name end except KeyError begin raise call ConfigurationError string No info for store %s % name end set store = call open_store type_ keyword options set stores at name ...
def get_store(self, name="default"): if name in self.stores: return self.stores[name] try: type_, options = self.store_infos[name] except KeyError: raise ConfigurationError("No info for store %s" % name) store = open_store(type_, **options) ...
Python
nomic_cornstack_python_v1
comment Listdir comment read csv rows comment if date is in range, immediately write to a csv comment all source files will be combined to a single csv import os import csv import sys set input_dir = argv at 1 set output_path = argv at 2 function date_in_range row begin set date = row at 3 comment because dates are alr...
# Listdir # read csv rows # if date is in range, immediately write to a csv # all source files will be combined to a single csv import os import csv import sys input_dir = sys.argv[1] output_path = sys.argv[2] def date_in_range(row): date = row[3] # because dates are already 8601 we can compare them cheaply ...
Python
zaydzuhri_stack_edu_python
comment print("Hello World Typo") import sys comment import pycorrector function typo text begin comment corrected_sent, detail = pycorrector.correct(text) print string Typo Analyse: received: + text + string result: end function if __name__ == string __main__ begin comment print(sys.argv[0]) comment print(sys.argv[1])...
#print("Hello World Typo") import sys # import pycorrector def typo(text): #corrected_sent, detail = pycorrector.correct(text) print("Typo Analyse: received:" + text + "result:") if __name__ == '__main__': #print(sys.argv[0]) #print(sys.argv[1]) typo(sys.argv[1])
Python
zaydzuhri_stack_edu_python
import re set fname = string regex_sum_1197743.txt set fh = open fname set s = 0 for line in fh begin set h1 = find all string [0-9]+ line if length h1 > 0 begin set h2 = length h1 for i in range h2 begin set s = s + integer h1 at i end end end print s
import re fname = 'regex_sum_1197743.txt' fh = open(fname) s = 0 for line in fh: h1 = re.findall('[0-9]+', line) if len(h1) > 0 : h2 = len(h1) for i in range(h2) : s = s + int(h1[i]) print(s)
Python
zaydzuhri_stack_edu_python
function test_save_ignore_fallback_marker self begin set x = call SimpleModel call set_current_language other_lang1 set tr_title = string TITLE_XX call set_current_language other_lang2 comment try fetching, causing an fallback marker call safe_translation_getter string tr_title any_language=true comment Now save. This ...
def test_save_ignore_fallback_marker(self): x = SimpleModel() x.set_current_language(self.other_lang1) x.tr_title = "TITLE_XX" x.set_current_language(self.other_lang2) # try fetching, causing an fallback marker x.safe_translation_getter("tr_title", any_language=True) ...
Python
nomic_cornstack_python_v1
string "" Author: Rajagopal Senthil Kumar Created Date: 07-Sep-2017 Modified Date: 07-Sep-2017 Purpose: Internal library - Encryption and Decryption class import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES class EnDec extends object begin function __init__ self master_key begin set mas...
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Author: Rajagopal Senthil Kumar Created Date: 07-Sep-2017 Modified Date: 07-Sep-2017 Purpose: Internal library - Encryption and Decryption class """""""""""""""""""""""""""""""""""""""""""""""...
Python
zaydzuhri_stack_edu_python
import os import torch import numpy as np import cv2 as cv from torch.utils.data import Dataset from pathlib import Path class CRDataset extends Dataset begin function __init__ self coco_path cell_path begin call __init__ set mpath = coco_path set mlist = list glob mpath string *.jpg set mlen = length mlist set tpath =...
import os import torch import numpy as np import cv2 as cv from torch.utils.data import Dataset from pathlib import Path class CRDataset(Dataset): def __init__(self, coco_path: Path, cell_path: Path): super(CRDataset, self).__init__() self.mpath = coco_path self.mlist = list(self.mpath.g...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import re import string from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split , cross_val_score from sklearn.metrics import accuracy_score , precision_score , recall_scor...
import pandas as pd import numpy as np import re import string from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import accuracy_score, precision_score, recall_score, ...
Python
jtatman_500k
function utility board begin if call winner board == X begin return 1 end else if call winner board == O begin return - 1 end else begin return 0 end end function
def utility(board): if winner(board) == X: return 1 elif winner(board) == O: return -1 else: return 0
Python
nomic_cornstack_python_v1
function init_from_file filename parser=int begin set filename = filename + string . + string PID function __parser_couple s begin set s = replace s string ( string set s = replace s string ) string set ss = split s string , return tuple integer ss at 0 integer ss at 1 end function set p = call PTree set content = call...
def init_from_file(filename, parser=int): filename = filename + "." + str(PID) def __parser_couple(s): s = s.replace("(", "") s = s.replace(")", "") ss = s.split(",") return int(ss[0]), int(ss[1]) p = PTree() content = SList([]) w...
Python
nomic_cornstack_python_v1
function connect_previous self previous_layer begin for neuron in _neurons begin for dest in _neurons begin call add_link string in dest end end end function
def connect_previous(self, previous_layer): for neuron in self._neurons: for dest in previous_layer._neurons: neuron.add_link('in', dest)
Python
nomic_cornstack_python_v1
from sys import stdin function solve s_original k begin comment cache of previously solved positions set cache = dict function solve_inner s begin comment if we hit this in the cache, we've returned to the original point, so obviously not optimal set cache at s = none if string - not in s begin return 0 end set best =...
from sys import stdin def solve(s_original, k): #cache of previously solved positions cache = {} def solve_inner(s): #if we hit this in the cache, we've returned to the original point, so obviously not optimal cache[s] = None if "-" not in s: return 0 ...
Python
zaydzuhri_stack_edu_python
function help_plot begin call open_help_text join path module_dir string help-plot.txt end function
def help_plot(): open_help_text(os.path.join(module_dir, "help-plot.txt"))
Python
nomic_cornstack_python_v1
comment Jeffrey Rodriguez 110733867 import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt comment Interpolation of left side set xl = array list - 1 - 0.75 - 0.5 - 0.25 0 set xr = array list 0 0.25 0.5 0.75 1 comment array of left and right values set xlr = unique append np xl xr print xlr fun...
#Jeffrey Rodriguez 110733867 import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt #Interpolation of left side xl = np.array([-1,-.75,-.5,-.25,0]) xr = np.array([0,.25,.5,.75,1]) xlr = np.unique(np.append(xl,xr)) #array of left and right values print(xlr) def f(x): return (1+25*x**2)**(-1...
Python
zaydzuhri_stack_edu_python
function node_camera_type self begin return _node_camera_type end function
def node_camera_type(self, ): return self._node_camera_type
Python
nomic_cornstack_python_v1