code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function plane_sphere p s
begin
call normalize
set d = dot o - o n
if d > r
begin
return false
end
else
begin
return tuple o - d * n square root r * r - d * d
end
end function | def plane_sphere(p, s):
p.normalize()
d = dot(s.o-p.o, p.n)
if d > s.r:
return False
else:
return (s.o - d*p.n, sqrt(s.r*s.r - d*d)) | Python | nomic_cornstack_python_v1 |
import kivy
call require string 1.7.2
string List of known kivy "peculiarities": - do NOT pass 'parent=XXX' to a widget constructor, because the parent widget is not properly linked to the child. However, the child widget still thinks he's not an orphan... :D - passing position and size to a widget constructor will do ... | import kivy
kivy.require("1.7.2")
"""
List of known kivy "peculiarities":
- do NOT pass 'parent=XXX' to a widget constructor, because the parent widget is not properly
linked to the child. However, the child widget still thinks he's not an orphan... :D
- passing position and size to a widget constructor will do t... | Python | zaydzuhri_stack_edu_python |
class CreditCardProcessor
begin
function __init__ self
begin
set cards = dict
set payments = dict
end function
function add_card self card_number card_holder_name
begin
set cards at card_number = card_holder_name
end function
function process_payment self card_number amount
begin
if card_number not in cards
begin
rai... | class CreditCardProcessor:
def __init__(self):
self.cards = {}
self.payments = {}
def add_card(self, card_number, card_holder_name):
self.cards[card_number] = card_holder_name
def process_payment(self, card_number, amount):
if card_number not in self.cards:
... | Python | flytech_python_25k |
function testconfig self
begin
set configuration = call getNodeTag self xmlDoc string configuration
set metadatadb = call getNodeTag self configuration string metadatadb
set user = call getNodeVal self metadatadb string user
set host = call getNodeVal self metadatadb string host
set port = call getNodeVal self metadata... | def testconfig(self):
configuration = Parser.getNodeTag(self, self.xmlDoc, "configuration")
metadatadb = Parser.getNodeTag(self, configuration, "metadatadb")
self.user = Parser.getNodeVal(self, metadatadb, "user")
self.host = ... | Python | nomic_cornstack_python_v1 |
import argparse
import glob
from PIL import Image
from tqdm import tqdm
function run height width
begin
set path = string C:/Users/forth/warpgrad/src/omniglot/data/omniglot-py/images_resized/
string Resize images
print string resizing images
set all_images = glob glob path + string */*/*
print all_images
for image_file... | import argparse
import glob
from PIL import Image
from tqdm import tqdm
def run(height, width):
path = 'C:/Users/forth/warpgrad/src/omniglot/data/omniglot-py/images_resized/'
"""Resize images"""
print('resizing images')
all_images = glob.glob(path + '*/*/*')
print(all_images)
for image_fil... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat Mar 7 20:18:17 2020 Content Columns age: age of primary beneficiary sex: insurance contractor gender, female, male bmi: Body mass index, providing an understanding of body, weights that are relatively high or low relative to height, objective index of body weight (kg ... | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 20:18:17 2020
Content
Columns
age: age of primary beneficiary
sex: insurance contractor gender, female, male
bmi: Body mass index, providing an understanding of body, weights that are relatively high or low relative to height,
objective index of body weigh... | Python | zaydzuhri_stack_edu_python |
function get_records field_id
begin
if not is_xhr
begin
call abort 403
end
if field_id == 0
begin
set field_id = get session string current_field_id 2
end
set field = get query field_id
set records = call limit 10
set top_10 = list
for record in records
begin
set is_you = false
set current_player = get session string ... | def get_records(field_id):
if not request.is_xhr:
abort(403)
if field_id == 0:
field_id = session.get('current_field_id', 2)
field = Field.query.get(field_id)
records = field.records.limit(10)
top_10 = []
for record in records:
is_you = False
current_player = se... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
set driver = call Chrome string C:/Users/vijay/Downloads/chromedriver_win32/chromedriver
set hotels = list
set prices = list
get driver string https://www.makemytrip.com/hotels/hotel-listing/?checkin=10022020&city=CTXDB&checkout=11022020... | from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
driver = webdriver.Chrome("C:/Users/vijay/Downloads/chromedriver_win32/chromedriver")
hotels=[]
prices=[]
driver.get("https://www.makemytrip.com/hotels/hotel-listing/?checkin=10022020&city=CTXDB&checkout=11022020&roomStayQualifier=... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Mar 21 10:20:10 2019 @author: Studente
import math
cos pi / 4
square root 81
import random
random choice list string apple string pear string banana string watermelon
set random_numbers = random sample range 100 10
print random_numbers
random
import statistics
set dat... | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 10:20:10 2019
@author: Studente
"""
import math
math.cos(math.pi/4)
math.sqrt(81)
import random
random.choice(["apple","pear","banana","watermelon"])
random_numbers = random.sample(range(100), 10)
print(random_numbers)
random.random()
import statistics
data = [... | Python | zaydzuhri_stack_edu_python |
function graph_GOT
begin
set resource_package = __name__
set resource_path = join string / tuple string toy_data string GoT_dyn_ts10
set fileLocation = call resource_filename resource_package resource_path
set dg = call read_snapshots fileLocation prefix=string GoT_SXXEXX_
return dg
end function | def graph_GOT():
resource_package = __name__
resource_path = '/'.join(('toy_data', 'GoT_dyn_ts10'))
fileLocation = pkg_resources.resource_filename(resource_package, resource_path)
dg = tn.read_snapshots(fileLocation,prefix="GoT_SXXEXX_")
return dg | Python | nomic_cornstack_python_v1 |
function test_performance_of_binary_outcome_models fixed_synthetic_bandit_feedback random_action_dist
begin
set bandit_feedback = copy fixed_synthetic_bandit_feedback
set expected_reward = bandit_feedback at string expected_reward at tuple slice : : slice : : newaxis
set action_dist = random_action_dist
comment c... | def test_performance_of_binary_outcome_models(
fixed_synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray
) -> None:
bandit_feedback = fixed_synthetic_bandit_feedback.copy()
expected_reward = bandit_feedback["expected_reward"][:, :, np.newaxis]
action_dist = random_action_dist
#... | Python | nomic_cornstack_python_v1 |
function test_check_if_error_one self
begin
with assert raises MyError
begin
call check_if_error
end
end function | def test_check_if_error_one(self):
with self.assertRaises(MyError):
SshpassErrorExitCodeController(ERROR_RETURN_CODE, ERROR_MESSAGE)\
.check_if_error() | Python | nomic_cornstack_python_v1 |
function setup_remote_site self
begin
comment Create tenant, L3out with contract on site 2
set site2 = call Session SITE2_URL SITE2_LOGIN SITE2_PASSWORD
set resp = call login
assert true ok
set tenant = call Tenant string intersite-testsuite
set l3out = call OutsideL3 string l3out tenant
set resp = call push_to_apic si... | def setup_remote_site(self):
# Create tenant, L3out with contract on site 2
site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD)
resp = site2.login()
self.assertTrue(resp.ok)
tenant = Tenant('intersite-testsuite')
l3out = OutsideL3('l3out', tenant)
resp = ten... | Python | nomic_cornstack_python_v1 |
function get_response self timeout=10
begin
if poll runningPlayer is none
begin
set exceptionFromThread = none
set thread = thread target=__get_response_thread
set daemon = true
start thread
join thread timeout
if exceptionFromThread is not none
begin
raise exceptionFromThread
end
if is alive thread
begin
raise call Bo... | def get_response(self, timeout=10):
if self.runningPlayer.poll() is None:
self.exceptionFromThread = None
thread = threading.Thread(target=self.__get_response_thread)
thread.daemon = True
thread.start()
thread.join(timeout)
if self.exceptio... | Python | nomic_cornstack_python_v1 |
comment stack[-1]이랑 비교해서 같으면 pop(), 다르면 append()
set N = integer input
set array = list
for _ in range N
begin
append array input
end
set stack = list
set cnt = 0
for string in array
begin
set stack = list
for i in range length string
begin
if not stack
begin
append stack string at i
end
else
if string at i == stack... | # stack[-1]이랑 비교해서 같으면 pop(), 다르면 append()
N = int(input())
array = []
for _ in range(N):
array.append(input())
stack = []
cnt = 0
for string in array:
stack = []
for i in range(len(string)):
if not stack:
stack.append(string[i])
else:
if string[i] == stack[-1]:
... | Python | zaydzuhri_stack_edu_python |
function test_parse_feed_data_rss_invalid_feed self
begin
set provider = call get_provider string RSS
set result = call parse_feed_data access_token rss_feed_data get SOCIAL_KEY_MAPPING string RSS social_links_rss_feed timestamp
for feed in result
begin
assert equal feed at string social_link_id id
assert not equal key... | def test_parse_feed_data_rss_invalid_feed(self):
provider = get_provider('RSS')
result = provider.parse_feed_data(
self.access_token,
self.rss_feed_data, settings.SOCIAL_KEY_MAPPING.get('RSS'),
self.social_links_rss_feed, self.timestamp
)
for feed in r... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
set data = call loadtxt fname=string data/inflammation-01.csv delimiter=string ,
set ave_inflammation = mean np data axis=0
plot ave_inflammation
set max_inflammation = max data axis=0
plot max_inflammation | import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt(
fname = 'data/inflammation-01.csv',
delimiter = ',')
ave_inflammation = np.mean(
data,
axis = 0
)
plt.plot(ave_inflammation)
max_inflammation = np.max(
data,
axis = 0
)
plt.plot(max_inflammation)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
import requests
import csv
import asyncio
import datetime
import re
comment ---- Global Variables
set day = now
set query_date = string
comment ----
function build_market_science_url
begin
global query_date
set url = string https://marketsscience.com/daily_report_%Date%.html
set query_date = string... | import pandas as pd
import requests
import csv
import asyncio
import datetime
import re
# ---- Global Variables
day = datetime.datetime.now()
query_date = ""
# ----
def build_market_science_url():
global query_date
url = "https://marketsscience.com/daily_report_%Date%.html"
query_date = day.strftime("%d... | Python | zaydzuhri_stack_edu_python |
function __init__ self value_module=none value_class=none **kwargs
begin
set kwc = copy kwargs
call __init__ self keyword kwc
set _template_attrs = dict
set _value_module = value_module or string coverage_model.parameter_values
set _value_class = value_class or string NumericValue
end function | def __init__(self, value_module=None, value_class=None, **kwargs):
kwc=kwargs.copy()
AbstractIdentifiable.__init__(self, **kwc)
self._template_attrs = {}
self._value_module = value_module or 'coverage_model.parameter_values'
self._value_class = value_class or 'NumericValue' | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_ninfarray_okarray_infnum_okarray_a_386 self
begin
comment This version is expected to pass.
call fma okarrayx okarrayy oknumz arrayout matherrors=true
comment This should raise an error.
with assert raises ArithmeticError
begin
call fma ninfarrayx okarrayy infnumz arrayout
end
end function | def test_fma_nan_param_ninfarray_okarray_infnum_okarray_a_386(self):
# This version is expected to pass.
arrayfunc.fma(self.okarrayx, self.okarrayy, self.oknumz, self.arrayout, matherrors=True)
# This should raise an error.
with self.assertRaises(ArithmeticError):
arrayfunc.fma(self.ninfarrayx, self.okarray... | Python | nomic_cornstack_python_v1 |
function __le__ self other
begin
return not call __gt__ other
end function | def __le__(self, other):
return not self.__gt__(other) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string This Python script is designed to perform various types of Natural Language processing tasks. Module used: NLTK Module Reference: https://www.nltk.org NLTK functions: 1. Part of Speech tagging 2. Frequency of words 3. Most common words 4. Tokenization 5. Adjectives 6. Pronouns 7. Ad... | #!/usr/bin/env python3
"""
This Python script is designed to perform various types of Natural Language
processing tasks.
Module used: NLTK
Module Reference: https://www.nltk.org
NLTK functions:
1. Part of Speech tagging
2. Frequency of words
3. Most common words
4. Tokenization
5. Adjectives
6. Pronouns
7. Adverbs
8... | Python | zaydzuhri_stack_edu_python |
import pygame
comment 최대 속도
set MAX_SPEED = 3
function to_Zero num
begin
string 관성구현을 휘한 함수
if num < 0
begin
return 1
end
else
if num > 0
begin
return - 1
end
else
begin
return 0
end
end function
class Ball extends Sprite
begin
comment 이미지,설치좌표(튜플로 전달),넓이와 높이를 튜플로 전달 ex: (가로,세로),FPS
function __init__ self img location ... | import pygame
MAX_SPEED=3 #최대 속도
def to_Zero(num):
'''관성구현을 휘한 함수'''
if num < 0:
return 1
elif num > 0:
return -1
else:
return 0
class Ball(pygame.sprite.Sprite):
def __init__(self, img, location, area,FPS=30): # 이미지,설치좌표(튜플로 전달),넓이와 높이를 튜플로 전달 ex: (가로,세로),FPS
... | Python | zaydzuhri_stack_edu_python |
function selection_sort arr
begin
set i = 0
while i < length arr
begin
set j = i + 1
while j < length arr
begin
if arr at i > arr at j
begin
set tuple arr at i arr at j = tuple arr at j arr at i
end
set j = j + 1
end
set i = i + 1
end
return arr
end function
print call selection_sort list 31 17 1 7 34 13 | def selection_sort(arr):
i = 0
while i < len(arr):
j = i + 1
while j < len(arr):
if (arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
j += 1
i += 1
return arr
print(selection_sort([31, 17, 1, 7, 34, 13]))
| Python | zaydzuhri_stack_edu_python |
function filter_end_dashes self string
begin
set newstring = string
while newstring at - 1 == string -
begin
set newstring = newstring at slice 0 : - 1 :
end
return newstring
end function | def filter_end_dashes(self, string):
newstring = string
while newstring[-1] == '-':
newstring = newstring[0:-1]
return newstring | Python | nomic_cornstack_python_v1 |
function run_shell_command cmdstr **subprocess_kwargs
begin
if string shell in subprocess_kwargs and not subprocess_kwargs at string shell
begin
raise call ProgramError string The "shell" kwarg may be omitted, but if provided it must be True.
end
else
begin
set subprocess_kwargs at string shell = true
end
if string exe... | def run_shell_command(cmdstr, **subprocess_kwargs):
if 'shell' in subprocess_kwargs and not subprocess_kwargs['shell']:
raise ProgramError(
'The "shell" kwarg may be omitted, but if '
'provided it must be True.')
else:
subprocess_kwargs['shell'] = True
if 'ex... | Python | nomic_cornstack_python_v1 |
function no_emojis s
begin
return strip join string filter lambda x -> x in printable s
end function | def no_emojis(s):
return "".join(filter(lambda x: x in string.printable, s)).strip() | Python | nomic_cornstack_python_v1 |
import threading
import time
from bs4 import BeautifulSoup
import requests
from urllib.parse import quote
import lxml
import random
from fake_useragent import UserAgent
comment google news
class googleNews extends Thread
begin
function __init__ self base_url url path
begin
call __init__ self
set base_url = base_url
set... | import threading
import time
from bs4 import BeautifulSoup
import requests
from urllib.parse import quote
import lxml
import random
from fake_useragent import UserAgent
#google news
class googleNews(threading.Thread):
def __init__(self, base_url, url, path):
threading.Thread.__init__(self)
self.bas... | Python | zaydzuhri_stack_edu_python |
if max_cake - without_cake - 1 < 0
begin
print 0
end
else
begin
print max_cake - without_cake - 1
end | if (max_cake - without_cake - 1 < 0) :
print(0)
else :
print(max_cake - without_cake - 1) | Python | zaydzuhri_stack_edu_python |
function run_tests_asynchronous self class_ids
begin
set url = string /tooling/runTestsAsynchronous/?classids= + join string , class_ids
set result = get self url
return result
end function | def run_tests_asynchronous(self, class_ids):
url = "/tooling/runTestsAsynchronous/?classids=" + ",".join(class_ids)
self.result = self.get(url)
return self.result | Python | nomic_cornstack_python_v1 |
comment Dictionary to map the teams with their season stats, and their previously calculated ratings
comment JG, JE , JP , Pts, Rating
set teams_dictionary = dict string Monterrey list 5 2 0 17 1000 ; string Tigres list 5 1 1 16 1000 ; string Leon list 4 2 1 14 1000 ; string Chivas list 4 2 1 14 1000 ; string Necaxa li... | # Dictionary to map the teams with their season stats, and their previously calculated ratings
# JG, JE , JP , Pts, Rating
teams_dictionary = {
"Monterrey": [5, 2, 0, 17, 1000],
"Tigres": [5, 1, 1, 16, 1000],
"Leon": [4, 2, 1, 14, 1000],
"Chivas": [4, 2, 1, 14, 1000],
"Necaxa": [3, 2, 1, 11, 100... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2
class descriptor
begin
function __init__ self bins
begin
set bins = bins
end function
function describe self image
begin
set image = call cvtColor image COLOR_BGR2HSV
set features = list
set tuple h w = shape at slice : 2 :
set tuple cX cY = tuple integer w * 0.5 integer h * 0.5
set seg... | import numpy as np
import cv2
class descriptor:
def __init__(self,bins):
self.bins=bins
def describe(self,image):
image=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
features=[]
(h,w)= image.shape[:2]
(cX,cY)=(int(w*0.5),int(h*0.5))
segments=[(0,cX,0,cY),(cX,w,0,cY... | Python | zaydzuhri_stack_edu_python |
function CreateContactDicts self contacts
begin
set contact_dicts = list
for contact in contacts
begin
if type contact in list str unicode
begin
append contact_dicts dict string identity contact
end
else
if type contact in list int long
begin
append contact_dicts dict string user_id contact
end
else
begin
assert is in... | def CreateContactDicts(self, contacts):
contact_dicts = []
for contact in contacts:
if type(contact) in [str, unicode]:
contact_dicts.append({'identity': contact})
elif type(contact) in [int, long]:
contact_dicts.append({'user_id': contact})
else:
assert isinsta... | Python | nomic_cornstack_python_v1 |
function play_action self action
begin
if not call is_action_valid action
begin
raise call InvalidAction action
end
set tuple i1 j1 i2 j2 = action
set h1 = absolute m at i1 at j1
set h2 = absolute m at i2 at j2
if m at i1 at j1 < 0
begin
set m at i2 at j2 = - h1 + h2
end
else
begin
set m at i2 at j2 = h1 + h2
end
set m... | def play_action(self, action):
if not self.is_action_valid(action):
raise InvalidAction(action)
i1, j1, i2, j2 = action
h1 = abs(self.m[i1][j1])
h2 = abs(self.m[i2][j2])
if self.m[i1][j1] < 0:
self.m[i2][j2] = -(h1 + h2)
else:
self.m[i2... | Python | nomic_cornstack_python_v1 |
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Activation
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from keras.layers.recurrent import LSTM
from sklearn.preprocessing import MinMaxScaler
comment function to split ... | from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Activation
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from keras.layers.recurrent import LSTM
from sklearn.preprocessing import MinMaxScaler
# function to spl... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import time
import datetime
import re
function time_zh times
begin
if find all string : times
begin
set date = string format time time string %Y-%m-%d call localtime time
end
else
if times == string 发布于昨天
begin
set today = today
set oneday = time delta days=1
set date = today - oneday
end
... | # -*- coding: utf-8 -*-
import time
import datetime
import re
def time_zh(times):
if re.findall(':', times):
date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
elif times == u'发布于昨天':
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
date = today - one... | Python | zaydzuhri_stack_edu_python |
function _from_dict cls _dict
begin
return call from_dict _dict
end function | def _from_dict(cls, _dict):
return cls.from_dict(_dict) | Python | nomic_cornstack_python_v1 |
import re
class coche
begin
set matricula = string
set marca = string
set modelo = string
set precio_dia = string
set disponible = false
function __init__ self matricula marca modelo precio_dia disponible
begin
set matricula = matricula
set marca = marca
set modelo = modelo
set precio_dia = precio_dia
set disponibl... | import re
class coche:
matricula=""
marca=""
modelo=""
precio_dia=""
disponible = False
def __init__(self,matricula,marca,modelo,precio_dia,disponible):
self.matricula=matricula
self.marca=marca
self.modelo=modelo
self.precio_dia=precio_dia
... | Python | zaydzuhri_stack_edu_python |
function GetProduct self model
begin
set results = list comprehension p for p in _products if model == model
if not results
begin
raise call NotFoundError string Not found in Shopee: %s % model
end
if length results > 1
begin
error string Multiple results in Shopee: %s (item_ids: %s) % tuple model list comprehension it... | def GetProduct(self, model):
results = [p for p in self._products if p.model == model]
if not results:
raise NotFoundError("Not found in Shopee: %s" % model)
if len(results) > 1:
logging.error(
"Multiple results in Shopee: %s (item_ids: %s)"
... | Python | nomic_cornstack_python_v1 |
function insert self index value
begin
insert list self index value
call changed
end function | def insert(self, index, value):
list.insert(self, index, value)
self.changed() | Python | nomic_cornstack_python_v1 |
function clean_up_terminal self
begin
if stdscr
begin
comment Disable the Keypad mode
call keypad false
comment Renable caracters echoing
call echo
comment Disable the interrupts
call nocbreak
comment Restore the terimnal to it's orginial operating mode
call endwin
end
end function | def clean_up_terminal(self) -> None:
if self.stdscr:
# Disable the Keypad mode
self.stdscr.keypad(False)
# Renable caracters echoing
curses.echo()
# Disable the interrupts
curses.nocbreak()
# Restore the terimnal to it's orginia... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Sep 22 21:15:27 2019 @author: klal1
from keras.layers import Conv2D , DepthwiseConv2D , Input , Concatenate , Add , UpSampling2D
from keras.layers import BatchNormalization , Activation , GlobalAveragePooling2D , Reshape
from keras.models import Model
comment from ker... | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 21:15:27 2019
@author: klal1
"""
from keras.layers import Conv2D, DepthwiseConv2D, Input, Concatenate, Add, UpSampling2D
from keras.layers import BatchNormalization, Activation, GlobalAveragePooling2D, Reshape
from keras.models import Model
#from keras.applications.x... | Python | zaydzuhri_stack_edu_python |
function getSizeRateFromEVM self
begin
set size = integer call getParam RUs at 0 string evb::EVM string superFragmentSize string xsd:unsignedInt
set rate = integer call getParam RUs at 0 string evb::EVM string eventRate string xsd:unsignedInt
return tuple size rate
end function | def getSizeRateFromEVM(self):
size = int(utils.getParam(self.config.RUs[0], 'evb::EVM',
'superFragmentSize', 'xsd:unsignedInt'))
rate = int(utils.getParam(self.config.RUs[0], 'evb::EVM',
'eventRate', 'xsd:unsignedInt'))
return size, rate | Python | nomic_cornstack_python_v1 |
function get_all_course_submission_information course_id item_type read_replica=true
begin
string For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant... | def get_all_course_submission_information(course_id, item_type, read_replica=True):
""" For the given course, get all student items of the given item type, all the submissions for those itemes,
and the latest scores for each item. If a submission was given a score that is not the latest score for the
releva... | Python | jtatman_500k |
function test_otoroshi_controllers_private_apps_controller_register_session self
begin
pass
end function | def test_otoroshi_controllers_private_apps_controller_register_session(self):
pass | Python | nomic_cornstack_python_v1 |
function get_pixmap model parentQSize=none
begin
from model import Model
set model : Model
if showingmode == ENTIRE
begin
set cvimg = call cvimread_unicode imgpath
end
else
if showingmode == SELECTED
begin
set cvimg = call cvimread_unicode selectedImgPath
end
set tuple h w c = shape
set ratio = zoomvalue / 100.0
set cv... | def get_pixmap(model, parentQSize=None):
from ..model import Model
model: Model
if model.showingmode == ShowingMode.ENTIRE:
cvimg = cvimread_unicode(model.imgpath)
elif model.showingmode == ShowingMode.SELECTED:
cvimg = cvimread_unicode(model.selectedImgPath)
h, w, c = cvimg.shape
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 16 23:08:24 2020 @author: Mane González
import json
with open string busqueda.json as file
begin
set data = load json file
end
set revisados = list
set camino = list
set auxiliar = list
set Nodsig = list
function primeroAnchura Carpeta Archivo
begin
if Carpeta... | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 23:08:24 2020
@author: Mane González
"""
import json
with open('busqueda.json') as file:
data = json.load(file)
revisados =[]
camino=[]
auxiliar = []
Nodsig=[]
def primeroAnchura(Carpeta,Archivo):
if Carpeta == Archivo:
return Archivo
if Nodsig... | Python | zaydzuhri_stack_edu_python |
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
set weights_path = join path string .. string .. string weights string csnn_two_level_inhibition string best
set assignments_path = join path string .. string .. str... | import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
weights_path = os.path.join('..', '..', 'weights', 'csnn_two_level_inhibition', 'best')
assignments_path = os.path.join('..', '..', 'assignments', 'csnn_two_level_... | Python | zaydzuhri_stack_edu_python |
function filterSpecies self
begin
for tuple specname specval in items species
begin
if specname not in constants
begin
update variablespecies dict specname specval
print specname
end
end
end function | def filterSpecies(self):
for specname, specval in self.species.items():
if specname not in self.constants:
self.variablespecies.update({specname: specval})
print(specname) | Python | nomic_cornstack_python_v1 |
comment -----------------------------------------------------------------------------
comment EntityManager
comment -----------------------------------------------------------------------------
class EntityManager
begin
set enitites = list
function add self entity
begin
append enitites entity
end function
function rem... | # -----------------------------------------------------------------------------
# EntityManager
# -----------------------------------------------------------------------------
class EntityManager:
enitites = []
def add (self, entity):
self.enitites.append(entity)
def remove (self, entity):
... | Python | zaydzuhri_stack_edu_python |
function tick self ms
begin
set tuple next_scene_id kwargs = call tick ms
comment quit via dummy scene constant
if next_scene_id == SCN_QUIT
begin
return OUT_QUIT
end
else
comment change scene
if next_scene_id is not none
begin
call pause
set cur_scene = scenes at next_scene_id
call resume keyword kwargs
end
return OUT... | def tick(self, ms):
next_scene_id, kwargs = self.cur_scene.tick(ms)
if next_scene_id == SCN_QUIT: # quit via dummy scene constant
return OUT_QUIT
elif next_scene_id is not None: # change scene
self.cur_scene.pause()
self.cur_scene = self.scenes[next_sc... | Python | nomic_cornstack_python_v1 |
function mpd_prop nRow nCol h p
begin
set mpd_out = call mpd nRow nCol h
set prop_out = call classifyArray mpd_out list 1 - p p
return prop_out
end function | def mpd_prop(nRow, nCol, h, p):
mpd_out = mpd(nRow, nCol, h)
prop_out = classifyArray(mpd_out, [1 - p, p])
return prop_out; | Python | nomic_cornstack_python_v1 |
import ast , re
comment from r"['[타이어 마찰음]\n', '오직 도깨비 신부만이\n', '\n']"
comment to [타이어 마찰음], 오직 도깨비 신부만
function prettify raw_str
begin
set subtitle_list = call literal_eval raw_str
set processed_str = string
for subtitle in subtitle_list
begin
set subtitle = sub string \n string subtitle
set processed_str = processe... | import ast, re
# from r"['[타이어 마찰음]\n', '오직 도깨비 신부만이\n', '\n']"
# to [타이어 마찰음], 오직 도깨비 신부만
def prettify(raw_str):
subtitle_list = ast.literal_eval(raw_str)
processed_str = ''
for subtitle in subtitle_list:
subtitle = re.sub(r'\n', '', subtitle)
processed_str += subtitle
return processed... | Python | zaydzuhri_stack_edu_python |
import os , json , sys
set dataDir = string /srv/runme/
set prefix = argv at 1
set f = open dataDir + prefix + string .txt string w
function dict_raise_on_duplicates ordered_pairs
begin
string Reject duplicate keys.
set d = dict
for tuple k v in ordered_pairs
begin
if k in d
begin
raise call ValueError string duplicat... | import os, json, sys
dataDir = '/srv/runme/'
prefix = sys.argv[1]
f = open(dataDir+prefix+'.txt', 'w')
def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Exercise 11.2. Read the documentation of the dictionary method setdefault and use it to write a more concise version of invert_dict. def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inve... | #!/usr/bin/env python3
"""
Exercise 11.2.
Read the documentation of the dictionary method setdefault and use it to write a
more concise version of invert_dict.
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
... | Python | zaydzuhri_stack_edu_python |
function etable_atom_pair_energies res1 atom_index_1 res2 atom_index_2 sfxn
begin
set score_manager = call get_instance
set etable_ptr = call etable call etable_type
set etable = lock
set etable_energy = call AnalyticEtableEnergy etable call energy_method_options
comment Construct coulomb class for calculating fa_elec ... | def etable_atom_pair_energies(res1, atom_index_1, res2, atom_index_2, sfxn):
score_manager = rosetta.core.scoring.ScoringManager.get_instance()
etable_ptr = score_manager.etable(sfxn.energy_method_options().etable_type())
etable = etable_ptr.lock()
etable_energy = rosetta.core.scoring.etable.AnalyticEta... | Python | nomic_cornstack_python_v1 |
function fig2array fig
begin
comment draw the renderer
call draw
comment Get the RGB buffer from the figure
set tuple w h = call get_width_height
set buf = call frombuffer call tostring_rgb dtype=uint8
set shape = tuple w h 3
return buf
end function | def fig2array(fig):
# draw the renderer
fig.canvas.draw()
# Get the RGB buffer from the figure
w, h = fig.canvas.get_width_height()
buf = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
buf.shape = (w, h, 3)
return buf | Python | nomic_cornstack_python_v1 |
async function persist_data self data
begin
set block = await call get_default_storage_block
if not block
begin
warn string No default storage has been set on the server. Using temporary local storage for results.
set block = call TempStorageBlock
end
set storage_token = await write block data
set storage_datadoc = enc... | async def persist_data(
self,
data: bytes,
) -> DataDocument:
block = await self.get_default_storage_block()
if not block:
warnings.warn(
"No default storage has been set on the server. "
"Using temporary local storage for results."
... | Python | nomic_cornstack_python_v1 |
from pathlib import Path
from os import listdir
import re
comment !/usr/bin/env python3
import os
import requests
import tkinter as tk
from tkinter import filedialog
from sys import exit
function set_text text
begin
delete 0 END
insert e 0 text
return
end function
function download_url url dest overwrite=false pbar=non... | from pathlib import Path
from os import listdir
import re
#!/usr/bin/env python3
import os
import requests
import tkinter as tk
from tkinter import filedialog
from sys import exit
def set_text(text):
e.delete(0,END)
e.insert(0,text)
return
def download_url(url, dest, overwrite=False, pbar=... | Python | zaydzuhri_stack_edu_python |
comment task #1243
comment Difficulty 53
print integer input % 7 | # task #1243
# Difficulty 53
print(int(input()) % 7)
| Python | zaydzuhri_stack_edu_python |
string 16. Construir un programa que simule el funcionamiento de una calculadora que puede realizar las cuatro operaciones aritméticas básicas(suma, resta, producto y división) con valores numéricos enteros. El usuario debe especificar la operación con el primer carácter del primer parámetro de la línea de comandos: S ... | """
16. Construir un programa que simule el funcionamiento de una calculadora que puede realizar las cuatro operaciones aritméticas básicas(suma, resta, producto y división) con valores numéricos enteros. El usuario debe especificar la operación con el primer carácter del primer parámetro de la línea de comandos: S o s... | Python | zaydzuhri_stack_edu_python |
function p_grid_t_output self p_grid_t_output
begin
set _p_grid_t_output = p_grid_t_output
end function | def p_grid_t_output(self, p_grid_t_output: SourceOutput):
self._p_grid_t_output = p_grid_t_output | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
import pandas as pd
comment In[2]:
comment remove all measurement
function measureRemover copy
begin
set Ingredients = replace str string ^\s* string
set Ingredients = replace str string pint\w* string
set Ingredients = replace str string dash\w* string
set Ingredients = replace str... | # coding: utf-8
# In[1]:
import pandas as pd
# In[2]:
# remove all measurement
def measureRemover(copy):
copy.Ingredients = copy.Ingredients.str.replace(r'^\s*', '')
copy.Ingredients = copy.Ingredients.str.replace(r'can\w*', '').str.replace(r'teaspoon\w*', '').str.replace(r'tablespoon\w*', '').str.replac... | Python | zaydzuhri_stack_edu_python |
function _parzen_torch dists width
begin
set hwidth = width / 2.0
set del_ovr_width = dists / hwidth
set near_mode = decimal
set in_tail = decimal
return near_mode * 1 - 6 * del_ovr_width ^ 2 * 1 - del_ovr_width + in_tail * 2 * 1 - del_ovr_width ^ 3
end function | def _parzen_torch(dists, width):
hwidth = width / 2.0
del_ovr_width = dists / hwidth
near_mode = (dists <= hwidth/2.0).float()
in_tail = ((dists > hwidth/2.0) * (dists <= hwidth)).float()
return near_mode * (1 - 6 * (del_ovr_width ** 2) * (1 - del_ovr_width)) \
+ in_tail * (2 * ((1 - del_... | Python | nomic_cornstack_python_v1 |
set ar1 = set literal 11 1 13 21 3 7
set ar2 = set literal 11 1 21 3
print call issubset ar1 | ar1={11, 1, 13, 21, 3, 7}
ar2= {11, 1,21,3}
print(ar2.issubset(ar1))
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
function empty_dict_list x
begin
string 정수를 전달받고 그 수만큼의 빈 사전 리스트를 반환하는 함수를 작성하자 sample in/out: count_of_dictionaries(5) -> [{}, {}, {}, {}, {}] count_of_dictionaries(10) -> [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
comment 여기 작성
comment 정수 개수 만큼
comment 비어있는 사전 리스트 반환하자.
set a = dictionary
... | # -*- coding: utf-8 -*-
def empty_dict_list(x):
""" 정수를 전달받고 그 수만큼의 빈 사전 리스트를 반환하는 함수를 작성하자
sample in/out:
count_of_dictionaries(5) -> [{}, {}, {}, {}, {}]
count_of_dictionaries(10) -> [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
"""
# 여기 작성
#정수 개수 만큼
#비어있는 사전 리스트 ... | Python | zaydzuhri_stack_edu_python |
comment 1.f=open('new.txt','r',encoding="utf8")
comment content=f.readlines()
comment n=int(input("enter number of lines you want to read from last"))
comment while n>0:
comment print(content[-n])
comment n-=1
comment f.close()
comment 2. f=open('new.txt','r',encoding="utf8")
comment w=input('enter the word you want to... | #1.f=open('new.txt','r',encoding="utf8")
#content=f.readlines()
#n=int(input("enter number of lines you want to read from last"))
#while n>0:
#print(content[-n])
#n-=1
#f.close()
#2. f=open('new.txt','r',encoding="utf8")
# w=input('enter the word you want to search')
# x=f.read()
# c=0
# for w in x:
# if w==x:
# c=c+... | Python | zaydzuhri_stack_edu_python |
function test_packageImport self
begin
call flakes string import fu.bar fu.bar
end function | def test_packageImport(self):
self.flakes('''
import fu.bar
fu.bar
''') | Python | nomic_cornstack_python_v1 |
while x != 0
begin
set x = input decimal string digita um numero:
append l x
end
print l | while x!=0:
x=input(float("digita um numero:"))
l.append(x)
print(l) | Python | zaydzuhri_stack_edu_python |
function extract_scheme password_hash
begin
set scheme = match string ^\{([^\}]{3,37})\} password_hash
if scheme
begin
return call groups at 0
end
return scheme
end function | def extract_scheme(password_hash):
scheme = re.match(r"^\{([^\}]{3,37})\}", password_hash)
if scheme:
return scheme.groups()[0]
return scheme | Python | nomic_cornstack_python_v1 |
comment a=("Hell0")
comment print(a)
comment a=('Hello')
comment print(a)
comment a="This is Amit’s Blog"
comment print(a)
comment str1 = "Welcome \tto my Blog"
comment str2 = "Welcome to\n my \tBlog"
comment print(str1)
comment print(str2)
comment str1 = "Welcome to my blog"
comment str2 = "Welcome to my \n Blog"
comm... | # a=("Hell0")
# print(a)
# a=('Hello')
# print(a)
# a="This is Amit’s Blog"
# print(a)
# str1 = "Welcome \tto my Blog"
# str2 = "Welcome to\n my \tBlog"
# print(str1)
# print(str2)
# str1 = "Welcome to my blog"
# str2 = "Welcome to my \n Blog"
# print(str1)
# print(str2)
# st... | Python | zaydzuhri_stack_edu_python |
function legacy_create_recstruct self
begin
from marcjsonconverter.bibrecord.bibrecord import create_record
return call create_record call legacy_export_as_marc at 0
end function | def legacy_create_recstruct(self):
from marcjsonconverter.bibrecord.bibrecord import create_record
return create_record(self.legacy_export_as_marc())[0] | Python | nomic_cornstack_python_v1 |
function test_07_view_runs_non_admin self
begin
set user = call create_user
set user_id = user at string data at string user_id
set run_data = dict string user_id user_id ; string date call isoformat ; string duration random integer 100 1000 ; string distance random integer 100 1000 ; string latitude 54.687157 ; string... | def test_07_view_runs_non_admin(self):
user = self.create_user()
user_id = user["data"]["user_id"]
run_data = {
"user_id": user_id,
"date": datetime.date.today().isoformat(),
"duration": random.randint(100, 1000),
"distance": random.randint(100, ... | Python | nomic_cornstack_python_v1 |
function weighted_loss y_true y_pred
begin
set y_true = call cast y_true float32
set log_likelihood = - pos_weight * y_true * log y_pred at tuple slice : : 1 + epsilon - neg_weight * 1 - y_true * log y_pred at tuple slice : : 0 + epsilon
set loss = mean K log_likelihood
return loss
end function | def weighted_loss(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
log_likelihood = -pos_weight * y_true * K.log(y_pred[:, 1] + epsilon) \
- neg_weight * (1 - y_true) * K.log(y_pred[:, 0] + epsilon)
loss = K.mean(log_likelihood)
return loss | Python | nomic_cornstack_python_v1 |
import pygame
string This is the Music Class. It only has one attribute, which is volume. All the methods call different sound effects.
class Music extends object
begin
function __init__ self
begin
set volume = 0.1
end function
string pygame.mixer.music.load loads in the music file
string pygame.mixer.music.set_volume ... | import pygame
"""This is the Music Class. It only has one attribute, which is volume. All the methods call different sound effects."""
class Music(object):
def __init__(self):
self.volume = 0.1
"""pygame.mixer.music.load loads in the music file"""
"""pygame.mixer.music.set_volume tak... | Python | zaydzuhri_stack_edu_python |
function word_polarity word pos_tag=none prior_polarity_score=false linear_score=none
begin
if prior_polarity_score
begin
return call __word_prior_polarity word pos_tag linear_score
end
set pos_tag = if expression pos_tag in PENN_NOUNS_TAGS then string NOUN else pos_tag
set pos_tag = if expression pos_tag in PENN_VERBS... | def word_polarity(word, pos_tag=None, prior_polarity_score=False, linear_score=None):
if prior_polarity_score:
return __word_prior_polarity(word, pos_tag, linear_score)
pos_tag = "NOUN" if pos_tag in util.PENN_NOUNS_TAGS else pos_tag
pos_tag = "VERB" if pos_tag in util.PENN_VERBS_TAGS else pos_tag
pos_tag = "AD... | Python | nomic_cornstack_python_v1 |
function extract_events trajectories traj_idx=0 cumulative_events_description=list
begin
function find_last_event events event_type player_num last_timestep=none
begin
for event in reversed events
begin
if get event string player == player_num and get event string action == event_type and last_timestep is none or event... | def extract_events(trajectories, traj_idx=0, cumulative_events_description=[]):
def find_last_event(events, event_type, player_num, last_timestep=None):
for event in reversed(events):
if event.get("player") == player_num and event.get("action") == event_type \
and (last_time... | Python | nomic_cornstack_python_v1 |
function test01b self
begin
set a = zeros tuple N 10 dtype=string bool
set a at slice 30 : 40 : = ones 10 dtype=string bool
set b = reshape array range N * 10 dtype=string f4 tuple N 10
assert raises NotImplementedError where a
end function | def test01b(self):
a = blz.zeros((self.N, 10), dtype="bool")
a[30:40] = blz.ones(10, dtype="bool")
b = blz.arange(self.N*10, dtype="f4").reshape((self.N, 10))
self.assertRaises(NotImplementedError, b.where, a) | Python | nomic_cornstack_python_v1 |
from chess.piece import piece
from chess.operate import operate_dict , operate_reverse
set user1_piece = list
set user2_piece = list
set action_array = list string up string down string left string right string center string up_left string down_left string up_right string down_right
comment 棋盘类
class board extends ob... | from chess.piece import piece
from chess.operate import operate_dict, operate_reverse
user1_piece = []
user2_piece = []
action_array = ["up", "down", "left", "right", "center", "up_left", "down_left", "up_right", "down_right"]
# 棋盘类
class board(object):
# 初始化棋盘
def __init__(self, size=3):
self.size =... | Python | zaydzuhri_stack_edu_python |
from jnpr.junos.device import Device
from jnpr.junos.factory.factory_loader import FactoryLoader
import yaml
import jxmlease
import argparse
from jnpr.junos.exception import *
from pprint import pprint
comment This on-box op script returns concatenated info on BGP peer state for multiple VRFs
comment minimum supported ... | from jnpr.junos.device import Device
from jnpr.junos.factory.factory_loader import FactoryLoader
import yaml
import jxmlease
import argparse
from jnpr.junos.exception import *
from pprint import pprint
# This on-box op script returns concatenated info on BGP peer state for multiple VRFs
# minimum supported JunOS vers... | Python | zaydzuhri_stack_edu_python |
function __init__ self initial_scale
begin
assert initial_scale > 0.0
set _scale = call FloatTensor list initial_scale
end function | def __init__(self, initial_scale):
assert initial_scale > 0.0
self._scale = torch.cuda.FloatTensor([initial_scale]) | Python | nomic_cornstack_python_v1 |
import numpy as np
function linear x xq y
begin
string Interpolates each column of a column-matrix :math:`x_q` on a matrix :math:`y`. Parameters ---------- x : :class:`np.ndarray` Points where :math:`y` is known. Must be a vector of size (n_x,). xq : :class:`np.ndarray` Values to interpolate. Must be a vector of size (... | import numpy as np
def linear(x, xq, y):
"""Interpolates each column of a column-matrix :math:`x_q` on a matrix
:math:`y`.
Parameters
----------
x : :class:`np.ndarray`
Points where :math:`y` is known. Must be a vector of size (n_x,).
xq : :class:`np.ndarray`
Values to interp... | Python | zaydzuhri_stack_edu_python |
import os.path
import logging
from enum import Enum
from date_bounds import BugzillaDateBoundFinder
from max_bounds import BugzillaMaxBoundFinder
from projects_bounds import BugzillaProjectBoundFinder
set logger = call getLogger __name__
function file_exists path
begin
return is file path path and st_size != 0
end func... | import os.path
import logging
from enum import Enum
from .date_bounds import BugzillaDateBoundFinder
from .max_bounds import BugzillaMaxBoundFinder
from .projects_bounds import BugzillaProjectBoundFinder
logger = logging.getLogger(__name__)
def file_exists(path):
return os.path.isfile(path) and os.stat(path).st_... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
plot list 1 2 4 1 list 1 2 4 1 label=string line1
plot list 3 1 2 3 list 3 1 2 3 label=string line2
legend
show | import matplotlib.pyplot as plt
plt.plot([1,2,4,1],[1,2,4,1], label='line1')
plt.plot([3,1,2,3],[3,1,2,3], label='line2')
plt.legend()
plt.show()
| Python | zaydzuhri_stack_edu_python |
import argparse , ConfigParser , requests , json
set p = config parser
read p string SF.ini
set apikey = get p string SF string APIkey
set p = call ArgumentParser
call add_argument string acct action=string store type=str
set args = call parse_args
function do_post URI data
begin
set resp = post URI headers=dict string... | import argparse, ConfigParser, requests, json
p = ConfigParser.ConfigParser()
p.read("SF.ini")
apikey = p.get("SF", "APIkey")
p = argparse.ArgumentParser()
p.add_argument('acct', action='store', type=str)
args = p.parse_args()
def do_post(URI, data):
resp = requests.post(URI, headers={"X-Starfighter-Authorizatio... | Python | zaydzuhri_stack_edu_python |
comment imports
import sqlite3
comment --------------------------------------------------
comment all the functions that insert data in the database
comment -------------------------------------------------
comment executes the databse statements
function execute test
begin
set conn = call connect string basketball.db
... | #imports
import sqlite3
#--------------------------------------------------
#all the functions that insert data in the database
#-------------------------------------------------
#executes the databse statements
def execute(test):
conn = sqlite3.connect('basketball.db')
c = conn.cursor()
c.ex... | Python | zaydzuhri_stack_edu_python |
function lengthOfLongestSubstring s
begin
string Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pw... | def lengthOfLongestSubstring(s):
"""Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1... | Python | zaydzuhri_stack_edu_python |
comment Start our youngest_age variable at something larger than anyone we'll find
set youngest_age = 9999
comment This will keep track of the person with the youngest age
set youngest_name = string
comment Go through each person in the list
for person_line in people
begin
comment by default this will split on the spa... | # Start our youngest_age variable at something larger than anyone we'll find
youngest_age = 9999
# This will keep track of the person with the youngest age
youngest_name = ""
# Go through each person in the list
for person_line in people:
parts = person_line.split() # by default this will split on the space
... | Python | zaydzuhri_stack_edu_python |
for name in names
begin
print name
end
set fav_food = list string pizza string pasta string steak string crisps string veg string noodles
print upper fav_food at 3
print lower fav_food at 3
print string My favorite food is: { title fav_food at 0 } | for name in names:
print(name)
fav_food = ['pizza', 'pasta', 'steak', 'crisps', 'veg', 'noodles']
print(fav_food[3].upper())
print(fav_food[3].lower())
print(f"My favorite food is: {fav_food[0].title()}") | Python | zaydzuhri_stack_edu_python |
function get_template self template_id
begin
try
begin
set data = call loadtxt extract file data template_id + string .dat
end
except KeyError
begin
raise call ValueError format string invalid star id: {0} template_id
end
return tuple data at tuple slice : : 0 data at tuple slice : : 1
end function | def get_template(self, template_id):
try:
data = np.loadtxt(self.data.extractfile(template_id + '.dat'))
except KeyError:
raise ValueError("invalid star id: {0}".format(template_id))
return data[:, 0], data[:, 1] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import random
from ast import literal_eval as make_tuple
import math
comment Edge definition:
comment - p1, p2: endpoints of the segment
comment - slope: slope of the segment
comment - intersect: intersect of the line (extention of the segment most probably) on... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from ast import literal_eval as make_tuple
import math
# Edge definition:
# - p1, p2: endpoints of the segment
# - slope: slope of the segment
# - intersect: intersect of the line (extention of the segment most probably) on the y axis
class Edge:
def __i... | Python | zaydzuhri_stack_edu_python |
function scsi_controller_count self
begin
return get pulumi self string scsi_controller_count
end function | def scsi_controller_count(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "scsi_controller_count") | Python | nomic_cornstack_python_v1 |
import re
function first_three_char some_str
begin
set lst = split some_str
for i in lst
begin
if length i == 1
begin
print i + string end=string
end
else
if length i == 2
begin
print i + string end=string
end
else
begin
print i at slice : 3 : end=string
end
end
end function
call first_three_char string fjsdfhj fhs... | import re
def first_three_char(some_str):
lst = some_str.split()
for i in lst:
if len(i) == 1:
print(i + ' ', end=' ')
elif len(i) == 2:
print(i + ' ', end=' ')
else:
print(i[:3], end=' ')
first_three_char('fjsdfhj fhsfhh trjtb nvd vf f jfi klm g,... | Python | zaydzuhri_stack_edu_python |
function obtain_user_permission client_creds
begin
comment We're using Google's synchronous OAuth library here instead of aiogoogle since:
comment 1. Configuration doesn't need or benefit from parallelism
comment 2. This handles the whole flow in just a couple of lines of code
comment The creds dicts are mostly compati... | def obtain_user_permission(client_creds) -> dict:
# We're using Google's synchronous OAuth library here instead of aiogoogle since:
#
# 1. Configuration doesn't need or benefit from parallelism
# 2. This handles the whole flow in just a couple of lines of code
#
# The creds dicts are mostly comp... | Python | nomic_cornstack_python_v1 |
function get_file_path
begin
return directory name path absolute path path real path path __file__
end function | def get_file_path():
return os.path.dirname(os.path.abspath(os.path.realpath(__file__))) | Python | nomic_cornstack_python_v1 |
function generate_udp_flows self traffic_profile build_version
begin
set Shost = call gethostbyaddr vm_node_ip
set Dhost = call gethostbyaddr vm_node_ip
info string Src_VM = %s, Src_IP_Range = %s to %s, Dest_VM = %s, Dest_IP = %s, Src_VN = %s, Dest_VN = %s, Port_Range = %s to %s, Src_Node = %s, Dst_Node = %s. % tuple v... | def generate_udp_flows(self, traffic_profile, build_version):
Shost = socket.gethostbyaddr(traffic_profile[0].vm_node_ip)
Dhost = socket.gethostbyaddr(traffic_profile[7].vm_node_ip)
self.logger.info(
"Src_VM = %s, Src_IP_Range = %s to %s, Dest_VM = %s, Dest_IP = %s, Src_VN = %s, Dest... | Python | nomic_cornstack_python_v1 |
function bridge_commands self
begin
if not cmds := get attribute self string _bridge_commands none
begin
set _bridge_commands = list
set cmds = list
end
return cmds
end function | def bridge_commands(self) -> list[BridgeCommand | BridgeCommandGroup]:
if not (cmds := getattr(self, "_bridge_commands", None)):
self._bridge_commands = cmds = []
return cmds | Python | nomic_cornstack_python_v1 |
import binascii
function conduct instruction_mapping
begin
set cmds = dict string ADD string 00101000 ; string SUB string 00100101 ; string OR string 00111000 ; string STR string 01011000 ; string LDR string 01011001 ; string MOVW string 00110000 ; string MOVT string 00110100 ; string B string 1010 ; string BL string 1... | import binascii
def conduct(instruction_mapping):
cmds = {'ADD': '00101000', 'SUB': '00100101', 'OR': '00111000',
'STR': '01011000', 'LDR': '01011001',
'MOVW': '00110000', 'MOVT': '00110100',
'B': '1010', 'BL': '1011', 'BX':'000100101111111111110001'}
cond = {'AL': '1110', 'NE': '0... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
from torch.utils.data.sampler import Sampler , BatchSampler , SubsetRandomSampler
import torch
from itertools import accumulate , chain , repeat , tee
set __all__ = list string FixBatchSampler
class FixBatchSampler extends Sampler
begin
function __init__ self dataset num_workers batch_size shuffle ... | # coding=utf-8
from torch.utils.data.sampler import Sampler, BatchSampler, SubsetRandomSampler
import torch
from itertools import accumulate, chain, repeat, tee
__all__ = ['FixBatchSampler']
class FixBatchSampler(Sampler):
def __init__(self, dataset, num_workers, batch_size, shuffle, drop_last=False):
s... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment recipeFrame.py
comment Copyright 2015 Franz Habison <habison.franz@gmx.at>
comment This program is free software; you can redistribute it and/or modify
comment it under the terms of the GNU General Public License as published by
comment the Free Softwar... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# recipeFrame.py
#
# Copyright 2015 Franz Habison <habison.franz@gmx.at>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.