code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
async function async_comprehension begin return list comprehension i for i in call async_generator end function
async def async_comprehension() -> List[float]: return [i async for i in async_generator()]
Python
nomic_cornstack_python_v1
function test_build_image_default_context self mock_docker_environment begin call build_image string Dockerfile.test TEST_IMAGE_NAME context=none call assert_called_with dockerfile=string Dockerfile.test path=call pwd tag=TEST_IMAGE_NAME end function
def test_build_image_default_context(self, mock_docker_environment): build_image("Dockerfile.test", TEST_IMAGE_NAME, context=None) mock_docker_environment.images.build.assert_called_with( dockerfile="Dockerfile.test", path=pwd(), tag=TEST_IMAGE_NAME )
Python
nomic_cornstack_python_v1
function delete_all_from self tablename begin set query = string delete from + tablename try begin execute __cur query commit __conn end except Exception as e begin rollback __conn raise e end end function
def delete_all_from(self,tablename): query = 'delete from ' + tablename try: self.__cur.execute(query) self.__conn.commit() except Exception as e: self.__conn.rollback() raise e
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- set counter = 1 set num = 0 function test_varibale begin global counter for I in tuple 1 2 3 begin set counter = counter + 1 end set num = 10 end function call test_varibale print counter num comment 4 0
# -*- coding: utf-8 -*- counter = 1 num = 0 def test_varibale(): global counter for I in (1, 2, 3): counter += 1 num = 10 test_varibale() print(counter, num) # 4 0
Python
zaydzuhri_stack_edu_python
function lineup_user self userid begin set headers = dict string Content-type string application/x-www-form-urlencoded ; string Accept string text/plain ; string Referer string http:// + domain + string /standings.phtml ; string User-Agent user_agent set req = content set soup = call BeautifulSoup req string html.parse...
def lineup_user(self, userid): headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", 'Referer': 'http://' + self.domain + '/standings.phtml', "User-Agent": user_agent} req = self.session.get('http://' + self.domain + '/playerInfo.phtml?pid=' + user...
Python
nomic_cornstack_python_v1
function run self inpt begin call system string mkdir build set generation = 1 set string = inpt set seen_machines = list set machines = list machine set new_machines = list set divider = join string list string = * 20 while machines begin print divider string GENERATION generation divider for tuple num machine in e...
def run(self, inpt): os.system("mkdir build") generation = 1 self.machine.string = inpt seen_machines = [] machines = [self.machine] new_machines = [] divider = "".join(["="] * 20) while machines: print (divider, "GENERATION", generation, divid...
Python
nomic_cornstack_python_v1
import sys from board import Board from player import Player from move import Move import copy import preview import relay import note import governance import shield import promoted_governance import promoted_preview import promoted_notes import promoted_relay import drive import utils class Game begin string class th...
import sys from board import Board from player import Player from move import Move import copy import preview import relay import note import governance import shield import promoted_governance import promoted_preview import promoted_notes import promoted_relay import drive import utils class Game: """ class ...
Python
zaydzuhri_stack_edu_python
import csv function read_nodes file begin set nodes = list with open file newline=string as csvfile begin set reader = reader csvfile delimiter=string quotechar=string | next reader for row in reader begin comment print(', '.join(row)) if row at 3 != string Россия begin continue end append nodes tuple row at 0 decima...
import csv def read_nodes(file): nodes = [] with open(file, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') next(reader) for row in reader: #print(', '.join(row)) if row[3] != 'Россия': continue nodes...
Python
zaydzuhri_stack_edu_python
function log_warning msg *args **kwargs begin import logging warning msg *args keyword kwargs end function
def log_warning(msg: object, *args: object, **kwargs: Any) -> None: import logging logging.getLogger('netpbmfile').warning(msg, *args, **kwargs)
Python
nomic_cornstack_python_v1
function avail_pawn_moves self rw cl board=current_board begin set allowed_moves = zeros tuple 8 8 if color == string w begin comment Checks if first spot in front is open if rw - 1 >= 0 and board at tuple rw - 1 cl == 0 begin set allowed_moves at tuple rw - 1 cl = 1 comment If first is open, and pawn hasn't moved, als...
def avail_pawn_moves(self, rw, cl, board = current_board): allowed_moves = np.zeros((8,8)) if self.color == 'w': # Checks if first spot in front is open if (rw-1 >= 0) and (board[rw-1, cl] == 0): allowed_moves[rw-1, cl] = 1 # If first ...
Python
nomic_cornstack_python_v1
async function _run self begin await sleep timeout call dispatch name *self.args keyword kwargs end function
async def _run(self): await asyncio.sleep(self.timeout) self.client.dispatch(self.name, *self.args, **self.kwargs)
Python
nomic_cornstack_python_v1
function _format_response self request response encoding begin set rstr = encode dumps response allow_nan=false check_circular=false ensure_ascii=false encoding=encoding encoding comment strict compliance to JSON comment speedup comment allows the result to be a UNICODE object. return rstr end function
def _format_response(self, request, response, encoding): rstr = json.dumps( response, allow_nan=False, # strict compliance to JSON check_circular=False, # speedup ensure_ascii=False, # allows the result to be a UNICODE object. encoding=encoding ...
Python
nomic_cornstack_python_v1
function draw self begin string Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples. set observed_arr = call generate set arr = call inference observed_arr return arr end function
def draw(self): ''' Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = self.noise_sampler.generate() arr = self.inference(observed_arr) return arr
Python
jtatman_500k
function test_get_config_noconfig_node hass test_client begin set app = call mock_http_component_app hass call register router set network = call MagicMock set data at DATA_NETWORK = call MagicMock set node = call MockNode node_id=2 set nodes = dict 2 node set return_value = values set client = yield from call test_cli...
def test_get_config_noconfig_node(hass, test_client): app = mock_http_component_app(hass) ZWaveNodeConfigView().register(app.router) network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values client = yie...
Python
nomic_cornstack_python_v1
function __trading_model self name begin return dict string breakout_with_MA_filter_and_ATR_stop BreakoutMAFilterATRStop ; string plunge_with_ATR_stop_and_profit PlungeATRStopProfit ; string bollinger_bands BollingerBands ; string ma_trend_on_pullback MATrendOnPullback ; string buy_and_hold BuyAndHold ; string ewmac EW...
def __trading_model(self, name): return { 'breakout_with_MA_filter_and_ATR_stop': BreakoutMAFilterATRStop, 'plunge_with_ATR_stop_and_profit': PlungeATRStopProfit, 'bollinger_bands': BollingerBands, 'ma_trend_on_pullback': MATrendOnPullback, 'buy_and_ho...
Python
nomic_cornstack_python_v1
comment Kütüphanelerimiz import ettik import numpy as np import cv2 as cv set img = call imread string smarties.png comment img=cv.VideoCapture(0) set output = copy img comment Resmimizi BGR DAN GRAY E çevirdik set gray = call cvtColor img COLOR_BGR2GRAY set gray = call medianBlur gray 5 comment çemberleri algılamak iç...
#Kütüphanelerimiz import ettik import numpy as np import cv2 as cv img=cv.imread("smarties.png") #img=cv.VideoCapture(0) output=img.copy() #Resmimizi BGR DAN GRAY E çevirdik gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) gray=cv.medianBlur(gray,5) #çemberleri algılamak için circles=cv.HoughCircles(gray,cv.HOUGH_...
Python
zaydzuhri_stack_edu_python
function computador_escolhe_jogada n m begin set p = 1 while p < m begin if n - p % m + 1 == 0 begin return p end else begin set p = p + 1 end end return p end function function usuario_escolhe_jogada n m begin set valido = 0 while valido == 0 begin set p = integer input string Quantas peças você vai tirar? if p > 0 an...
def computador_escolhe_jogada(n,m): p = 1 while (p < m): if ((n-p)%(m+1)==0): return p else: p+=1 return p def usuario_escolhe_jogada(n,m): valido = 0 while (valido == 0): p = int(input("Quantas peças você vai tirar? ")) if (p>0 ...
Python
zaydzuhri_stack_edu_python
function fnu_ir self spectrum begin if not is instance spectrum BasicSpectrum begin raise call ValueError string Input must be a Spectrum end comment work in frequencies call in_nu set nus = call nu set allnu = call location nus x try begin set ifnu = call fnu_nu allnu end except any begin raise call ValueError string ...
def fnu_ir(self, spectrum): if not isinstance(spectrum, BasicSpectrum): raise ValueError("Input must be a Spectrum") # work in frequencies self.in_nu() nus = spectrum.nu() allnu = self.location(nus, self.x) try: ifnu = spectrum.fnu_nu(allnu) ...
Python
nomic_cornstack_python_v1
string 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题...
""" 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这...
Python
zaydzuhri_stack_edu_python
function cov_params_opg self begin return call _cov_params_opg _cov_approx_complex_step _cov_approx_centered end function
def cov_params_opg(self): return self._cov_params_opg(self._cov_approx_complex_step, self._cov_approx_centered)
Python
nomic_cornstack_python_v1
function meters_to_radians_test self begin call assertAlmostEqual call meters_to_radians 3500 0.0004703595114532541 end function
def meters_to_radians_test(self): self.assertAlmostEqual(meters_to_radians(3500), 0.0004703595114532541)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys import subprocess set DEBUG = false function RunCmd cmd begin set output = check output list cmd stderr=STDOUT shell=true end function
#!/usr/bin/env python import sys import subprocess DEBUG = False def RunCmd(cmd): output = subprocess.check_output([cmd], stderr=subprocess.STDOUT, shell=True)
Python
zaydzuhri_stack_edu_python
function interpolate_tow_points self target=none begin set prev_pts = new_pts if target begin comment w/4 set target_length = target end else begin set target_length = interp_dist end set n_pts = length new_pts at 2 set points = copy np new_pts comment Batch up sections for large tows set batch = list set batch_combin...
def interpolate_tow_points(self, target=None): self.prev_pts = self.new_pts if target: target_length = target #w/4 else: target_length = self.interp_dist n_pts = len(self.new_pts[2]) points = np.copy(self.new_pts) # Ba...
Python
nomic_cornstack_python_v1
import re with open string Syllable_dictionary_updated.txt as f ; open string Syllable_dictionary_updated2.txt string w as g begin for line in f begin set match = match string ^(.+) (\d+) (\d+)$ line set word = call group 1 set syll = integer call group 2 set end_syll = integer call group 3 write g format string {} {} ...
import re with open("Syllable_dictionary_updated.txt") as f, open("Syllable_dictionary_updated2.txt", "w") as g: for line in f: match = re.match("^(.+) (\d+) (\d+)$", line) word = match.group(1) syll = int(match.group(2)) end_syll = int(match.group(3)) g.write("{} {} {}\n".fo...
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter import ttk import cine_database set window = call Tk title window string Taquilla MEDINOE PLUS set frame_app = call Frame window width=400 height=600 bg=string red call pack set pelicula = call StringVar set hora = call StringVar set fecha = call StringVar set idioma = call StringVar ...
from tkinter import * from tkinter import ttk import cine_database window = Tk() window.title("Taquilla MEDINOE PLUS") frame_app = Frame(window, width=400, height=600, bg="red") frame_app.pack() pelicula = StringVar() hora = StringVar() fecha = StringVar() idioma = StringVar() def show_data(): pel...
Python
zaydzuhri_stack_edu_python
import json from urllib.request import urlopen function getCountryCity ipAddress begin set response = decode read url open string http://ip-api.com/json/ + ipAddress string utf-8 set responseJson = loads response return list get responseJson string country get responseJson string city end function print call getCountry...
import json from urllib.request import urlopen def getCountryCity(ipAddress): response = urlopen('http://ip-api.com/json/' + ipAddress).read().decode('utf-8') responseJson = json.loads(response) return [responseJson.get('country'), responseJson.get('city')] print(getCountryCity(input('Введите IP: ...
Python
zaydzuhri_stack_edu_python
string Created on May 26, 2018 @author: Thuong import json from pprint import pprint from chuong2.thu_vien import doc_noi_dung_json if __name__ == string __main__ begin set noi_dung = call doc_noi_dung_json string QLCT_1.json set cong_ty = noi_dung at string CONG_TY print string Tên công ty: cong_ty at 0 at string Ten ...
''' Created on May 26, 2018 @author: Thuong ''' import json from pprint import pprint from chuong2.thu_vien import doc_noi_dung_json if __name__ == '__main__': noi_dung = doc_noi_dung_json("QLCT_1.json") cong_ty = noi_dung['CONG_TY'] print('Tên công ty:',cong_ty[0]['Ten']) print('Địa chỉ:...
Python
zaydzuhri_stack_edu_python
comment needed format comment path/to/image.jpg,x1,y1,x2,y2,class_name import numpy as np import cv2 function draw_poly img x1 y1 x2 y2 begin set pts = array list list x1 y1 list x1 y2 list x2 y2 list x2 y1 list x1 y1 int32 set pts = reshape pts tuple - 1 1 2 call polylines img list pts true tuple 0 255 255 end functio...
# needed format # path/to/image.jpg,x1,y1,x2,y2,class_name import numpy as np import cv2 def draw_poly(img, x1, y1, x2, y2): pts = np.array([ [x1, y1], [x1, y2], [x2, y2], [x2, y1], [x1, y1] ], np.int32) pts = pts.reshape((-1, 1, 2)) cv2.polylines(img,[pts], True, (0, 255, 255)) if __name__ == "__main_...
Python
zaydzuhri_stack_edu_python
from pygeo.intersect import intersect , _intersect_ray_with_sphere , _intersect_ray_with_triangle from pygeo.objects import Ray , Sphere , Triangle , Point , Vector import numpy as np comment intersect comment _intersect_ray_with_sphere function test_intersect_ray_and_sphere_with_same_origin begin assert call _intersec...
from pygeo.intersect import ( intersect, _intersect_ray_with_sphere, _intersect_ray_with_triangle, ) from pygeo.objects import Ray, Sphere, Triangle, Point, Vector import numpy as np # intersect # _intersect_ray_with_sphere def test_intersect_ray_and_sphere_with_same_origin(): assert(_intersect_ray_w...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Oct 8 14:32:52 2018 @author: luolei 数据相关性分析 import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import sys append path string ../ from mods.config_loader import config from mods.data_filtering import savitzky_golay_filtering fu...
# -*- coding: utf-8 -*- """ Created on Mon Oct 8 14:32:52 2018 @author: luolei 数据相关性分析 """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import sys sys.path.append('../') from mods.config_loader import config from mods.data_filtering import savitzky_golay_filtering ...
Python
zaydzuhri_stack_edu_python
import sys if __name__ == string __main__ begin set N = integer input set arr = list for _ in range N begin set tuple a b = map int split read line stdin append arr tuple b a end sort arr reverse=true set ans = arr at 0 at 0 - arr at 0 at 1 for i in range 1 N begin if ans > arr at i at 0 begin set ans = arr at i at 0 ...
import sys if __name__ == '__main__': N = int(input()) arr = [] for _ in range(N): a, b = map(int, sys.stdin.readline().split()) arr.append((b, a)) arr.sort(reverse=True) ans = arr[0][0] - arr[0][1] for i in range(1, N): if ans > arr[i][0]: ans = arr[i][0] - ...
Python
zaydzuhri_stack_edu_python
function _set_lsp_cspf self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedClassType base_type=unicode restriction_type=string dict_key restriction_arg=dict string enable dict string value 1 ; string disable dict string value...
def _set_lsp_cspf(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'enable': {'value': 1}, u'disabl...
Python
nomic_cornstack_python_v1
function report xs begin set result = string set total = 0 set countscore = 0 set i = 0 while i < length xs begin set count = 0 set names = list if is instance xs at i int begin set total = total + xs at i set countscore = countscore + 1 set i = i + 1 end if i == length xs begin break end while is instance xs at i st...
def report(xs): result="" total=0 countscore=0 i=0 while i < len(xs): count=0 names=[] if isinstance(xs[i], int): total=total+xs[i] countscore=countscore+1 i=i+1 if i==len(xs): break while isinstance(xs[i], str):...
Python
zaydzuhri_stack_edu_python
from create_db import db , Message from datetime import datetime function update name body begin set message = call Message name=name body=body timestamp=now add session message commit session end function function select begin set message = call order_by call desc return message end function function get_count begin s...
from create_db import db, Message from datetime import datetime def update(name, body): message = Message(name=name, body=body, timestamp=datetime.now()) db.session.add(message) db.session.commit() def select(): message = Message.query.order_by(Message.timestamp.desc()) return message def get_...
Python
zaydzuhri_stack_edu_python
string Methods for finding receptive fields of CNN voxels via least-suqares approximation of model parameters. (The only receptive-field model currently implemented is a gaussian). While this is far from being the most accurate or fastest method of finding CNN voxels, it matches the processes performed in animal/human ...
""" Methods for finding receptive fields of CNN voxels via least-suqares approximation of model parameters. (The only receptive-field model currently implemented is a gaussian). While this is far from being the most accurate or fastest method of finding CNN voxels, it matches the processes performed in animal/human psy...
Python
zaydzuhri_stack_edu_python
function _qr_rectangular_pullback cls Qbar_data Rbar_data A_data Q_data R_data out=none begin if out is none begin raise call NotImplementedError string need to implement that... end set Abar_data = out set A_shp = shape set tuple D P M N = A_shp if M < N begin raise call NotImplementedError string supplied matrix has ...
def _qr_rectangular_pullback(cls, Qbar_data, Rbar_data, A_data, Q_data, R_data, out = None): if out is None: raise NotImplementedError('need to implement that...') Abar_data = out A_shp = A_data.shape D,P,M,N = A_shp if M < N: raise NotImplementedErro...
Python
nomic_cornstack_python_v1
import numpy as np function write_inserts_to_text_file output_path header_statement data_ref begin string Writes sql inserts to a text file :param output_path: file to write to :param header_statement: The first row of the insert statement :param data_ref: parameterized data to write to the file :return: with open outp...
import numpy as np def write_inserts_to_text_file(output_path, header_statement, data_ref): """ Writes sql inserts to a text file :param output_path: file to write to :param header_statement: The first row of the insert statement :param data_ref: parameterized data to write to the file :return...
Python
zaydzuhri_stack_edu_python
function genFirstPop nPos totPlayers masterList popSize=1000 begin comment TODO: replace genWorking team with a for loop that consolidates genRandTeam & findDups into this block set population = list comprehension call genWorkingTeam nPos totPlayers for i in range popSize set population = call getStats population maste...
def genFirstPop(nPos, totPlayers, masterList, popSize=1000): #TODO: replace genWorking team with a for loop that consolidates genRandTeam & findDups into this block population = [genWorkingTeam(nPos, totPlayers) for i in range(popSize)] population = getStats(population, masterList) return population
Python
nomic_cornstack_python_v1
import pygame , sys from pygame.locals import * set CENTER_SCREEN_X = 410 set CENTER_SCREEN_y = 245 set INITIAL_POSITION_ON_MATRIX_I = 0 set INITIAL_POSITION_ON_MATRIX_J = 8 set ANIMATION_DOWN = 1 set ANIMATION_LEFT = 2 set ANIMATION_RIGHT = 3 set ANIMATION_UP = 4 set ANIMATION_STOP = 0 set START_SPRITE_DOWN = 1 set ST...
import pygame, sys from pygame.locals import * CENTER_SCREEN_X = 410 CENTER_SCREEN_y = 245 INITIAL_POSITION_ON_MATRIX_I = 0 INITIAL_POSITION_ON_MATRIX_J = 8 ANIMATION_DOWN = 1 ANIMATION_LEFT = 2 ANIMATION_RIGHT = 3 ANIMATION_UP = 4 ANIMATION_STOP = 0 START_SPRITE_DOWN = 1 START_SPRITE_LEFT = 5 START_SPRITE_RIGHT = 9...
Python
zaydzuhri_stack_edu_python
function itkIsolatedConnectedImageFilterID3ID3_cast *args begin return call itkIsolatedConnectedImageFilterID3ID3_cast *args end function
def itkIsolatedConnectedImageFilterID3ID3_cast(*args): return _itkIsolatedConnectedImageFilterPython.itkIsolatedConnectedImageFilterID3ID3_cast(*args)
Python
nomic_cornstack_python_v1
function lis sequence begin set lis = list comprehension 1 for _ in range length sequence for i in range 1 length sequence begin for j in range 0 i begin if sequence at i > sequence at j and lis at i < lis at j + 1 begin set lis at i = lis at j + 1 end end end set maximum = 0 for i in range length sequence begin set ma...
def lis(sequence): lis = [1 for _ in range(len(sequence))] for i in range (1 , len(sequence)): for j in range(0 , i): if sequence[i] > sequence[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 maximum = 0 for i in range(len(sequence)): maximum = ma...
Python
flytech_python_25k
function add_user self first_name last_name login_name email title=string account_role=string standard_user time_zone=string Pacific Time (US & Canada) can_export=string false can_import=string false has_public_library=string false sso_enabled=string true begin set params = copy locals del params at string self set pa...
def add_user(self, first_name, last_name, login_name, email, title='', account_role='standard_user', time_zone='Pacific Time (US & Canada)', can_export='false', can_import='false', has_public_library='false', sso_enabled='true'): params = locals().copy() del param...
Python
nomic_cornstack_python_v1
function collectPairs mpack multipack=true begin set feats = none set label = list comment Collect all pairs' label and features if multipack begin for dpack in values mpack begin if feats is none begin set feats = data end else begin set feats = vertical stack tuple feats data format=string csr end extend label targe...
def collectPairs(mpack, multipack=True): feats = None label = [] # Collect all pairs' label and features if multipack: for dpack in mpack.values(): if feats is None: feats = dpack.data else: feats = sc.sparse.vstack((feats, dpack.data), fo...
Python
nomic_cornstack_python_v1
function add_member self member cursor=none begin if length call get_current_takes == 149 begin raise MemberLimitReached end if status != string active begin raise InactiveParticipantAdded end call set_take_for member ZERO self cursor=cursor end function
def add_member(self, member, cursor=None): if len(self.get_current_takes()) == 149: raise MemberLimitReached if member.status != 'active': raise InactiveParticipantAdded self.set_take_for(member, ZERO, self, cursor=cursor)
Python
nomic_cornstack_python_v1
function __init__ self begin set _user_map = default dictionary UserNode set _timestamp = 0 end function
def __init__(self): self._user_map = defaultdict(self.UserNode) self._timestamp = 0
Python
nomic_cornstack_python_v1
function dump_packages self package_name=string com.sagas.dss begin set model_reader = call getModelReader set tree_map = call getEntitiesByPackage none none comment print(tree_map) set py_tree_map = dictionary comprehension call trim_prefix k : call to_list vals for tuple k vals in items tree_map for tuple k vals in i...
def dump_packages(self, package_name='com.sagas.dss'): model_reader = oc.delegator.getModelReader() tree_map = model_reader.getEntitiesByPackage(None, None) # print(tree_map) py_tree_map={trim_prefix(k):to_list(vals) for (k,vals) in tree_map.items() } for (k,vals) in py_tree_map....
Python
nomic_cornstack_python_v1
comment 에라토스테네스의 체 알고리즘 function prime n begin set sieve = list true * n set m = integer n ^ 0.5 for i in range 2 m + 1 begin if sieve at i == true begin for j in range i + i n i begin set sieve at j = false end end end return list comprehension i for i in range 2 n if sieve at i == true end function
# 에라토스테네스의 체 알고리즘 def prime(n): sieve = [True]*n m = int(n**0.5) for i in range(2, m+1): if sieve[i] == True: for j in range(i+i, n, i): sieve[j] = False return [i for i in range(2, n) if sieve[i] == True]
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- import sys import datetime import time import os string 对资源进行分析 求出每个文件的最大值 最小值 平均值 处理cpu mem io function analysis stat_type filepath begin print stat_type print filepath set __console__ = stdout set fp = open filepath set fp2 = open string ResourceAnalysis.txt string a set stdout = fp2 set...
# -*- coding: UTF-8 -*- import sys import datetime import time import os ''' 对资源进行分析 求出每个文件的最大值 最小值 平均值 处理cpu mem io ''' def analysis(stat_type,filepath): print(stat_type) print(filepath) __console__=sys.stdout fp=open(filepath) fp2=open("ResourceAnalysis.txt","a") sys.stdout=fp2 begin...
Python
zaydzuhri_stack_edu_python
for _ in range integer input begin set tuple m x y = map int split input set lst = list map int split input set houses = list 0 * 100 set max = x * y for i in lst begin set upper = i + max set lower = i - max if lower < 1 begin set lower = 1 end if upper > 100 begin set upper = 100 end for j in range lower upper + 1 be...
for _ in range(int(input())): m,x,y=map(int,input().split()) lst=list(map(int, input().split())) houses=[0]*100 max=x*y for i in lst: upper=i+max lower=i-max if(lower<1): lower=1 if(upper>100): upper=100 for j in range(lower, upper+1): if(houses[j-1]==0): houses[j-1]=1 print(...
Python
zaydzuhri_stack_edu_python
function probs self np_x debug=false begin set dataset = call DatasetNumpy np_x zeros list length np_x transform=transform set loader = call DataLoader dataset batch_size=128 set probs_list = list if debug begin set loader = call tqdm loader desc=string Probs.. end with no grad begin for tuple x _ in loader begin set ...
def probs(self, np_x, debug=False): dataset = data_utils.DatasetNumpy(np_x, np.zeros([len(np_x)]), transform=self.transform) loader = torch.utils.data.DataLoader(dataset, batch_size=128) probs_list = [] if debug: loader = tqdm.tqdm(loader, desc='Probs..') wit...
Python
nomic_cornstack_python_v1
function RenderGenericRenderer request begin try begin set tuple action renderer_name = split path string / at slice - 2 : : set renderer_cls = call NewPlugin name=renderer_name end except KeyError begin call IncrementCounter string grr_admin_ui_unknown_renderer return call AccessDenied string Error: Renderer %s not ...
def RenderGenericRenderer(request): try: action, renderer_name = request.path.split("/")[-2:] renderer_cls = renderers.Renderer.NewPlugin(name=renderer_name) except KeyError: stats.STATS.IncrementCounter("grr_admin_ui_unknown_renderer") return AccessDenied("Error: Renderer %s not found" % renderer_...
Python
nomic_cornstack_python_v1
function test_period self begin with assert raises ParseException begin call evaluator dict dict string . end with assert raises ParseException begin call evaluator dict dict string 1+. end end function
def test_period(self): with self.assertRaises(ParseException): calc.evaluator({}, {}, '.') with self.assertRaises(ParseException): calc.evaluator({}, {}, '1+.')
Python
nomic_cornstack_python_v1
from typing import List string n-th Catalan numbers of length 2n $ O(\prod_{i=1}^n rac{i}{i+1} * {2n \choose n} * 2n) \sim O( rac{1}{n+1} * {2n \choose n} * 2n) \sim O( rac{4^n}{n^{3\over 2}\sqrt{\pi}} * 2n) \sim O( rac{4^n}{n^{1\over 2}}) $ class Solution begin comment Time complexity: O(4^n/n^0.5) comment Space compl...
from typing import List """ n-th Catalan numbers of length 2n $ O(\prod_{i=1}^n \frac{i}{i+1} * {2n \choose n} * 2n) \sim O(\frac{1}{n+1} * {2n \choose n} * 2n) \sim O(\frac{4^n}{n^{3\over 2}\sqrt{\pi}} * 2n) \sim O(\frac{4^n}{n^{1\over 2}}) $ """ class Solution: # Time complexity: O(4^n/n^0.5) # Space comp...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python from mpl_toolkits.mplot3d import Axes3D import matplotlib.pylab as p import numpy as np from sys import argv set f = open string argv at 1 string rb set X = list set Y = list set U = list for line in f begin set data = list comprehension decimal x for x in split line string , append X data a...
#!/usr/bin/python from mpl_toolkits.mplot3d import Axes3D import matplotlib.pylab as p import numpy as np from sys import argv f = open(str(argv[1]), 'rb') X = [] Y = [] U = [] for line in f: data = [float(x) for x in line.split(',')] X.append(data[0]) Y.append(data[1]) U.append(data[2]) X = np.arr...
Python
zaydzuhri_stack_edu_python
function convmf m_in e_in begin set m = array m_in % 2.0 * pi set numiter = 50 set small = 1e-08 if e_in > small begin set ecc = e_in * 1.0 comment ;; /* ------------ initial guess ------------- */ set e0 = m + ecc set lo = call logical_or m < 0.0 ? m > - pi m > pi set e0 at lo = m at lo - ecc set ktr = 1 set e1 = e0 +...
def convmf(m_in, e_in): m = np.array(m_in) % (2. * np.pi) numiter = 50 small = 0.00000001 if e_in > small: ecc = e_in * 1.0 # ;; /* ------------ initial guess ------------- */ e0 = m + ecc lo = np.logical_or((m < 0.0) & (m > -np.pi), m > np.pi) e0[lo] = ...
Python
nomic_cornstack_python_v1
from rest_framework.response import Response class APIResponse extends Response begin function __init__ self data_status=0 data_msg=string ok results=none http_status=none headers=none exception=false **kwargs begin comment data的初始状态:状态码与状态信息 set data = dict string status data_status ; string msg data_msg comment data的...
from rest_framework.response import Response class APIResponse(Response): def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs): # data的初始状态:状态码与状态信息 data = { 'status': data_status, 'msg': data_msg, ...
Python
zaydzuhri_stack_edu_python
string 每次将n-1个元素加1 相当于每次将一个元素减1 k = sum(nums) - n*min(nums) 与之类似还有462.Minimum Moves to Equal Array Elements II class Solution begin function minMoves self nums begin string :type nums: List[int] :rtype: int return sum nums - length nums * min nums end function end class
''' 每次将n-1个元素加1 相当于每次将一个元素减1 k = sum(nums) - n*min(nums) 与之类似还有462.Minimum Moves to Equal Array Elements II ''' class Solution: def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ return sum(nums) - len(nums)*min(nums)
Python
zaydzuhri_stack_edu_python
from __future__ import annotations from string import punctuation import pandas as pd from sklearn.base import BaseEstimator , TransformerMixin from spacy.lang.en.stop_words import STOP_WORDS import spacy set stopwords = list STOP_WORDS set nlp = load spacy string en_core_web_sm class Preprocessor extends BaseEstimator...
from __future__ import annotations from string import punctuation import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from spacy.lang.en.stop_words import STOP_WORDS import spacy stopwords = list(STOP_WORDS) nlp = spacy.load("en_core_web_sm") class Preprocessor(BaseEstimator, Tr...
Python
zaydzuhri_stack_edu_python
function tags_all self begin return get pulumi self string tags_all end function
def tags_all(self) -> pulumi.Output[Mapping[str, str]]: return pulumi.get(self, "tags_all")
Python
nomic_cornstack_python_v1
function typo_homo_bits_others_squatting domain squat_dic begin for key in squat_dic begin set current_type = squat_dic at key for item in current_type begin if item == domain begin return key end end end return none end function
def typo_homo_bits_others_squatting(domain, squat_dic): for key in squat_dic: current_type = squat_dic[key] for item in current_type: if item == domain: return key return None
Python
nomic_cornstack_python_v1
import tensorflow as tf from base.base_model import BaseModel class DeepYeastModel extends BaseModel begin function __init__ self config begin call __init__ config call build_model call init_saver end function function build_model self begin call init_build_model comment Block 1 set x = conv 2d input_layer 64 3 padding...
import tensorflow as tf from base.base_model import BaseModel class DeepYeastModel(BaseModel): def __init__(self, config): super(DeepYeastModel, self).__init__(config) self.build_model() self.init_saver() def build_model(self): super(DeepYeastModel, self).init_build_model() ...
Python
zaydzuhri_stack_edu_python
comment print out a statement saying what you're most excited to learn in this course! print string I am excited to see what you can do with coding. comment print out the number 5 and the string "days" using one line of code. set message = string 5 days: set space = string set days = string Monday, Tuesday, Wednesday,...
# print out a statement saying what you're most excited to learn in this course! print("I am excited to see what you can do with coding.") # print out the number 5 and the string "days" using one line of code. message = "5 days:" space = " " days = "Monday, Tuesday, Wednesday, Thursday, Friday" print(message + space +...
Python
zaydzuhri_stack_edu_python
for i in range 0 n begin set a = decimal input set sum = sum + a end set avg = sum / decimal n
for i in range(0,n): a=float(input()) sum=sum+a avg=(sum)/float(n)
Python
zaydzuhri_stack_edu_python
comment Tipos de variables (cadenas, números, listas, diccionarios, boleanos) ######### comment cadena set texto = string Taller de Python comment entero set num = 35 comment flotante set flotante = 3.5 comment boleano set verdadero = true comment boleano set falso = false comment lista set list = list string pedro str...
######### Tipos de variables (cadenas, números, listas, diccionarios, boleanos) ######### texto = "Taller de Python" # cadena num = 35 # entero flotante = 3.5 # flotante verdadero = True # boleano falso = False # boleano list = ["pedro", "pablo", "juan", texto] # lista print(list[3]) dict = {"altura": "1...
Python
zaydzuhri_stack_edu_python
set even_list = list comprehension x for x in list if x % 2 == 0
even_list = [x for x in list if x%2 == 0]
Python
flytech_python_25k
comment Leap motion controller for space invaders comment Differs from the listener in that we only poll the controller when we want. import Leap , sys , thread , time from Leap import CircleGesture , KeyTapGesture , ScreenTapGesture , SwipeGesture import math class SpaceController extends Controller begin function __i...
# Leap motion controller for space invaders # Differs from the listener in that we only poll the controller when we want. import Leap, sys, thread, time from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture import math class SpaceController(Leap.Controller): def __init__(self): Le...
Python
zaydzuhri_stack_edu_python
function state_file_name self state_name begin return call joinpath state_name + string .json end function
def state_file_name(self, state_name: str) -> Path: return self.home.joinpath(state_name + ".json")
Python
nomic_cornstack_python_v1
function get_mask self image begin set mask = call get_gradients image return mask end function
def get_mask(self, image): mask = self.get_gradients(image) return mask
Python
nomic_cornstack_python_v1
function height self begin return __height end function
def height(self): return self.__height
Python
nomic_cornstack_python_v1
function __str__ self begin return format string {0} {1} ({2}) rec_date rec_time store end function
def __str__(self): return '{0} {1} ({2})'.format(self.rec_date, self.rec_time, self.store)
Python
nomic_cornstack_python_v1
from __future__ import print_function , division import pandas as pd from torch.utils.data import Dataset import torch class PIMADataset extends Dataset begin string PIMA Indian Diabetes Database function __init__ self csv_file begin set df = read csv csv_file comment Standardising set X = drop df string Outcome axis=1...
from __future__ import print_function, division import pandas as pd from torch.utils.data import Dataset import torch class PIMADataset(Dataset): """ PIMA Indian Diabetes Database """ def __init__(self, csv_file): df = pd.read_csv(csv_file) # Standardising X = df.drop('Outcome...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import os as os import timeit string Class backprop: --------------- Constructor Parameters: 1. input: training input to the model (numpy array) 2. target: target values for supervised training (numpy array) 3. n_hidden: number of hidden layers (int) 4. hidden: number of neuro...
import tensorflow as tf import numpy as np import os as os import timeit ''' Class backprop: --------------- Constructor Parameters: 1. input: training input to the model (numpy array) 2. target: target values for supervised training (numpy array) 3. n_hidden: number of hidden layers (int) ...
Python
zaydzuhri_stack_edu_python
class Solution begin function multiply self num1 num2 begin set digit = list string 0 string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 set tuple times1 times2 = tuple 1 1 set tuple first second = tuple 0 0 for letter in num1 at slice : : - 1 begin set n = index digit letter set first =...
class Solution: def multiply(self, num1: str, num2: str) -> str: digit = ['0','1','2','3','4','5','6','7','8','9'] times1, times2 = 1, 1 first, second = 0, 0 for letter in num1[::-1]: n = digit.index(letter) first += n * times1 times1 *= 1...
Python
zaydzuhri_stack_edu_python
function get self get_args begin set include = get get_args string include none set get_args = call prepare_paginator_args get_args set get_args at string query = call handle_query_dict get_args at string query set tuple result total_count = call run_paginator_query get_args comment Reference alanlara erişim istenmiş m...
def get(self, get_args): include = get_args.get('include', None) get_args = self.prepare_paginator_args(get_args) get_args['query'] = self.handle_query_dict(get_args['query']) result, total_count = self.run_paginator_query(get_args) # Reference alanlara erişim istenmiş mi kontrol...
Python
nomic_cornstack_python_v1
string #01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: a) tamanho da lista. b) maior valor da lista. c) menor valor da lista. d) soma de todos os elementos da lista. e) lista em ordem crescente. f) lista em ordem decrescente. set l = list 5 7 2 9 4 1 3 print strin...
'''#01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: a) tamanho da lista. b) maior valor da lista. c) menor valor da lista. d) soma de todos os elementos da lista. e) lista em ordem crescente. f) lista em ordem decrescente.''' l = [5, 7, 2, 9, 4, 1, 3] pri...
Python
zaydzuhri_stack_edu_python
function main begin comment find 10001st prime function isPrime num factors begin set isPrime = true comment check if is prime by dividing by primes smaller than itself for factor in factors begin if num % factor == 0 begin set isPrime = false break end end return isPrime end function set primes = list 2 set j = 2 whil...
def main(): #find 10001st prime def isPrime(num, factors): isPrime = True #check if is prime by dividing by primes smaller than itself for factor in factors: if num % factor == 0: isPrime = False break return isPrime primes = [2...
Python
zaydzuhri_stack_edu_python
function getInitParams self begin set paramDict = dict set paramDict at string Module file name = functionFile set paramDict at string The residuum is provided = __actionImplemented at string residuum set paramDict at string The sign of the residuum is provided = __actionImplemented at string residuumSign set paramDic...
def getInitParams(self): paramDict = {} paramDict['Module file name' ] = self.functionFile paramDict['The residuum is provided' ] = self.__actionImplemented['residuum'] paramDict['The sign of the residuum is provided'] = self.__actionImplemented['residuumSign'] paramDic...
Python
nomic_cornstack_python_v1
function list_all_keys_starting_with_choose mapping model_name ignore_list isblacklist begin debug string Top of list_all_keys_starting_with_choose set all_chooses = list set keys = list mapping for key in keys begin set value = mapping at key if is instance key str and starts with key string choose_ and not isblackli...
def list_all_keys_starting_with_choose(mapping, model_name, ignore_list, isblacklist): logging.debug("Top of list_all_keys_starting_with_choose") all_chooses = [] keys = list(mapping) for key in keys: value = mapping[key] if ( isinstance(key, str) and key.startswi...
Python
nomic_cornstack_python_v1
class Point begin function __init__ self x y begin set x = x set y = y end function function __str__ self begin return format string ({0}, {1}) x y end function function __repr__ self begin return format string Point({0}, {1}) x y end function function __eq__ self other begin return x == x and y == y end function funct...
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "({0}, {1})".format(self.x, self.y) def __repr__(self): return "Point({0}, {1})".format(self.x, self.y) def __eq__(self, other): return self.x == other.x and se...
Python
zaydzuhri_stack_edu_python
function get_name_from_name_consensus_hash self name_consensus_hash sender_script_pubkey block_id begin string Find the name.ns_id from hash( name.ns_id, consensus_hash ), given the sender and block_id, and assuming that name.ns_id is already registered. There are only a small number of values this hash can take, so te...
def get_name_from_name_consensus_hash( self, name_consensus_hash, sender_script_pubkey, block_id ): """ Find the name.ns_id from hash( name.ns_id, consensus_hash ), given the sender and block_id, and assuming that name.ns_id is already registered. There are only a small number of values...
Python
jtatman_500k
comment !/usr/bin/env python3 import argparse import json import sys from recova.util import eprint function merge_statistics dict1 dict2 begin return dict end function function merge_result_files result_files output begin set metadata = dict set merged_data = list set statistics = dict set what = none for entry in...
#!/usr/bin/env python3 import argparse import json import sys from recova.util import eprint def merge_statistics(dict1, dict2): return {} def merge_result_files(result_files, output): metadata = {} merged_data = [] statistics = {} what = None for entry in result_files: with open(e...
Python
zaydzuhri_stack_edu_python
function broadcast_to_session self session_id header msg exclude=list begin set host = sessions at session_id at string HOST at string ID call send header host msg for key in keys sessions at session_id at string USERS begin if key not in exclude begin call send header key msg end end end function
def broadcast_to_session(self,session_id,header,msg, exclude = []): host = self.sessions[session_id]["HOST"]["ID"] self.send(header,host,msg) for key in self.sessions[session_id]["USERS"].keys(): if key not in exclude: self.send(header,key,msg)
Python
nomic_cornstack_python_v1
function latest_read_timestamp self begin set timestamp = latest_read_timestamp return call from_timestamp timestamp end function
def latest_read_timestamp(self): timestamp = (self._conversation.self_conversation_state. self_read_state.latest_read_timestamp) return parsers.from_timestamp(timestamp)
Python
nomic_cornstack_python_v1
function is_nic_legacy_boot_protocol_pxe self nic_id begin return call is_nic_legacy_boot_protocol_pxe nic_id end function
def is_nic_legacy_boot_protocol_pxe(self, nic_id): return self._nic_cfg.is_nic_legacy_boot_protocol_pxe(nic_id)
Python
nomic_cornstack_python_v1
function _get_mi_hyperpplanes self begin set d = dim - 1 set hyperplanes = list comprehension tuple d const for const in range order + 1 return hyperplanes end function
def _get_mi_hyperpplanes(self) -> List[Tuple[int, int]]: d = self.dim - 1 hyperplanes = [(d, const) for const in range(self.order + 1)] return hyperplanes
Python
nomic_cornstack_python_v1
comment p20.py comment Layla Gallez comment 2/28/2021 comment Python 3.8.1 comment Description: Program to show output in Python set user_input = integer input string How Many Numbers Would You Like To Enter? set sum = 0 set sumNeg = 0 set sumPos = 0 for index in range 0 user_input 1 begin set number = decimal input st...
# p20.py # Layla Gallez # 2/28/2021 # Python 3.8.1 # Description: Program to show output in Python user_input =int(input('How Many Numbers Would You Like To Enter? ')) sum = 0 sumNeg = 0 sumPos = 0 for index in range(0, user_input,1): number = float(input('Enter number %i: ' %(index+1) )) if number < 0: ...
Python
zaydzuhri_stack_edu_python
function test_no_undefined_references_from_session begin set bf = call Session load_questions=false use_deprecated_workmgr_v1=false with call object q string undefinedReferences create=true as undefinedReferences begin comment Test success set return_value = call MockQuestion call assert_no_undefined_references comment...
def test_no_undefined_references_from_session(): bf = Session(load_questions=False, use_deprecated_workmgr_v1=False) with patch.object(bf.q, "undefinedReferences", create=True) as undefinedReferences: # Test success undefinedReferences.return_value = MockQuestion() bf.asserts.assert_no_u...
Python
nomic_cornstack_python_v1
set a = integer input set b = decimal input set c = input print i + a print d + b print s + c
a=int(input()) b=float(input()) c=input() print(i+a) print(d+b) print(s+c)
Python
zaydzuhri_stack_edu_python
comment Bags/Sweets program set bags = integer input string Enter the number of bags you have: set sweets = integer input string Enter the number of sweets you have (must be greater than that of the number of bags): while bags >= sweets begin set sweets = integer input string Please enter a number of sweets larger than...
#Bags/Sweets program bags = int(input("Enter the number of bags you have: ")) sweets = int(input("Enter the number of sweets you have (must be greater than that of the number of bags): ")) while bags >= sweets: sweets = int(input((f"Please enter a number of sweets larger than {bags}: "))) if(sweets/bags) % 2 ...
Python
zaydzuhri_stack_edu_python
comment IMPORT DEPENDENCIES comment ------------------------------------------------------------------------------------- from nltk.tokenize import word_tokenize as token from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import string , math , numpy as np , pandas as pd comment IMPORT DAT...
#IMPORT DEPENDENCIES #------------------------------------------------------------------------------------- from nltk.tokenize import word_tokenize as token from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import string, math, numpy as np, pandas as pd #IMPORT DATASET #---------...
Python
zaydzuhri_stack_edu_python
import ctypes , os comment see <linux/time.h> set CLOCK_MONOTONIC = 1 class timespec extends Structure begin set _fields_ = list tuple string tv_sec c_long tuple string tv_nsec c_long end class set librt = call CDLL string librt.so.1 use_errno=true set clock_gettime = clock_gettime set argtypes = list c_int call POINTE...
import ctypes, os CLOCK_MONOTONIC = 1 # see <linux/time.h> class timespec(ctypes.Structure): _fields_ = [ ('tv_sec', ctypes.c_long), ('tv_nsec', ctypes.c_long) ] librt = ctypes.CDLL('librt.so.1', use_errno=True) clock_gettime = librt.clock_gettime clock_gettime.argtypes = [ctypes.c_int, ctype...
Python
zaydzuhri_stack_edu_python
function is_dark wf begin if not get alfred_env string theme_background begin return true end set rgb = list comprehension integer x for x in split alfred_env at string theme_background at slice 5 : - 6 : string , return 0.299 * rgb at 0 + 0.587 * rgb at 1 + 0.114 * rgb at 2 / 255 < 0.5 end function function get_icon ...
def is_dark(wf): if not wf.alfred_env.get('theme_background'): return True rgb = [int(x) for x in wf.alfred_env['theme_background'][5:-6].split(',')] return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255 < 0.5 def get_icon(wf, name): name = '%s-dark' % name if is_dark(wf) else name return "ico...
Python
jtatman_500k
function enrich_predictions df_pred path_dtype_data begin comment from photometry header comment get headers set list_head = glob glob string { path_dtype_data } /*HEAD.FITS set list_df_head = list for fname in list_head begin set dat = read Table fname format=string fits append list_df_head call to_pandas end set df_...
def enrich_predictions(df_pred, path_dtype_data): # from photometry header # get headers list_head = glob.glob(f"{path_dtype_data}/*HEAD.FITS") list_df_head = [] for fname in list_head: dat = Table.read(fname, format='fits') list_df_head.append(dat.to_pandas()) df_head = pd.conca...
Python
nomic_cornstack_python_v1
function get_tsv_files begin set tuple df_dic _ = call get_all_dataframes set folder = string dataframes if not exists path folder begin make directories folder end for tuple y df in items df_dic begin fill missing df 0 inplace=true set filename = string df + string y + string .tsv print string Saving filename to csv d...
def get_tsv_files(): df_dic, _ = get_all_dataframes() folder = 'dataframes' if not os.path.exists(folder): os.makedirs(folder) for y, df in df_dic.items(): df.fillna(0, inplace=True) filename = 'df'+str(y)+'.tsv' print("Saving ", filename) df.to_csv(Path(folder)...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment tup1=(23,46,"false",49) comment print(tup1) comment print(type(tup1)) comment In[2]: set tup1 = tuple 23 46 string false 49 print tup1 at 2 print type tup1 comment In[4]: set tup1 = tuple 23 46 string false 493 46 string true 49 print tup1 at slice 2 : 5 : prin...
#!/usr/bin/env python # coding: utf-8 # tup1=(23,46,"false",49) # print(tup1) # print(type(tup1)) # In[2]: tup1=(23,46,"false",49) print(tup1[2]) print(type(tup1)) # In[4]: tup1=(23,46,"false",493,46,"true",49) print(tup1[2:5]) print(type(tup1)) # In[7]: tup1=(23,46,"false",49,True,"apple","mango") print(tu...
Python
zaydzuhri_stack_edu_python
import cv2 set face_cascade = call CascadeClassifier string haarcascade_frontalface_default.xml set capture = call VideoCapture 0 while true begin set tuple ret img = read capture set gray_img = call cvtColor img COLOR_BGR2GRAY set faces = call detectMultiScale gray_img 1.3 5 for tuple x y w h in faces begin call recta...
import cv2 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') capture = cv2.VideoCapture(0) while True: ret, img = capture.read() gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray_img, 1.3, 5) for (x,y,w,h) in faces: ...
Python
zaydzuhri_stack_edu_python
function get_album art_name art_bum art_num=none begin set artist = dict string Name art_name ; string Album art_bum if art_num begin set artist at string Number of Songs = art_num end return artist end function
def get_album(art_name, art_bum, art_num = None): artist = {'Name': art_name, 'Album': art_bum} if art_num: artist['Number of Songs'] = art_num return artist
Python
nomic_cornstack_python_v1
from typing import List , Optional comment type: ignore import shapefile as shp import pandas as pd from src.log import logger class ShapefileManager begin function __init__ self input_shapefile_path output_shapefile_path csv_path begin set output_shapefile_path = output_shapefile_path if csv_path begin call _create_ra...
from typing import List, Optional import shapefile as shp # type: ignore import pandas as pd from src.log import logger class ShapefileManager: def __init__( self, input_shapefile_path: str, output_shapefile_path: str, csv_path: Optional[str], ): self.output_shapefil...
Python
zaydzuhri_stack_edu_python
import os if __name__ == string __main__ begin set amazon_path = string images\Reference images\Amazom set imageName = split amazon_path sep at - 1 set dotIndex = find imageName string . print dotIndex print imageName at slice 0 : dotIndex : print sep end
import os if __name__ == '__main__': amazon_path = "images\\Reference images\\Amazom" imageName = amazon_path.split(os.path.sep)[-1] dotIndex = imageName.find("."); print(dotIndex) print(imageName[0:dotIndex]) print(os.path.sep)
Python
zaydzuhri_stack_edu_python
string Creates training data from semi-supervised technique. Give the script a set of data that has a specific turn. It then clusters the events. Each cluster represents a component of the timed event (ie. starting cluster of events, middle nad end of events) import datetime import os import sys import numpy as np impo...
""" Creates training data from semi-supervised technique. Give the script a set of data that has a specific turn. It then clusters the events. Each cluster represents a component of the timed event (ie. starting cluster of events, middle nad end of events) """ import datetime import os import sys import numpy as np imp...
Python
zaydzuhri_stack_edu_python