code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import requests from bs4 import BeautifulSoup set url = string https://comic.naver.com/webtoon/weekday set res = get requests url call raise_for_status set soup = call BeautifulSoup text string lxml comment 네이버 웹툰 전체 목록 가져오기 comment 클래스 속성이 title인 모든 'a' element set cartoons = find all soup string a attrs=dict string c...
import requests from bs4 import BeautifulSoup url="https://comic.naver.com/webtoon/weekday" res=requests.get(url) res.raise_for_status() soup=BeautifulSoup(res.text,"lxml") #네이버 웹툰 전체 목록 가져오기 cartoons = soup.find_all("a",attrs={"class":"title"}) #클래스 속성이 title인 모든 'a' element for cartoon in cartoons: ...
Python
zaydzuhri_stack_edu_python
import json from GetRestaurantsYelpAPI import getRestaurants from yelp_scraper import scrapeYelp from multiprocessing import Process function scrape_for_url url id begin print string start scrapping for url + url set scrape_data = call scrapeYelp url id print scrape_data with open string YelpData.txt string a+ as outfi...
import json from GetRestaurantsYelpAPI import getRestaurants from yelp_scraper import scrapeYelp from multiprocessing import Process def scrape_for_url(url,id): print('start scrapping for url ' + url) scrape_data = scrapeYelp(url,id) print(scrape_data) with open('YelpData.txt', 'a+') as outfile: ...
Python
zaydzuhri_stack_edu_python
function get_size self begin return list _size end function
def get_size(self): return list(self._size)
Python
nomic_cornstack_python_v1
if nacho_price > cash begin print string Sorry, no ncahos for you! end if nacho_price < cash begin print string Woot, nachos! end if nacho_price == cash begin print string That sure was lucky! end print string Thanks for using nacho_buyer.py. print string Welcome to the convenience store! print string Enter your age: s...
if nacho_price > cash: print("Sorry, no ncahos for you!") if nacho_price < cash: print("Woot, nachos!") if nacho_price == cash: print("That sure was lucky!") print("Thanks for using nacho_buyer.py.") print("Welcome to the convenience store!") print("Enter your age:") age = input() age = int(age) if age >= 18: ...
Python
zaydzuhri_stack_edu_python
class LinkedList begin function __init__ self value begin set value = value set next = none end function function insert self value begin if next is none begin set next = call LinkedList value end else begin insert next value end end function function show self begin print value if next is not none begin show end end f...
class LinkedList(): def __init__(self, value): self.value = value self.next = None def insert(self, value): if self.next is None: self.next = LinkedList(value) else: self.next.insert(value) def show(self): print(self.value) if self.ne...
Python
zaydzuhri_stack_edu_python
function population begin set pop_csv = read csv call csv_path string Population.csv index_col=0 dtype=dict string Population uint32 set pop_csv at string Population = as type pop_csv at string Population * POPULATION_SCALE string uint32 return pop_csv end function
def population(): pop_csv = pd.read_csv(csv_path("Population.csv"), index_col=0, dtype={"Population": np.uint32}) pop_csv["Population"] = (pop_csv["Population"] * POPULATION_SCALE).astype("uint32") return pop_csv
Python
nomic_cornstack_python_v1
function test01_math_operators self begin import _cppyy set number = number assert call number 20 + call number 10 == call number 30 assert call number 20 + 10 == call number 30 assert call number 20 - call number 10 == call number 10 assert call number 20 - 10 == call number 10 assert call number 20 / call number 10 =...
def test01_math_operators(self): import _cppyy number = _cppyy.gbl.number assert (number(20) + number(10)) == number(30) assert (number(20) + 10 ) == number(30) assert (number(20) - number(10)) == number(10) assert (number(20) - 10 ) == number(10) ...
Python
nomic_cornstack_python_v1
function test_PxC N=25 begin if not with_cython begin return end set lon0 = 10 set lat0 = - 25 set Lon = 540 * random N - 180 set Lat = 90 * 2 * random N - 1 set tuple Lon Lat = call meshgrid Lon Lat comment print("Testing scalar") comment d = haversine(Lat[0, 0], Lon[0, 0], lat0, lon0) comment c_d = c_haversine(Lat[0,...
def test_PxC(N=25): if not with_cython: return lon0 = 10 lat0 = -25 Lon = 540*random(N) - 180 Lat = 90*(2*random(N)-1) Lon, Lat = np.meshgrid(Lon, Lat) #print("Testing scalar") #d = haversine(Lat[0, 0], Lon[0, 0], lat0, lon0) #c_d = c_haversine(Lat[0, 0], Lon[0, 0], lat0, ...
Python
nomic_cornstack_python_v1
function encrypt self message key begin set p = call from_bytes call _pad_message message call byte_size BYTE_ORDER set c = call encrypt p return call to_bytes call byte_size BYTE_ORDER end function
def encrypt(self, message: bytes, key: Key) -> bytes: p = int.from_bytes(self._pad_message(message, key.byte_size()), self.BYTE_ORDER) c = key.encrypt(p) return c.to_bytes(key.byte_size(), self.BYTE_ORDER)
Python
nomic_cornstack_python_v1
import numpy as np from copy import deepcopy import time import resource from collections import deque from queue import PriorityQueue from sys import argv set max_depth = 0 set max_frontier = 0 set count = 0 class Node extends object begin function __init__ self state=none begin set state = state set depth = 0 set par...
import numpy as np from copy import deepcopy import time import resource from collections import deque from queue import PriorityQueue from sys import argv max_depth = 0 max_frontier = 0 count = 0 class Node(object): def __init__(self, state = None): self.state = state self.depth = 0 self....
Python
zaydzuhri_stack_edu_python
comment Write a program that reads some lines containing votes: each line contains a name. comment Have the program print the list of candidates in descending order of the number of votes received. set s = string modi 10 rahul 0 mamta 8 lalu 6 modi 8 set m = 0 set r = 0 set ma = 0 set l = 0 set x = list for i in split...
#Write a program that reads some lines containing votes: each line contains a name. #Have the program print the list of candidates in descending order of the number of votes received. s="""modi 10 rahul 0 mamta 8 lalu 6 modi 8""" m=0 r=0 ma=0 l=0 x=[] for i in s.split("\n"): if 'modi' in i: ...
Python
zaydzuhri_stack_edu_python
function entry entry fhandle begin import time set timestamp = string format time time string %H:%M:%S end function
def entry(entry,fhandle): import time timestamp = time.strftime('%H:%M:%S')
Python
nomic_cornstack_python_v1
function attach self observer begin string Attach an observer. Args: observer (func): A function to be called when new messages arrive Returns: :class:`Stream`. Current instance to allow chaining if not observer in _observers begin append _observers observer end return self end function
def attach(self, observer): """ Attach an observer. Args: observer (func): A function to be called when new messages arrive Returns: :class:`Stream`. Current instance to allow chaining """ if not observer in self._observers: self._observers.a...
Python
jtatman_500k
function df_group_accupancy_by_column df col func target_col begin set df = call aggregate func return tuple index df at target_col end function
def df_group_accupancy_by_column(df, col, func, target_col): df = df.groupby(col).aggregate(func) return df.index, df[target_col]
Python
nomic_cornstack_python_v1
comment ------------------------------------------------------------------------------- comment Sherif Sarhan comment This is a simple program to output the word count of a file. comment ------------------------------------------------------------------------------- function parse_document filename begin comment Opens ...
#------------------------------------------------------------------------------- # Sherif Sarhan # This is a simple program to output the word count of a file. #------------------------------------------------------------------------------- def parse_document(filename): #Opens file with read param file = open(filenam...
Python
zaydzuhri_stack_edu_python
function resume workflow_id storage=none begin assert call is_initialized return call resume workflow_id storage end function
def resume(workflow_id: str, storage: "Optional[Union[str, Storage]]" = None) -> ray.ObjectRef: assert ray.is_initialized() return execution.resume(workflow_id, storage)
Python
nomic_cornstack_python_v1
function __eq__ self other begin if is instance self __class__ begin return __dict__ == __dict__ end return false end function
def __eq__(self, other): if isinstance(self, other.__class__): return self.__dict__ == other.__dict__ return False
Python
nomic_cornstack_python_v1
from PyQt5 import QtCore , QtWidgets from PyQt5.QtGui import QPixmap import random from solver import AStar import time class Tiles begin function __init__ self gridlen begin string Initializes the tiles. Tile order will be represented as a single list of numbers as strings and "*" as the empty tile. As an example, the...
from PyQt5 import QtCore, QtWidgets from PyQt5.QtGui import QPixmap import random from solver import AStar import time class Tiles(): def __init__(self, gridlen): """Initializes the tiles. Tile order will be represented as a single list of numbers as strings and "*" as the empty tile. ...
Python
zaydzuhri_stack_edu_python
from PyQt5 import QtWidgets , QtGui from PyQt5.QtCore import QRect , Qt from PyQt5.QtGui import QPen , QBrush , QColor function get_color color begin set tuple r g b = tuple max 0 - color max 0 color 0 return call QColor r * 255 g * 255 b * 255 end function class NeuralNetworkViewer extends QMainWindow begin function _...
from PyQt5 import QtWidgets, QtGui from PyQt5.QtCore import QRect, Qt from PyQt5.QtGui import QPen, QBrush, QColor def get_color(color): r, g, b = max(0, -color), max(0, color), 0 return QColor(r * 255, g * 255, b * 255) class NeuralNetworkViewer(QtWidgets.QMainWindow): def __init__(self, network=None, ...
Python
zaydzuhri_stack_edu_python
function play_card self table_cards player begin set cards = list comprehension card for played_card in table_cards set is_allowed_card = false set generator = call choose_card state=call get_status set chosen_card = next generator while not is_allowed_card begin set is_allowed_card = call card_allowed table_cards=card...
def play_card(self, table_cards, player): cards = [played_card.card for played_card in table_cards] is_allowed_card = False generator = player.choose_card(state=self.get_status()) chosen_card = next(generator) while not is_allowed_card: is_allowed_card = card_allowed(...
Python
nomic_cornstack_python_v1
import os set list_path = list string C:\Windows\Prefetch string C:\Windows\Temp call getenv string temp function clear_data locate begin for tuple raiz diretorios arquivos in walk locate begin for arquivo in arquivos begin try begin remove os join path raiz arquivo end except any begin print arquivo + string Erro end ...
import os list_path = ['C:\Windows\Prefetch','C:\Windows\Temp', os.getenv('temp')] def clear_data(locate): for raiz, diretorios, arquivos in os.walk(locate): for arquivo in arquivos: try: os.remove(os.path.join(raiz, arquivo)) except: print(arquivo + ' Erro') for i in list_path: clear_data(i) ...
Python
zaydzuhri_stack_edu_python
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer , TfidfVectorizer from sklearn import metrics from sklearn.svm import SVC set clf = support vector classifier kernel=string linear set twenty_train = call fetch_20newsgroups subset=string train shuffle=true set t...
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn import metrics from sklearn.svm import SVC clf = SVC(kernel='linear') twenty_train = fetch_20newsgroups(subset='train', shuffle=True) twenty_test = fetch_20newsgroups(subset='test'...
Python
zaydzuhri_stack_edu_python
import urllib.request from bs4 import BeautifulSoup import requests set url = string https://example.com set response = get requests url set soup = call BeautifulSoup text string html.parser set images = find all soup string img comment Let me run it for you! for tuple i img in enumerate images begin url retrieve img a...
import urllib.request from bs4 import BeautifulSoup import requests url = 'https://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') images = soup.find_all('img') # Let me run it for you! for i, img in enumerate(images): urllib.request.urlretrieve(img['src'], f'image{i}....
Python
flytech_python_25k
function sum_of_squares arr begin set even_nums = list set odd_count = 0 if length arr == 0 begin return tuple 0 0 list end if arr at 0 % 2 == 0 begin append even_nums arr at 0 set even_sum = arr at 0 ^ 2 set odd_count = 0 end else begin set even_sum = 0 set odd_count = 1 end set tuple sub_even_sum sub_odd_count sub_...
def sum_of_squares(arr): even_nums = [] odd_count = 0 if len(arr) == 0: return 0, 0, [] if arr[0] % 2 == 0: even_nums.append(arr[0]) even_sum = arr[0]**2 odd_count = 0 else: even_sum = 0 odd_count = 1 sub_even_sum, sub_odd_count, sub_even_nums =...
Python
greatdarklord_python_dataset
function to_str data begin string Takes an input str or bytes object and returns an equivalent str object. :param data: Input data :type data: str or bytes :returns: Data normalized to str :rtype: str if is instance data bytes begin return decode codecs data TEXT_ENCODING end return data end function
def to_str(data): """Takes an input str or bytes object and returns an equivalent str object. :param data: Input data :type data: str or bytes :returns: Data normalized to str :rtype: str """ if isinstance(data, bytes): return codecs.decode(data, TEXT_ENCODING) return data
Python
jtatman_500k
set a = 5 set b = 12 set c = 10 set Volume = a * b * c print Volume set SurfaceArea = 2 * a * b + b * c + a * c print SurfaceArea
a = 5 b = 12 c = 10 Volume = a * b * c print(Volume) SurfaceArea = 2 * (a*b + b*c + a*c) print(SurfaceArea)
Python
zaydzuhri_stack_edu_python
function client_request_access_token begin call clear_current_request call inject_new_request set payload = call DTO sub=200 auth=string test set access_token = call generate_access_token payload set refresh_token = call generate_refresh_token payload call set_access_token access_token call set_refresh_token refresh_to...
def client_request_access_token(): test_session_services.clear_current_request() test_session_services.inject_new_request() payload = DTO(sub=200, auth='test') access_token = token_services.generate_access_token(payload) refresh_token = token_services.generate_refresh_token(payload) test_sessio...
Python
nomic_cornstack_python_v1
function is_conditional begin raise NotImplementedError end function
def is_conditional(): raise NotImplementedError
Python
nomic_cornstack_python_v1
from fst import FST , ACCEPT_SYMBOL import itertools from random import sample , choice set INTERSECT = string INTERSECT set UNION = string UNION class FSTools begin function __init__ self begin pass end function function _merge_fst self list_fst op=INTERSECT begin comment given list of fst [ Q, R, T ] comment new stat...
from fst import FST, ACCEPT_SYMBOL import itertools from random import sample, choice INTERSECT = "INTERSECT" UNION = "UNION" class FSTools: def __init__(self): pass def _merge_fst(self, list_fst, op=INTERSECT): # given list of fst [ Q, R, T ] # new states are [ ... (qi, rj, tk) ...] ...
Python
zaydzuhri_stack_edu_python
function array123 nums begin for i in range length nums - 2 begin if tuple nums at i nums at i + 1 nums at i + 2 == tuple 1 2 3 begin return true end end return false end function
def array123(nums): for i in range(len(nums)-2): if (nums[i], nums[i+1], nums[i+2]) == (1, 2, 3): return True return False
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys import os import os.path import pwd import subprocess import multiprocessing import logging import time class CreateNewVNCServer extends Process begin function __init__ self name username display_number display_name geometry pixelformat begin call __init__ name=name set log = ca...
#!/usr/bin/env python3 import sys import os import os.path import pwd import subprocess import multiprocessing import logging import time class CreateNewVNCServer(multiprocessing.Process): def __init__(self, name, username, display_number, display_name, geometry, pixelformat): super().__init__(name=name)...
Python
zaydzuhri_stack_edu_python
function test_singular_vs_multiprocess_parse_dls self begin comment Parse with multiprocessing and store table entry count set multi_params = length call test_multiprocess_parse_dls comment Parse again with a single process and store table entry count set singular_params = length call _single_process_parse_dls param_mo...
def test_singular_vs_multiprocess_parse_dls(self): # Parse with multiprocessing and store table entry count multi_params = len(self.test_multiprocess_parse_dls()) # Parse again with a single process and store table entry count singular_params = \ len(self._single_process_par...
Python
nomic_cornstack_python_v1
comment %% comment Imports ########## import torch as torch import torch.nn as nn import torchvision from torchvision import datasets , models , transforms import torch.optim as optim import numpy as np import matplotlib.pyplot as plt import time import os import copy from alexnet import AlexNet from vgg import VGG , v...
#%% ########## Imports ########## import torch as torch import torch.nn as nn import torchvision from torchvision import datasets, models, transforms import torch.optim as optim import numpy as np import matplotlib.pyplot as plt import time import os import copy from alexnet import AlexNet from vgg import VGG, vgg13 ...
Python
zaydzuhri_stack_edu_python
function limit_color_value data begin return integer data > 255 end function
def limit_color_value(data): return int(data) > 255
Python
nomic_cornstack_python_v1
import numpy as np from matplotlib import pyplot as plt import scipy.stats from scipy.optimize import fmin_cobyla from scipy.optimize import fmin import math from multiprocessing import Pool import time import sys call setrecursionlimit 1000000 string Calibration Functions comment https://stats.stackexchange.com/questi...
import numpy as np from matplotlib import pyplot as plt import scipy.stats from scipy.optimize import fmin_cobyla from scipy.optimize import fmin import math from multiprocessing import Pool import time import sys sys.setrecursionlimit(1000000) """ Calibration Functions""" # https://stats.stackexchange.com/question...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ http_proxy=none https_proxy=none no_proxy=none begin if http_proxy is not none begin set __self__ string http_proxy http_proxy end if https_proxy is not none begin set __self__ string https_proxy https_proxy end if no_proxy is not none begin set __self__ string no_proxy no_proxy end end funct...
def __init__(__self__, *, http_proxy: Optional[pulumi.Input[str]] = None, https_proxy: Optional[pulumi.Input[str]] = None, no_proxy: Optional[pulumi.Input[str]] = None): if http_proxy is not None: pulumi.set(__self__, "http_proxy", http_proxy) ...
Python
nomic_cornstack_python_v1
import subprocess import re comment Copies the tiles in the s3 folder to the spot machine function s3_to_spot folder begin set dld = list string aws string s3 string cp folder string . string --recursive check call dld end function comment Gets the tile id from the full tile name using a regular expression function get...
import subprocess import re # Copies the tiles in the s3 folder to the spot machine def s3_to_spot(folder): dld = ['aws', 's3', 'cp', folder, '.', '--recursive'] subprocess.check_call(dld) # Gets the tile id from the full tile name using a regular expression def get_tile_id(tile_name): # based on http...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Jul 12 14:50:55 2018 @author: amit from datetime import * import time set t1 = string parse time call ctime string %a %b %d %H:%M:%S %Y if hour >= 19 or hour <= 5 begin print string Night end else begin print string Day end
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 12 14:50:55 2018 @author: amit """ from datetime import * import time t1 = datetime.strptime(time.ctime(),'%a %b %d %H:%M:%S %Y') if t1.hour >= 19 or t1.hour <= 5: print("Night") else: print("Day")
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from unittest.mock import patch from A2.dungeonsanddragons import choose_attack class TestChoose_attack extends TestCase begin decorator patch string random.choice side_effect=list string kitty string puppy string otter string longsword string AK-47 string thermonuclear device function tes...
from unittest import TestCase from unittest.mock import patch from A2.dungeonsanddragons import choose_attack class TestChoose_attack(TestCase): @patch('random.choice', side_effect=['kitty', 'puppy', 'otter', 'longsword', 'AK-47', 'thermonuclear device']) def test_choose_monster_attack(self, mock_choice): ...
Python
zaydzuhri_stack_edu_python
function set_open_kernal_x self open_kernel_x begin set open_kernel_x = call _passed_to_int open_kernel_x end function
def set_open_kernal_x(self, open_kernel_x): self.open_kernel_x = self._passed_to_int(open_kernel_x)
Python
nomic_cornstack_python_v1
function solution S begin set A = list for i in range length S begin if S at i == string { begin append A string } end if S at i == string [ begin append A string ] end if S at i == string ( begin append A string ) end if S at i == string } or S at i == string ] or S at i == string ) begin if length A == 0 begin retur...
def solution(S): A = [] for i in range(len(S)): if S[i] == '{': A.append('}') if S[i] == '[': A.append(']') if S[i] == '(': A.append(')') if S[i] == '}' or S[i] == ']' or S[i] == ')': if len(A) == 0: return 0 ...
Python
zaydzuhri_stack_edu_python
function get_total_divisors number begin if number <= 2 begin return number end try begin set d = saved_divisors at number return d end except any begin set a = square root number set array = list range 1 integer a set div = filter lambda x -> number % x == 0 array set total_divisors = length div * 2 set saved_divisors...
def get_total_divisors(number): if number <= 2: return number try: d = saved_divisors[number] return d except: a = math.sqrt(number) array = list(range(1,int(a))) div = filter(lambda x: number%x == 0, array) total_divisors = len(div) * 2 saved_...
Python
nomic_cornstack_python_v1
import os import speech_recognition as sr import playsound from gtts import gTTS import getpass import time import wolframalpha import webbrowser from selenium import webdriver set num = 1 function assistant_speaks output begin global num set num = num + 1 comment print("Rookie : ", output) set toSpeak = call gTTS text...
import os import speech_recognition as sr import playsound from gtts import gTTS import getpass import time import wolframalpha import webbrowser from selenium import webdriver num = 1 def assistant_speaks(output): global num num += 1 #print("Rookie : ", output) toSpeak = gTTS(text = output, lang ='en', sl...
Python
zaydzuhri_stack_edu_python
function preffered_channel_select_list2 self selected_field selected_list_state selected_list_id is_readonly select_list_initial_msg begin comment this dictionary is used to store the name and value of select list set preffered_channel_list_name_value_dic = dict append set default preffered_channel_list_name_value_dic...
def preffered_channel_select_list2(self, selected_field, selected_list_state, selected_list_id, is_readonly, select_list_initial_msg): # this dictionary is used to store the name and value of select list preffered_channel_list_name_value_dic = {} preffered_channel_list_name_value_dic.setdefault...
Python
nomic_cornstack_python_v1
comment group 1 | group 2 | group 3 comment --------------------------- comment group 4 | group 5 | group 6 comment --------------------------- comment group 7 | group 8 | group 9 comment Setup board ############# set row_1 = list set list 7 set list 1 2 3 4 5 6 7 8 9 set list 1 2 3 4 5 6 7 8 9 set list 1 set list 1 2 ...
# group 1 | group 2 | group 3 # --------------------------- # group 4 | group 5 | group 6 # --------------------------- # group 7 | group 8 | group 9 ############# Setup board ############# row_1 = [set([7]), set([1, 2, 3, 4, 5, 6, 7, 8, 9]), set([1, 2, 3, 4, 5, 6, 7, 8, 9]), set([1]), set([1, 2, 3, 4, 5, 6, 7, 8, 9])...
Python
zaydzuhri_stack_edu_python
function __init__ self gtfFile lineNumber begin set lineNumber = lineNumber set gtfFile = gtfFile comment -2 remove ';\n' set data = split lines at lineNumber at slice : - 2 : string set proto_atts = split strip data at legend at string attributes string ; set atts = dict for a in proto_atts begin set sa = split a s...
def __init__(self, gtfFile, lineNumber) : self.lineNumber = lineNumber self.gtfFile = gtfFile self.data = gtfFile.lines[lineNumber][:-2].split('\t') #-2 remove ';\n' proto_atts = self.data[gtfFile.legend['attributes']].strip().split('; ') atts = {} for a in proto...
Python
nomic_cornstack_python_v1
comment get a bot playable in the regular engine from weights. import shutil , json from robot import Robot set epoch = input string Epoch? set bot = 0 if string / in epoch begin set tuple epoch bot = split epoch1 string / set bot = integer bot end with open string saved_weights/epoch { epoch } .json as f begin set wei...
# get a bot playable in the regular engine from weights. import shutil, json from robot import Robot epoch = input("Epoch? ") bot = 0 if "/" in epoch: epoch, bot = epoch1.split("/") bot = int(bot) with open(f"saved_weights/epoch{epoch}.json") as f: weights = json.load(f)[bot] name = input("Name? ") r ...
Python
zaydzuhri_stack_edu_python
function myadd a n=10 *d **args begin if a <= 0 begin return 0 end else begin set sum = 0 for i in range 1 n + 1 begin set sum = sum + a end print string sum end return tuple a n d args end function
def myadd(a,n=10,*d,**args): if a<=0: return 0 else: sum = 0 for i in range(1,n+1): sum = sum + a print("sum") return a,n,d,args
Python
nomic_cornstack_python_v1
function __init__ self config_file_path module_output_dir begin comment Initial settings set config_path = config_file_path comment Ouput directory (Should be created outside of the constructor) set module_output_dir = module_output_dir comment Local count on the number of safe trajectories generated set safe_trajs_gen...
def __init__(self, config_file_path, module_output_dir): # Initial settings self.config_path = config_file_path # Ouput directory (Should be created outside of the constructor) self.module_output_dir = module_output_dir # Local count on the number of safe trajectories generated self.safe_trajs_generated ...
Python
nomic_cornstack_python_v1
function target_spot_capacity self begin return get pulumi self string target_spot_capacity end function
def target_spot_capacity(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "target_spot_capacity")
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import math class Gaussian extends object begin string Gaussian distribution to act as pior distribution for variational inference function __init__ self mu rho begin set mu = mu set rho = rho set normal = call Normal 0 1 end function decorator property function sigma self begin retur...
import torch import torch.nn as nn import math class Gaussian(object): """Gaussian distribution to act as pior distribution for variational inference""" def __init__(self, mu, rho): self.mu = mu self.rho = rho self.normal = torch.distributions.Normal(0, 1) @property def s...
Python
zaydzuhri_stack_edu_python
comment keras-010 #3-A [Validation Percentage] comment train_test_split을 2번 했을 때 어떻게 나뉘는지 보기 위한 예제 from icecream import ic import numpy as np from sklearn.model_selection import train_test_split set x = array range 1 101 set y = array range 1 101 set tuple x_train x_test y_train y_test = train test split x y test_size=...
# keras-010 #3-A [Validation Percentage] # train_test_split을 2번 했을 때 어떻게 나뉘는지 보기 위한 예제 from icecream import ic import numpy as np from sklearn.model_selection import train_test_split x = np.array(range(1, 101)) y = np.array(range(1, 101)) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, s...
Python
zaydzuhri_stack_edu_python
comment while倒序打印字符 function search_show text begin set i = length text - 1 while i >= 0 begin print text at i set i = i - 1 end end function comment for倒序打印字符 function search_show_for1 text begin for i in range length text begin set j = length text - i print text at j - 1 end end function comment while正序打印字符 function ...
# while倒序打印字符 def search_show(text): i = len(text)-1 while i >= 0: print(text[i]) i = i - 1 # for倒序打印字符 def search_show_for1(text): for i in range(len(text)): j = len(text)-i print(text[j-1]) # while正序打印字符 def search_show2(text): i = 0 while i < len(text): ...
Python
zaydzuhri_stack_edu_python
function extract_fea_for_datagroup self data_group mode=string train begin if mode == string train begin set fp = open train_path string r end else begin set fp = open test_path string r end for tuple i line in call tqdm enumerate fp begin set tuple audio_name label = split line set audio_path = join path dev_path audi...
def extract_fea_for_datagroup(self, data_group, mode='train'): if mode == 'train': fp = open(self.train_path, 'r') else: fp = open(self.test_path, 'r') for i, line in tqdm(enumerate(fp)): audio_name, label = line.split() audio_path = os.path.join(...
Python
nomic_cornstack_python_v1
function post self begin set parser = call RequestParser call add_argument string email location=string json required=true help=string Your input email is invalid call add_argument string new_password location=string json required=true help=string Your input password is invalid set args = call parse_args set pattern = ...
def post(self): parser = reqparse.RequestParser() parser.add_argument('email', location='json', required=True, help = "Your input email is invalid") parser.add_argument('new_password', location='json', required=True, help = "Your input password is invalid") args = parser.parse_args() ...
Python
nomic_cornstack_python_v1
import os import random import time import argparse import FuzzyCMeans import pandas as pd import numpy as np import logging function log_val out_path cluster_scores begin set column_labels = list string File *list(range(2, 11)) * 2 set df = call DataFrame cluster_scores columns=column_labels to csv df path_or_buf=out_...
import os import random import time import argparse import FuzzyCMeans import pandas as pd import numpy as np import logging def log_val(out_path, cluster_scores): column_labels = ["File", *list(range(2, 11))*2] df = pd.DataFrame(cluster_scores, columns=column_labels) df.to_csv(path_or_buf=out_path, inde...
Python
zaydzuhri_stack_edu_python
string Class example import re import time import logging import ConfigParser from crontab import CronTab from job import Job set LOGGER = call getLogger __name__ set CONFIG = config parser read CONFIG string siecle.cfg class Scheduler extends object begin string CLI class function __init__ self _crontab=none begin str...
"""Class example""" import re import time import logging import ConfigParser from crontab import CronTab from .job import Job LOGGER = logging.getLogger(__name__) CONFIG = ConfigParser.ConfigParser() CONFIG.read("siecle.cfg") class Scheduler(object): """CLI class""" def __init__(self, _crontab = None): ...
Python
zaydzuhri_stack_edu_python
from __future__ import print_function import numpy as np from sklearn.metrics import f1_score import warnings import matplotlib.pyplot as plt filter warnings string ignore class RegularizedLogisticRegression begin function __init__ self learning_rate=0.001 reg_factor=0.01 rand_seed=none begin set learning_rate = learni...
from __future__ import print_function import numpy as np from sklearn.metrics import f1_score import warnings import matplotlib.pyplot as plt warnings.filterwarnings("ignore") class RegularizedLogisticRegression: def __init__(self,learning_rate=0.001,reg_factor=0.01,rand_seed=None): self.learning_rate = learnin...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Jan 17 18:43:01 2017 @author: nimselsa function words s begin set word_string = split s set word_dict = dict for word in word_string begin if call isnumber begin set word = integer word end if word in word_dict begin set word_dict at word = word_dict at word + 1 end ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 17 18:43:01 2017 @author: nimselsa """ def words(s): word_string = s.split() word_dict={} for word in word_string: if word.isnumber(): word = int(word) if word in word_dict: word_dict[word]+= 1 else: ...
Python
zaydzuhri_stack_edu_python
import socket import sys import time import random set CHUNK_SIZE = 4096
import socket import sys import time import random CHUNK_SIZE = 4096
Python
zaydzuhri_stack_edu_python
import pygame from numpy import linalg , matrix , array import graphics set font = call SysFont string Droif Serif 20 set info_c = list 255 100 55 class TopBar extends object begin string This class involves a couple of pieces of information box that flashes messages including 'evade', 'extinction', etc. text for previ...
import pygame from numpy import linalg, matrix, array import graphics font = pygame.font.SysFont("Droif Serif", 20) info_c = [255,100,55] class TopBar(object): '''This class involves a couple of pieces of information box that flashes messages including 'evade', 'extinction', etc. text for previous lifespans grap...
Python
zaydzuhri_stack_edu_python
function get_timeseries rics fields=string * start_date=none end_date=none interval=string daily count=none calendar=none corax=none normalize=false raw_output=false debug=false begin set logger = logger comment set the ric(s) in the payload call check_for_string_or_list_of_strings rics string rics if call is_string_ty...
def get_timeseries(rics, fields='*', start_date=None, end_date=None, interval='daily', count=None, calendar=None, corax=None, normalize=False, raw_output=False, debug=False): logger = eikon.Profile.get_profile().logger # set the ric(s) in the payload check_for_string_...
Python
nomic_cornstack_python_v1
set ladoa = integer input string digite o valor do primeiro lado: set ladob = integer input string digite o valor do segundo lado: set ladoc = integer input string digite o valor do terceiro lado: if ladoa * ladoa + ladob * ladob == ladoc * ladoc begin print string Isso e um triangulo retangulo end else if ladoa * lado...
ladoa = int(input('digite o valor do primeiro lado: ')) ladob = int(input('digite o valor do segundo lado: ')) ladoc = int(input('digite o valor do terceiro lado: ')) if(((ladoa*ladoa)+(ladob*ladob))==(ladoc*ladoc)): print("Isso e um triangulo retangulo") elif(((ladoa*ladoa)+(ladoc*ladoc))==(ladob*ladob)): ...
Python
zaydzuhri_stack_edu_python
function _build self lr_schedule begin set pi_head = to call MLP input_dim=feat_dim layer_dims=net_arch at string pi act_fn=act_fn device set vf_head = to call MLP input_dim=vf_feat_dim layer_dims=net_arch at string vf act_fn=act_fn device if is instance action_dist DiagGaussianDistribution begin set tuple action_net l...
def _build(self, lr_schedule: Schedule) -> None: self.pi_head = MLP(input_dim=self.feat_dim, layer_dims=self.net_arch['pi'], act_fn=self.act_fn).to(self.device) self.vf_head = MLP(input_dim=self.vf_feat_dim, layer_dims=sel...
Python
nomic_cornstack_python_v1
import threading class CrawlThread extends Thread begin function __init__ self c progress_bar begin call __init__ self set crawler = c set progress_bar = progress_bar end function function run self begin while numberOfVisitedPage < n and length queue > 0 begin acquire lockQueue set currentURL = pop queue 0 release lock...
import threading class CrawlThread(threading.Thread): def __init__(self, c, progress_bar): threading.Thread.__init__(self) self.crawler = c self.progress_bar = progress_bar def run(self): while self.crawler.numberOfVisitedPage < self.crawler.n and len(self.crawler.queue) > 0: ...
Python
zaydzuhri_stack_edu_python
string This file was a first pass at developing an algorithm for calculating minimum Starbucks distance with better than n^2 efficiency. The idea was to use the concept of quadtrees (see here: https://en.wikipedia.org/wiki/Quadtree). The original plan was as follows: -- Create a lat/long grid by using the min/max lat/l...
''' This file was a first pass at developing an algorithm for calculating minimum Starbucks distance with better than n^2 efficiency. The idea was to use the concept of quadtrees (see here: https://en.wikipedia.org/wiki/Quadtree). The original plan was as follows: -- Create a lat/long grid by using the min/max lat/l...
Python
zaydzuhri_stack_edu_python
function convert_to_digits str_input seed len_out begin set s = string set i = 0 while i < len_out begin set m = search str_input i if not m begin break end set j = start m - i if j > 0 begin set s = s + str_input at slice i : i + j : end set s = s + character seed + ordinal str_input at i % 10 + 48 set i = i + j + 1...
def convert_to_digits(str_input, seed, len_out): s = '' i = 0 while i < len_out: m = RE_NON_NUMERIC.search(str_input, i) if not m: break j = m.start() - i if j > 0: s += str_input[i: i + j] s += chr((seed + ord(str_input[i])) % 10 + 48) ...
Python
nomic_cornstack_python_v1
function ask_for_reject self average_index begin set reject = get get get get org string Calibration dict string Analysis dict string AuxValues dict string RejectIndex list set text = input string Do you want to keep the current set of rejected data points with indices: + string reject + string (type enter if ok)? if t...
def ask_for_reject(self, average_index): reject = self.org.get('Calibration', {}).get('Analysis', {}).get('AuxValues', {}).get('RejectIndex', []) text = input("Do you want to keep the current set of rejected data points with indices: " + str(reject) + " (type enter if ok)? ") if text != "": ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2 function factorial num begin if num == 1 begin return num end else begin return num * call factorial num - 1 end end function set num = input string enter number if num < 0 begin print string fact cannt be of negative number end else if num == 0 begin print string fact is 1 end else begin prin...
#!/usr/bin/python2 def factorial(num): if num==1: return num else: return num*factorial(num-1) num=input("enter number") if num<0: print("fact cannt be of negative number") elif num==0: print("fact is 1") else : print("factorial of givn number is" , factorial(num))
Python
zaydzuhri_stack_edu_python
function _responds_html response begin call responds_http_status 200 call responds_content_type string text/html end function comment TODO: delayed HTML validation comment response.responds_with_valid_html() comment todo: links responds_with_valid_links
def _responds_html(response): response.responds_http_status(200) response.responds_content_type('text/html') # TODO: delayed HTML validation # response.responds_with_valid_html() # todo: links responds_with_valid_links
Python
nomic_cornstack_python_v1
function __getattr__ self attr begin if attr in NP_OVERLOAD begin set ufunc = call __getattribute__ attr function func begin return call _new_func lambda x -> call ufunc call _eval x end function set __name__ = attr set __doc__ = format string wraps numpy ufunc: {} attr return func end return call __getattribute__ attr...
def __getattr__(self,attr): if attr in NP_OVERLOAD: ufunc = np.__getattribute__(attr) def func(): return self._new_func( lambda x: ufunc( self._eval(x) ) ) func.__name__ = attr func.__doc__ = "wraps numpy ufunc: {}".format(attr) return...
Python
nomic_cornstack_python_v1
function log_like_iid_gamma_log_params params t begin set tuple alpha b = params if alpha <= 0 or b <= 0 begin return - inf end return sum call logpdf t alpha scale=1 / b end function
def log_like_iid_gamma_log_params(params, t): alpha, b = params if(alpha <= 0 or b <= 0): return -np.inf return np.sum(st.gamma.logpdf(t, alpha, scale = 1/b))
Python
nomic_cornstack_python_v1
comment Author: Ronak from classes.issue import Issue from datetime import datetime function create_issue db user_id begin set issue = input string Type in your issue: set issue = call Issue user_id issue set result = insert db string ISSUE issue if result is not false begin print string Issue saved... end end function...
# Author: Ronak from classes.issue import Issue from datetime import datetime def create_issue(db, user_id): issue = input("Type in your issue: ") issue = Issue(user_id, issue) result = insert(db, "ISSUE", issue) if (result is not False): print("Issue saved...") def insert(db, table_name, ...
Python
zaydzuhri_stack_edu_python
import pytest from datetime import datetime from decimal import Decimal from credit_card.utils import RecordTranslator from credit_card.models import CreditCardRecord decorator fixture function csv_row begin return b'2015-07-27,,IOF de "Tjmaxx $0142 Norwell Ma",14.05\n' end function decorator fixture function invalid_c...
import pytest from datetime import datetime from decimal import Decimal from credit_card.utils import RecordTranslator from credit_card.models import CreditCardRecord @pytest.fixture def csv_row(): return b'2015-07-27,,IOF de "Tjmaxx $0142 Norwell Ma",14.05\n' @pytest.fixture def invalid_csv_row(): return b',...
Python
zaydzuhri_stack_edu_python
function __init__ self pyclass ofwhat pname=none inorder=false inline=false mutable=true mixed=false mixed_aname=string _text **kw begin call __init__ self pname pyclass=pyclass keyword kw set inorder = inorder set inline = inline set mutable = mutable set mixed = mixed set mixed_aname = none if mixed is true begin set...
def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False, mutable=True, mixed=False, mixed_aname='_text', **kw): TypeCode.__init__(self, pname, pyclass=pyclass, **kw) self.inorder = inorder self.inline = inline self.mutable = mutable self.mixed = mixed ...
Python
nomic_cornstack_python_v1
comment encoding: UTF-8 comment Autor:Angel Roberto Pesado Bartolo, A01374942 comment Descripcion: Elaborar un algoritmo que pida al usuario las coordenadas de un punto y obtener el angulo y la magnitud. comment A partir de aquí escribe tu programa import math set x = decimal input string Dame el valor en x: set y = de...
#encoding: UTF-8 # Autor:Angel Roberto Pesado Bartolo, A01374942 # Descripcion: Elaborar un algoritmo que pida al usuario las coordenadas de un punto y obtener el angulo y la magnitud. # A partir de aquí escribe tu programa import math x=float(input("Dame el valor en x: ")) y=float(input("Dame el valor ...
Python
zaydzuhri_stack_edu_python
function register_model_architecture model_name arch_name begin function register_model_arch_fn fn begin if model_name not in MODEL_REGISTRY begin raise call ValueError format string Cannot register model architecture for unknown model type ({}) model_name end if arch_name in ARCH_MODEL_REGISTRY begin raise call ValueE...
def register_model_architecture(model_name, arch_name): def register_model_arch_fn(fn): if model_name not in MODEL_REGISTRY: raise ValueError('Cannot register model architecture for unknown model type ({})'.format(model_name)) if arch_name in ARCH_MODEL_REGISTRY: raise Value...
Python
nomic_cornstack_python_v1
function recurrence self begin return get pulumi self string recurrence end function
def recurrence(self) -> pulumi.Input[str]: return pulumi.get(self, "recurrence")
Python
nomic_cornstack_python_v1
import os from glob import glob import managers.dataset_manager as dmng from commons import Commons from train import train_nn , train_svm , predict , evaluate_model , kfold_nn , kfold_svm import numpy as np function cls begin call system if expression name == string nt then string cls else string clear end function fu...
import os from glob import glob import managers.dataset_manager as dmng from commons import Commons from train import train_nn, train_svm, predict, evaluate_model, kfold_nn, kfold_svm import numpy as np def cls(): os.system('cls' if os.name == 'nt' else 'clear') def initialize_dataset(): dmng.initialize() ...
Python
zaydzuhri_stack_edu_python
comment vim: ts=4:sw=4:sts=4:et comment -*- coding:utf-8 -*- import os import json import pkg_resources set resource_package = __name__ class SensitiveTree extends object begin string {'key': {'child_key':{'child_key1': {'is_end': true}}, 'is_end': false}, 'is_end': false} function __init__ self tree_types=list string ...
# vim: ts=4:sw=4:sts=4:et # -*- coding:utf-8 -*- import os import json import pkg_resources resource_package = __name__ class SensitiveTree(object): """ {'key': {'child_key':{'child_key1': {'is_end': true}}, 'is_end': false}, 'is_end': false} """ def __init__(self, tree_typ...
Python
zaydzuhri_stack_edu_python
function parse_xdot_data self data begin string Parses xdot data and returns the associated components. set parser = parser comment if pyparsing_version >= "1.2": comment parser.parseWithTabs() if data begin return call parseString data end else begin return list end end function
def parse_xdot_data(self, data): """ Parses xdot data and returns the associated components. """ parser = self.parser # if pyparsing_version >= "1.2": # parser.parseWithTabs() if data: return parser.parseString(data) else: return []
Python
jtatman_500k
import importlib import os from routersploit.core.exploit import print_error from routersploit.core.exploit.exceptions import RoutersploitException from routersploit.core.exploit.utils import humanize_path from routersploit.extsploit.settings import ENGINE_DIR , SAVE_DIR function index_modules modules_directory begin s...
import importlib import os from routersploit.core.exploit import ( print_error ) from routersploit.core.exploit.exceptions import RoutersploitException from routersploit.core.exploit.utils import humanize_path from routersploit.extsploit.settings import ENGINE_DIR, SAVE_DIR def index_modules(modules_directory: s...
Python
zaydzuhri_stack_edu_python
from leetcode26 import Solution set sln = call Solution function test_case0 begin set nums = list 1 1 2 assert list 1 2 == nums at slice : call removeDuplicates nums : end function function test_case1 begin set nums = list 0 0 1 1 1 2 2 3 3 4 assert list 0 1 2 3 4 == nums at slice : call removeDuplicates nums : end...
from leetcode26 import Solution sln = Solution() def test_case0(): nums = [1, 1, 2] assert [1, 2] == nums[:sln.removeDuplicates(nums)] def test_case1(): nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] assert [0, 1, 2, 3, 4] == nums[:sln.removeDuplicates(nums)] def test_case2(): nums = [-1, 0, 0, 0, 0, ...
Python
zaydzuhri_stack_edu_python
function _frequency_and_multiplier freq_type begin set multiplier = 1 if freq_type == 5 begin set freq_type = 3 end return tuple freq_type multiplier end function
def _frequency_and_multiplier(freq_type): multiplier = 1 if freq_type == 5: freq_type = 3 return freq_type, multiplier
Python
nomic_cornstack_python_v1
comment utilização desta feature em: "Functional discrimination of membrane proteins using machine learning techniques" function create_aminoacid_occurrence data begin set data = data set FEATURES = array tuple string Alanine-A string Arginine-R string Asparagine-N string Aspartiv Acid-D string Cysteine-C string Gluman...
def create_aminoacid_occurrence(data): #utilização desta feature em: "Functional discrimination of membrane proteins using machine learning techniques" data=data FEATURES=np.array(("Alanine-A","Arginine-R","Asparagine-N","Aspartiv Acid-D","Cysteine-C","Glumanine-Q", "Glutamic acid-E","...
Python
nomic_cornstack_python_v1
import requests import urllib import json set access_token = string Your Access Token function get_page_data page_id begin set count = 0 set url = string https://graph.facebook.com/ + string page_id + string /feed?limit=100&access.token= + access_token set data = get requests url set response = loads text comment Print...
import requests import urllib import json access_token='Your Access Token' def get_page_data(page_id): count=0 url='https://graph.facebook.com/'+str(page_id)+'/feed?limit=100&access.token='+access_token data=requests.get(url) response=json.loads(data.text) #Prints all messages of posts. for post in response['data...
Python
zaydzuhri_stack_edu_python
function forwards apps schema_editor begin set Event = call get_model string spectator_events string Event set Work = call get_model string spectator_events string Work set WorkRole = call get_model string spectator_events string WorkRole set WorkSelection = call get_model string spectator_events string WorkSelection f...
def forwards(apps, schema_editor): Event = apps.get_model("spectator_events", "Event") Work = apps.get_model("spectator_events", "Work") WorkRole = apps.get_model("spectator_events", "WorkRole") WorkSelection = apps.get_model("spectator_events", "WorkSelection") for event in Event.objects.filter(ki...
Python
nomic_cornstack_python_v1
function __getattr__ self attrib begin raise call NotImplementedError string This function can only be used in an Azure Synapse Spark environment. end function
def __getattr__(self, attrib): raise NotImplementedError( "This function can only be used in an Azure Synapse Spark environment." )
Python
nomic_cornstack_python_v1
function _read_bytes_to_framed_body self b begin string Reads the requested number of bytes from source to a streaming framed message body. :param int b: Number of bytes to read :returns: Bytes read from source stream, encrypted, and serialized :rtype: bytes debug string collecting %d bytes b set _b = b if b > 0 begin ...
def _read_bytes_to_framed_body(self, b): """Reads the requested number of bytes from source to a streaming framed message body. :param int b: Number of bytes to read :returns: Bytes read from source stream, encrypted, and serialized :rtype: bytes """ _LOGGER.debug("colle...
Python
jtatman_500k
comment -*- coding: utf-8 -*- comment Wechat.py import os from wxpy import * class Wechat begin string 微信处理类 对微信的消息进行处理,分析并作出回应 function __init__ self group_name admin_name begin comment 类被实例化的时候即对机器人实例化 set bot = call Bot comment 指定群聊名 set group_name = group_name comment 管理员微信名 set admin_name = admin_name comment 过滤后的...
# -*- coding: utf-8 -*- # Wechat.py import os from wxpy import * class Wechat: """ 微信处理类 对微信的消息进行处理,分析并作出回应 """ def __init__(self, group_name, admin_name): self.bot = Bot() # 类被实例化的时候即对机器人实例化 self.group_name = group_name # 指定群聊名 self.admin_name = admin_name # 管理员微信名 ...
Python
zaydzuhri_stack_edu_python
function backTrack assignment csp domain method=string natural begin comment assignment的定义:dict index=color comment backTrack:通过递归,对assignment做尝试赋值并AC-3检查,保存副本(浪费空间,但是作为练习够用),失败则回复副本. comment domain:当前domain assignment:当前赋值位置 comment csp:问题描述(static) comment method:选择下一个变量采用的方法 if length assignment == length csp begin ...
def backTrack(assignment, csp, domain, method='natural'): # assignment的定义:dict index=color # backTrack:通过递归,对assignment做尝试赋值并AC-3检查,保存副本(浪费空间,但是作为练习够用),失败则回复副本. # domain:当前domain assignment:当前赋值位置 # csp:问题描述(static) # method:选择下一个变量采用的方法 if len(assignment) == len(csp): return assignment ...
Python
zaydzuhri_stack_edu_python
string 1) Start from the snap file which contains only particles along the line of sight 2) Read in the caesar list of satellite galaxies and their positions and sizes 3) For each satellite, get the particles in the snap file which are associated with the satellite 4) Get unique particle ids, save out particle ids file...
""" 1) Start from the snap file which contains only particles along the line of sight 2) Read in the caesar list of satellite galaxies and their positions and sizes 3) For each satellite, get the particles in the snap file which are associated with the satellite 4) Get unique particle ids, save out particle ids file "...
Python
zaydzuhri_stack_edu_python
import pygame as pg class Butterfly extends object begin set colors = list string blue string red string green string yellow string pink set velocities = set comprehension tuple x y for x in tuple - 1 0 1 for y in tuple - 1 0 1 function __init__ self rect begin set color = call chocie colors set images = cycle list GFX...
import pygame as pg class Butterfly(object): colors = ["blue", "red", "green", "yellow", "pink"] velocities = {(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1)} def __init__(self, rect): self.color = chocie(self.colors) self.images = cycle([prepare.GFX["butterfly{}{}".format(self.color,...
Python
zaydzuhri_stack_edu_python
function table x begin set c = counter x return tuple list c list values c end function
def table(x): c = Counter(x) return list(c), list(c.values())
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Nov 6 15:17:21 2019 @author: benja import os import pandas as pd import re from author_work import aut_cleaner import utils import numpy as np comment %% set topics = call load_topics function parse_ref string begin string Parser for reference sub-strings. Returns a p...
# -*- coding: utf-8 -*- """ Created on Wed Nov 6 15:17:21 2019 @author: benja """ import os import pandas as pd import re from author_work import aut_cleaner import utils import numpy as np #%% topics= utils.load_topics() def parse_ref(string): '''Parser for reference sub-strings. Re...
Python
zaydzuhri_stack_edu_python
function mdcext a b begin set resto = a % b set q = a // b if resto == 0 begin return tuple 0 1 b end set tuple x y mdc = call mdcext b resto return tuple y x - q * y mdc end function set tuple x y mdc = call mdcext a b print mdc x y
def mdcext(a, b): resto = a%b q = a//b if resto==0: return (0,1,b) x,y,mdc = mdcext(b,resto) return (y,x-q*y,mdc) x,y,mdc = mdcext(a,b) print (mdc,x,y)
Python
zaydzuhri_stack_edu_python
function waiting_approval_loan self begin call ensure_one set due_date = call from_string start_date + time delta duration * 365 / 12 set state = string open end function
def waiting_approval_loan(self): self.ensure_one() self.due_date = fields.Datetime.from_string(self.start_date) + timedelta(self.duration * 365 / 12) self.state = 'open'
Python
nomic_cornstack_python_v1
function game_score self begin set score = call quantize call Decimal string 0.001 return if expression score > 0 then score else 0 end function
def game_score(self): score = self.score.quantize(Decimal('0.001')) return score if score > 0 else 0
Python
nomic_cornstack_python_v1
class TicTacToe begin function __init__ self curr_player begin set board = dict 1 string ; 2 string ; 3 string ; 4 string ; 5 string ; 6 string ; 7 string ; 8 string ; 9 string set curr_player = curr_player end function function display_board self begin comment representing the board print board at 1 + string ...
class TicTacToe(): def __init__(self, curr_player): self.board = {1: "", 2: "", 3: "", 4: "", 5: "", 6: "", 7: "", 8: "", 9: ""} self.curr_player = curr_player def display_board(self): #representing the board print(self.board[1] + " | " + self.board[2] + " | " + self.board[3]) print(self.board[4] + " | " +...
Python
zaydzuhri_stack_edu_python
function __getitem__ self k begin set it = call __getitem__ self k if it != none begin return it at 1 end else begin return it end end function
def __getitem__(self, k): it = Historial.__getitem__(self, k) if it != None: return it[1] else: return it
Python
nomic_cornstack_python_v1