code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import json
from copy import deepcopy
from flask import Response
function response_object_formatting func
begin
function wrapper *args **kwargs
begin
set tuple res result errors links status = call func *args keyword kwargs
if result or errors or links
begin
set res_copy = deep copy res
set res_copy at string result = ... | import json
from copy import deepcopy
from flask import Response
def response_object_formatting(func):
def wrapper(*args, **kwargs):
res, result, errors, links, status = func(*args, **kwargs)
if result or errors or links:
res_copy = deepcopy(res)
res_copy["result"] = resul... | Python | zaydzuhri_stack_edu_python |
function status
begin
set statuses = call get_all_statuses
return dumps statuses indent=4
end function | def status():
statuses = get_all_statuses()
return json.dumps(statuses, indent=4) | Python | nomic_cornstack_python_v1 |
string Dado un numero, encontrar cuantas veces aparece un digito en ese numero
string 467544 4 -> 3 veces aparece (num,digito)
function conteo_num num digito
begin
if is instance num int and tuple digito int and num > 0 and digito >= 0
begin
return call cantidad_num num digito
end
else
begin
return 0
end
end function
f... | """ Dado un numero, encontrar
cuantas veces aparece un digito en ese numero"""
"""467544
4 -> 3 veces
aparece (num,digito)
"""
def conteo_num (num, digito):
if isinstance (num, int) and (digito, int) and (num > 0) and (digito >= 0):
return cantidad_num(num,digito)
else:
... | Python | zaydzuhri_stack_edu_python |
function isNewAttribute self attr
begin
pass
end function | def isNewAttribute(self, attr):
pass | Python | nomic_cornstack_python_v1 |
import torch
import cv2
import numpy as np
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from PIL import Image
comment todo: add random crops
class BgrToRgbClip
begin
function __call__ self clip
begin
comment assert clip[0] == np.ndarray
return list comprehension call cvtColo... | import torch
import cv2
import numpy as np
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from PIL import Image
#todo: add random crops
class BgrToRgbClip:
def __call__(self, clip):
# assert clip[0] == np.ndarray
return [cv2.cvtColor(frame, cv2.COLOR_BGR2... | Python | zaydzuhri_stack_edu_python |
function GetNext self sess=none
begin
if sess is none
begin
set sess = call get_default_session
end
set tuple image label = run _next
return tuple image label
end function | def GetNext(self, sess: tf.Session = None):
if sess is None:
sess = tf.get_default_session()
image, label = sess.run(self._next)
return image, label | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python
import socket
import sys
comment create a TCP/IP socket
set sock = call socket AF_INET SOCK_STREAM
comment bind the sockect to the port
set server_address = tuple string 172.31.15.170 10000
tuple print ? stderr string starting up on %s port %s % server_address
call bind server_address
comment ... | #! /usr/bin/python
import socket
import sys
#create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the sockect to the port
server_address = ('172.31.15.170', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
#listen for incoming connect... | Python | zaydzuhri_stack_edu_python |
function attention self x_i x index
begin
set e_i = list
set c_i = list
for output in x
begin
set output = reshape tf output list - 1 embedding_size
set atten_hidden = tanh add tf matrix multiply x_i attention_W matrix multiply output attention_U
set e_i_j = matrix multiply atten_hidden attention_V
append e_i e_i_j
e... | def attention(self, x_i, x, index):
e_i = []
c_i = []
for output in x:
output = tf.reshape(output, [-1, self.embedding_size])
atten_hidden = tf.tanh(tf.add(tf.matmul(x_i, self.attention_W), tf.matmul(output, self.attention_U)))
e_i_j = tf.matmul(atten_hidden,... | Python | nomic_cornstack_python_v1 |
function contains_position_within_bounding_box self pos
begin
if pos at 0 < position at 0 + nzis_min at 0
begin
return false
end
if pos at 0 > position at 0 + nzis_max at 0
begin
return false
end
if pos at 1 < position at 1 + nzis_min at 1
begin
return false
end
if pos at 1 > position at 1 + nzis_max at 1
begin
return ... | def contains_position_within_bounding_box(self, pos):
if pos[0] < self.position[0] + self.nzis_min[0]:
return False
if pos[0] > self.position[0] + self.nzis_max[0]:
return False
if pos[1] < self.position[1] + self.nzis_min[1]:
return False
if pos[1] > ... | Python | nomic_cornstack_python_v1 |
function index request
begin
if is_authenticated
begin
set date_projects = list
set dates = list
set days = list
try
begin
set last_login = Timestamp
set changed_projects = call order_by string -TimeStamp
comment buckets of days.
for x in call values_list string TimeStamp flat=true
begin
comment make days unique.
if... | def index(request):
if request.user.is_authenticated:
date_projects = []
dates = []
days = []
try:
last_login = request.user.logins.all().order_by('-Timestamp')[1].Timestamp
changed_projects = get_visible_projects(request.user).filter(TimeStamp__gte=las... | Python | nomic_cornstack_python_v1 |
function getUserToEmailMap self
begin
set ldapToEmailMap = dict
try
begin
set ldapToEmailMap = _yamlDict at string user_to_email_map
if ldapToEmailMap is none
begin
set ldapToEmailMap = dict
end
end
except KeyError
begin
warning string config missing user_to_email_map
end
return ldapToEmailMap
end function | def getUserToEmailMap(self):
ldapToEmailMap = {}
try:
ldapToEmailMap = self._yamlDict['user_to_email_map']
if ldapToEmailMap is None:
ldapToEmailMap = {}
except KeyError:
logger.warning("config missing user_to_email_map")
return ldapToE... | Python | nomic_cornstack_python_v1 |
function operator self x
begin
pass
end function | def operator(self, x):
pass | Python | nomic_cornstack_python_v1 |
string 当i为奇数时,nums[i] >= nums[i - 1] 当i为偶数时,nums[i] <= nums[i - 1] 那么只要对每个数字,根据其奇偶性,选择是否与上一个数交换即可
class Solution
begin
string @param: nums: A list of integers @return: nothing
function wiggleSort self nums
begin
set l = length nums
for i in call xrange 1 l
begin
if i % 2 == 1 and nums at i < nums at i - 1 or i % 2 == 0... | '''
当i为奇数时,nums[i] >= nums[i - 1]
当i为偶数时,nums[i] <= nums[i - 1]
那么只要对每个数字,根据其奇偶性,选择是否与上一个数交换即可
'''
class Solution:
"""
@param: nums: A list of integers
@return: nothing
"""
def wiggleSort(self, nums):
l = len(nums)
for i in xrange(1, l):
if i % 2 == 1 and nums[i] < nums[... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
class income_distribution
begin
comment flag value to check whether input is valid or not
set valid_input = 1
comment to assign the data to the class variables
function set_Data self country_by_region_data gdp_by_year
begin
set country_by_region_data = country_by_region_data
set gdp_by_y... | import matplotlib.pyplot as plt
class income_distribution:
valid_input = 1 # flag value to check whether input is valid or not
def set_Data(self, country_by_region_data, gdp_by_year): #to assign the data to the class variables
self.country_by_region_data = country_by_region_data
self.gdp... | Python | zaydzuhri_stack_edu_python |
import winsound
class animal
begin
function __init__ self legs=4 eyes=2 tail=1
begin
set legs = legs
set eyes = eyes
end function
end class
class wild extends animal
begin
function habitat self
begin
print string In Jungle
end function
end class
class domestic extends animal
begin
function habitat self
begin
print stri... | import winsound
class animal:
def __init__(self , legs=4, eyes=2, tail=1):
self.legs=legs
self.eyes=eyes
class wild(animal):
def habitat(self):
print("In Jungle")
class domestic(animal):
def habitat(self):
print("Among Human"... | Python | zaydzuhri_stack_edu_python |
comment Necesarry imports
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.stem.porter import *
import os
import string
import email
import nltk
call download string stopwords quiet=true
call download string punkt quiet=true
call download string... | # Necesarry imports
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.stem.porter import *
import os
import string
import email
import nltk
nltk.download('stopwords', quiet=True)
nltk.download('punkt', quiet=True)
nltk.download('wordnet', quiet=T... | Python | zaydzuhri_stack_edu_python |
function __init__ self *waveforms
begin
if length waveforms < 2
begin
raise call ValueError string Needs at least two waveforms to form a CompositeWaveform.
end
for wf in waveforms
begin
call _validate wf
end
set _waveforms = list waveforms
end function | def __init__(self, *waveforms):
if len(waveforms) < 2:
raise ValueError("Needs at least two waveforms to form a "
"CompositeWaveform.")
for wf in waveforms:
self._validate(wf)
self._waveforms = list(waveforms) | Python | nomic_cornstack_python_v1 |
function store self course_id filename buff
begin
set key = call key_for course_id filename
set data = call getvalue
set size = length data
set content_encoding = string gzip
set content_type = string text/csv
comment Just setting the content encoding and type above should work
comment according to the docs, but when e... | def store(self, course_id, filename, buff):
key = self.key_for(course_id, filename)
data = buff.getvalue()
key.size = len(data)
key.content_encoding = "gzip"
key.content_type = "text/csv"
# Just setting the content encoding and type above should work
# ... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , Conv2D , Flatten , Dropout , MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
import numpy as np
import matplotlib.pyplot as plt
comment Downloading the data
set _... | import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
import numpy as np
import matplotlib.pyplot as plt
#Downloading the data
_URL = 'https:... | Python | zaydzuhri_stack_edu_python |
import unittest
from models.people import *
from main import *
from models.room import *
class TestOfMainSpacesAllocation extends TestCase
begin
string This are for testing the main.py class function and method
function setUp self
begin
string This is to setup for the rest of the testing the input
set andela = call Bui... | import unittest
from models.people import *
from main import *
from models.room import *
class TestOfMainSpacesAllocation(unittest.TestCase):
"""
This are for testing the main.py class function and method
"""
def setUp(self):
"""
This is to setup for the rest of the testing the input
"""
self.andela = Buil... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment List of Porn star names at: http://www.ranker.com/list/top-20-pornstars-_female_/ratamatata?page=2
import scrapy
class PornStarSpider extends Spider
begin
set name = string pornstars
set allowed_domains = list string http://www.ranker.com
set start_urls = list string http://www.ranker.c... | #!/usr/bin/python
#List of Porn star names at: http://www.ranker.com/list/top-20-pornstars-_female_/ratamatata?page=2
import scrapy
class PornStarSpider(scrapy.Spider):
name = 'pornstars'
allowed_domains = ['http://www.ranker.com']
start_urls = ['http://www.ranker.com/list/top-20-pornstars-_female_/rata... | Python | zaydzuhri_stack_edu_python |
function regularization_losses self
begin
pass
end function | def regularization_losses(self):
pass | Python | nomic_cornstack_python_v1 |
function configure_nginx
begin
call sudo string /etc/init.d/nginx start
if exists string /etc/nginx/sites-enabled/default
begin
call sudo string rm /etc/nginx/sites-enabled/default
end
if exists string /etc/nginx/sites-enabled/kmis_project is false
begin
call sudo string touch /etc/nginx/sites-available/kmis_project
ca... | def configure_nginx():
sudo('/etc/init.d/nginx start')
if exists('/etc/nginx/sites-enabled/default'):
sudo('rm /etc/nginx/sites-enabled/default')
if exists('/etc/nginx/sites-enabled/kmis_project') is False:
sudo('touch /etc/nginx/sites-available/kmis_project')
sudo('ln -s /etc/nginx/... | Python | nomic_cornstack_python_v1 |
function db_uri_generator proj_root db_name
begin
return string sqlite:/// + join path proj_root string database db_name + string .sqlite3
end function | def db_uri_generator(*, proj_root: str, db_name: str) -> str:
return "sqlite:///" + os.path.join(proj_root, "database", db_name + ".sqlite3") | Python | nomic_cornstack_python_v1 |
comment import the necessary packages
import numpy as np
import pandas as pd
import tensorflow as tf
comment read in the training dataset
set df = read csv string data.csv
comment initializing the training data
set X = df at string Open
set y = df at string Close
comment creating and tuning the model
set model = sequen... | #import the necessary packages
import numpy as np
import pandas as pd
import tensorflow as tf
#read in the training dataset
df = pd.read_csv('data.csv')
#initializing the training data
X = df['Open']
y = df['Close']
#creating and tuning the model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(64, acti... | Python | iamtarun_python_18k_alpaca |
function test__add_service self mock_policy mock_down_action mock_dirwatch
begin
comment Disable W0212(protected-access)
comment pylint: disable=W0212
set mon = call Monitor services_dir=none service_dirs=tuple policy_impl=mock_policy down_action=call mock_down_action
set mock_pol_inst = return_value
set mock_reg_hand... | def test__add_service(self, mock_policy, mock_down_action, mock_dirwatch):
# Disable W0212(protected-access)
# pylint: disable=W0212
mon = monitor.Monitor(
services_dir=None,
service_dirs=(),
policy_impl=mock_policy,
down_action=mock_down_action()
... | Python | nomic_cornstack_python_v1 |
function process self
begin
process
set _determine_places_counter = _determine_places_counter + 1
comment If Event is timed, then call respective method
if is_timed == true
begin
sort _results key=_sort_results_timed
end
else
begin
comment If Event is scored, then call respective method
sort _results key=_sort_results_... | def process(self) :
super().process()
DeterminePlaces._determine_places_counter += 1
if Event.is_timed == True: # If Event is timed, then call respective method
self._results.sort(key = self._sort_results_timed)
else: # If Event is scor... | Python | nomic_cornstack_python_v1 |
function countMatches g1 g2
begin
comment sanity check
if g1 is none or g2 is none or length g1 == 0 or length g1 at 0 == 0
begin
return 0
end
set count = 0
for i in range length g1
begin
for j in range length g1 at 0
begin
if g1 at i at j == g2 at i at j == 1 and call search_grid g1 g2 i j
begin
set count = count + 1
... | def countMatches(g1, g2):
if g1 is None or g2 is None or len(g1) == 0 or len(g1[0]) == 0: # sanity check
return 0
count = 0
for i in range(len(g1)):
for j in range(len(g1[0])):
if g1[i][j] == g2[i][j] == 1 and search_grid(g1, g2, i, j):
count = count + 1
retu... | Python | nomic_cornstack_python_v1 |
import Blue_stacks_role_class as role_class
comment Class which maintains the users and related functions
class Users extends Roles
begin
function __init__ self name passw
begin
set username = name
set password = passw
end function
function add_admin_user self
begin
set users at username = self
set users_roles at usern... | import Blue_stacks_role_class as role_class
# Class which maintains the users and related functions
class Users(role_class.Roles):
def __init__(self, name, passw):
self.username = name
self.password = passw
def add_admin_user(self):
self.users[self.username] = self
self.users_r... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment coding=utf-8
comment created by raylei, 2018/8/26
comment 定义:适配器模式将一个类的接口转换成客户期望的另一个接口。
comment 好处:让客户从实现的接口解耦,不必为了应对不同的接口而跟着改变。
class Target extends object
begin
function request self
begin
print string normal request.
end function
end class
class Adaptee extends object
begin
function ... | #!/usr/bin/python
# coding=utf-8
#
# created by raylei, 2018/8/26
#
# 定义:适配器模式将一个类的接口转换成客户期望的另一个接口。
# 好处:让客户从实现的接口解耦,不必为了应对不同的接口而跟着改变。
class Target(object):
def request(self):
print('normal request.')
class Adaptee(object):
def specific_request(self):
print('specific request.')
class Adapt... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Oct 20 14:00:08 2019 @author: adhan
import numpy as np
import math
set imgTest = array list list 8 10 0 list 8 4 2 list 8 8 6
set lbpLoop = array range 1 999
set lbpBinarySeq = list 0 0 0 0 0 0 0 0
set lbpVal = 0
set i = 1
set j = 1
comment Atas-Kiri
if imgTest at tup... | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 14:00:08 2019
@author: adhan
"""
import numpy as np
import math
imgTest = np.array( [[8, 10, 0],
[8, 4, 2],
[8, 8, 6]
])
lbpLoop = np.arange(1,999)
lbpBinarySeq = [0,0,0,0,0,0,0,0]
l... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
function run s
begin
set idx = 0
set arr = map int split s
set res = 0
while true
begin
try
begin
set val = arr at idx
end
except IndexError
begin
return res
end
try else
begin
if val >= 3
begin
set arr at idx = val - 1
end
else
begin
set arr at idx = val + 1
end
set idx = idx + val
set res... | #!/usr/bin/env python
def run(s):
idx = 0
arr = map(int, s.split())
res = 0
while True:
try:
val = arr[idx]
except IndexError:
return res
else:
if val >= 3:
arr[idx] = val - 1
else:
arr[idx] = val +... | Python | zaydzuhri_stack_edu_python |
import requests
set resp = get requests string http://api.football-data.org/v1/competitions/426/teams headers=dict string X-Response-Control string minified
if status_code != 200
begin
comment This means something went wrong.
raise call ApiError format string GET /teams/ {} status_code
end
print string test
from operat... | import requests
resp = requests.get('http://api.football-data.org/v1/competitions/426/teams', headers={"X-Response-Control":"minified"})
if resp.status_code != 200:
# This means something went wrong.
raise ApiError('GET /teams/ {}'.format(resp.status_code))
print ('test')
from operator import itemgetter
# f... | Python | zaydzuhri_stack_edu_python |
function smoothing self alphas betas
begin
set probas = list
for tuple count alpha beta in zip range length alphas alphas betas
begin
set multi = alpha * beta
set normalize_factor = 1 / sum multi axis=0
append probas normalize_factor * multi
end
info format string Probabilities, backward forward {} probas
return proba... | def smoothing(self, alphas, betas):
probas = []
for count, alpha, beta in (zip(range(len(alphas)), alphas, betas)):
multi = alpha * beta
normalize_factor = 1 / np.sum(multi, axis=0)
probas.append((normalize_factor * multi))
self.logger.info('Probabilities, bac... | Python | nomic_cornstack_python_v1 |
function noticks ax=none
begin
set ax = if expression ax is not none then ax else call gca
call set_xticks list
call set_yticks list
end function | def noticks(ax=None):
ax=ax if ax is not None else pl.gca()
ax.set_xticks([])
ax.set_yticks([]) | Python | nomic_cornstack_python_v1 |
comment 23.02
from random import choice
from string import ascii_letters
from random import randint
from itertools import permutations
from datetime import datetime
comment task 1
set number = random integer 1 11
print string Try to guess the number:
set i = 0
while 1
begin
if i == 3
begin
print string You lost!The num... | #23.02
from random import choice
from string import ascii_letters
from random import randint
from itertools import permutations
from datetime import datetime
#task 1
number = randint(1, 11)
print ('Try to guess the number:')
i=0
while 1:
if i==3:
print ('You lost!The number was%... | Python | zaydzuhri_stack_edu_python |
for _ in range amount
begin
set name = input string 請輸入名字:
set score = integer input string 請輸入分數:
append n name
append s score
end
print s
for m in range amount
begin
set total = total + s at m
end
set avg = total / amount
print string 平均是 avg
set highest = 0
set lowest = 99999999
for k in s
begin
if k > highest
begin... | for _ in range(amount):
name=input("請輸入名字: ")
score=int(input("請輸入分數: "))
n.append(name)
s.append(score)
print (s)
for m in range(amount):
total=total+s[m]
avg=total/amount
print("平均是",avg)
highest=0
lowest=99999999
for k in s:
if k>highest:
highest=k
print("最高分為",high... | Python | zaydzuhri_stack_edu_python |
async function _async_reset_meter self event
begin
set now = now
if _period == WEEKLY and call weekday != _period_offset
begin
return
end
if _period == MONTHLY and day != 1 + _period_offset
begin
return
end
if _period == YEARLY and month != 1 + _period_offset or day != 1
begin
return
end
await call async_reset_meter en... | async def _async_reset_meter(self, event):
now = dt_util.now()
if self._period == WEEKLY and now.weekday() != self._period_offset:
return
if self._period == MONTHLY and\
now.day != (1 + self._period_offset):
return
if self._period == YEARLY and\
... | Python | nomic_cornstack_python_v1 |
function histvals_o a cumulative=false **kwargs
begin
set tuple counts bins = call histogram a keyword kwargs
if cumulative == true
begin
set counts = cumulative sum np counts
end
set x = concatenate list zip bins at slice : - 1 : bins at slice 1 : :
set y = concatenate list zip counts counts
set x = concatenate tup... | def histvals_o(a, cumulative=False, **kwargs):
counts, bins = np.histogram(a, **kwargs)
if cumulative==True:
counts = np.cumsum(counts)
x = np.concatenate( list(zip( bins[:-1], bins[1:] )) )
y = np.concatenate( list(zip( counts, counts )) )
x = np.concatenate(( [x[0]], x, [x[-1]] ))
y = np.concat... | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_okarray_okarray_infnum_none_b_7 self
begin
comment The expected results.
set expected = list comprehension x * y + z for tuple x y z in zip okarrayx okarrayy repeat infnumz
comment Exceptions are turned off so we can use the results to test for correct values.
call fma okarrayx okarrayy infn... | def test_fma_nan_param_okarray_okarray_infnum_none_b_7(self):
# The expected results.
expected = [(x * y + z) for x,y,z in zip(self.okarrayx, self.okarrayy, itertools.repeat(self.infnumz))]
# Exceptions are turned off so we can use the results to test for correct values.
arrayfunc.fma(self.okarrayx, self.okarr... | Python | nomic_cornstack_python_v1 |
function pomodoro_time start_time duration
begin
comment time.sleep takes duration in seconds
set duration_sec = duration * 60
comment Used to show whether a pomodoro was interrupted
set complete = false
while not complete
begin
try
begin
comment Wait for length of pomodoro
sleep duration_sec
print string Pomodoro Comp... | def pomodoro_time(start_time, duration):
duration_sec = duration * 60 # time.sleep takes duration in seconds
complete = False # Used to show whether a pomodoro was interrupted
while not complete:
try:
sleep(duration_sec) # Wait for length of pomodoro
print("Pomodoro Comp... | Python | nomic_cornstack_python_v1 |
function check_ambari_server_process_up self
begin
set process_name = string ambari-server
set output = call __find_process process_name
return search process_name output
end function | def check_ambari_server_process_up(self):
process_name = "ambari-server"
output = self.__find_process(process_name)
return re.search(process_name, output) | Python | nomic_cornstack_python_v1 |
function printProgressBar iteration total prefix=string suffix=string decimals=1 length=100 fill=string █ printEnd=string
begin
set percent = format string {0:. + string decimals + string f} 100 * iteration / decimal total
set filledLength = integer length * iteration // total
set bar = fill * filledLength + string -... | def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLen... | Python | nomic_cornstack_python_v1 |
function below_sea_level z sea_level
begin
return z <= sea_level
end function | def below_sea_level(z, sea_level):
return z <= sea_level | Python | nomic_cornstack_python_v1 |
from DBUtil import *
from nltk.stem.wordnet import WordNetLemmatizer
from itertools import combinations
import networkx as nx
function split_and_process_keywords con
begin
string 对已经导入到数据库中的文献进行关键词拆分和词形还原处理, 然后将关键词以分号分隔整合后存入数据库 :param con: 数据库连接对象 :return: None
set cursor = call cursor
execute cursor string SELECT `sid... | from DBUtil import *
from nltk.stem.wordnet import WordNetLemmatizer
from itertools import combinations
import networkx as nx
def split_and_process_keywords(con):
"""
对已经导入到数据库中的文献进行关键词拆分和词形还原处理,
然后将关键词以分号分隔整合后存入数据库
:param con: 数据库连接对象
:return: None
"""
cursor = con.cursor()
cursor.ex... | Python | zaydzuhri_stack_edu_python |
function get_service_location_info self service_location_id
begin
set url = url join URLS at string servicelocation string service_location_id string info
set headers = dict string Authorization format string Bearer {} access_token
set r = get requests url headers=headers
call raise_for_status
return json r
end functio... | def get_service_location_info(self, service_location_id):
url = urljoin(URLS['servicelocation'], str(service_location_id), "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json() | Python | nomic_cornstack_python_v1 |
function get_hash self delays temp_map delta_temp_map **kwargs
begin
set param = list delays only_heat
if size np temp_map > 1000000.0
begin
set temp_map = flatten temp_map at slice 0 : 1000000 :
set delta_temp_map = flatten delta_temp_map at slice 0 : 1000000 :
end
append param temp_map
append param delta_temp_map
f... | def get_hash(self, delays, temp_map, delta_temp_map, **kwargs):
param = [delays, self.only_heat]
if np.size(temp_map) > 1e6:
temp_map = temp_map.flatten()[0:1000000]
delta_temp_map = delta_temp_map.flatten()[0:1000000]
param.append(temp_map)
param.append(delta_te... | Python | nomic_cornstack_python_v1 |
function get_streams pps burst_num model src_num tot_pkts_burst l3_data test
begin
if src_num > 1
begin
raise call RuntimeError string Currently not implemented!
end
set pps = pps * 10 ^ 6
call pp pps
if pps < LATENCY_FLOW_PPS
begin
raise call RuntimeError string The minimal PPS { LATENCY_FLOW_PPS } is required for acc... | def get_streams(
pps: float, burst_num: int, model: str, src_num, tot_pkts_burst, l3_data, test: bool
) -> list:
if src_num > 1:
raise RuntimeError("Currently not implemented!")
pps = pps * 10 ** 6
pprint.pp(pps)
if pps < LATENCY_FLOW_PPS:
raise RuntimeError(
f"The minim... | Python | nomic_cornstack_python_v1 |
function setup_gui_global main_window dat_details config
begin
comment Reset the window size and splitter widths if they're available in user-config.yaml
set window_width : int = 0
set window_height : int = 0
try
begin
set window_width = integer call get_config_value user_gui_settings string gui width string 0 false
en... | def setup_gui_global(main_window: Any, dat_details: dict[str, dict[str, str]], config: Config) -> None:
# Reset the window size and splitter widths if they're available in user-config.yaml
window_width: int = 0
window_height: int = 0
try:
window_width = int(get_config_value(config.user_... | Python | nomic_cornstack_python_v1 |
set length = input
set num_list = list map int string input
print sum num_list | length = input()
num_list = list(map(int, str(input())))
print(sum(num_list)) | Python | zaydzuhri_stack_edu_python |
comment Import important stuff #
from SudokuBoard import SudokuBoard
from sudokuSolver import sudoku_solver
from time import time
comment Make and solve a board #
comment Make the board
set board = call SudokuBoard list comprehension integer v for v in string 530070000600195000098000060800060003400803001700020006060000... | ##########################
# Import important stuff #
##########################
from SudokuBoard import SudokuBoard
from sudokuSolver import sudoku_solver
from time import time
##########################
# Make and solve a board #
##########################
# Make the board
board = SudokuBoard([int(v) for v in "530... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment -*- coding:utf-8 -*-
import os
set files = list directory string . | #! /usr/bin/env python
# -*- coding:utf-8 -*-
import os
files = os.listdir("."); | Python | zaydzuhri_stack_edu_python |
import cv2 as cv
import numpy as np
function load_image file_path
begin
string 이미지 불러오기 함수 디렉터리 명에 한글이 포함되면 opencv는 해당 path를 인식하지 못함 임의로 python에서 bytearray로 불러와서 opencv에서 이미지를 인코딩하는 방식을 취함
with open file_path string rb as f
begin
set barr = bytearray read f
end
set barr = array barr dtype=uint8
set img = call imdecode ... | import cv2 as cv
import numpy as np
def load_image(file_path):
'''
이미지 불러오기 함수
디렉터리 명에 한글이 포함되면 opencv는 해당 path를 인식하지 못함
임의로 python에서 bytearray로 불러와서 opencv에서 이미지를 인코딩하는 방식을 취함
'''
with open(file_path, 'rb') as f:
barr = bytearray(f.read())
barr = np.array(barr, dtype=np.uint8)
... | Python | zaydzuhri_stack_edu_python |
function _get_group_levels self level=1
begin
set list_items = list comprehension col at slice 0 : level : for col in index
set results = list
for x in list_items
begin
if x not in results
begin
set results = results + list x
end
end
return results
end function | def _get_group_levels(self, level=1):
list_items = [col[0:level] for col in self._obj.index]
results = []
for x in list_items:
if x not in results:
results += [x]
return results | Python | nomic_cornstack_python_v1 |
function intersects self other
begin
return not _lbound > _rbound or _rbound < _lbound
end function | def intersects(self, other):
return not (self._lbound > other._rbound or
self._rbound < other._lbound) | Python | nomic_cornstack_python_v1 |
function SnapToScreen self snap=true monitor=0 hAlign=RIGHT vAlign=TOP
begin
if not snap
begin
set _is_docked = tuple false RIGHT TOP 0
return
end
set displayCount = call GetCount
if monitor > displayCount
begin
raise exception string Invalid monitor selected: you only have %d monitors % displayCount
end
set _is_docked... | def SnapToScreen(self, snap=True, monitor=0, hAlign=wx.RIGHT, vAlign=wx.TOP):
if not snap:
self._is_docked = (False, wx.RIGHT, wx.TOP, 0)
return
displayCount = wx.Display.GetCount()
if monitor > displayCount:
raise Exception("Invalid monitor ... | Python | nomic_cornstack_python_v1 |
function unsetName self
begin
return call Reaction_unsetName self
end function | def unsetName(self):
return _libsbml.Reaction_unsetName(self) | Python | nomic_cornstack_python_v1 |
from mail.context.smtp import mail_server
from mail.factory.invite import InviteMailFactory
class MailSender extends object
begin
string Почтальон
decorator staticmethod
function send_invite_mail email_to values
begin
string Отправить письмо с приглосом :param email_to: Адресат :param values: Значения для формирования ... | from mail.context.smtp import mail_server
from mail.factory.invite import InviteMailFactory
class MailSender(object):
"""
Почтальон
"""
@staticmethod
def send_invite_mail(email_to: str, values: dict) -> bool:
"""
Отправить письмо с приглосом
:param email_to: Адресат
... | Python | zaydzuhri_stack_edu_python |
import re
import requests
from bs4 import BeautifulSoup
import urllib.request
import shutil
function Satellite
begin
set url = string https://www.cwb.gov.tw/V7/js/s1p.js
set request = call Request url
set response = url open request
set html = read response
set soup = call BeautifulSoup html string lxml
comment print(s... | import re
import requests
from bs4 import BeautifulSoup
import urllib.request
import shutil
def Satellite():
url = "https://www.cwb.gov.tw/V7/js/s1p.js"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
html =response.read()
soup=BeautifulSoup(html,'lxml')
... | Python | zaydzuhri_stack_edu_python |
import unittest
from typing import cast
from dataladmetadatamodel.common import get_top_level_metadata_objects
from dataladmetadatamodel.datasettree import DatasetTree
from dataladmetadatamodel.metadata import Metadata
from dataladmetadatamodel.metadatapath import MetadataPath
class TestRemote extends TestCase
begin
fu... | import unittest
from typing import cast
from dataladmetadatamodel.common import get_top_level_metadata_objects
from dataladmetadatamodel.datasettree import DatasetTree
from dataladmetadatamodel.metadata import Metadata
from dataladmetadatamodel.metadatapath import MetadataPath
class TestRemote(unittest.TestCase):
... | Python | jtatman_500k |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string @author: wj @license: (C) Copyright 2013-2018. @contact: 1693841903@qq.com @file: iter对象.py @version: 1.0 @time: 2018/4/11 09:29 @desc: # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━━━┛┻┓ ┃ ☃ ┃ ... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: wj
@license: (C) Copyright 2013-2018.
@contact: 1693841903@qq.com
@file: iter对象.py
@version: 1.0
@time: 2018/4/11 09:29
@desc:
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
import os
import re
import imageio
import matplotlib.pyplot as plt
function compare_images model sample_observations image_dir
begin
string side by side comparison of image and reconstruction
set reconstructed = call forward sample_observations
set tuple fig axes = call subplots nrow... | from collections import defaultdict
import os
import re
import imageio
import matplotlib.pyplot as plt
def compare_images(model, sample_observations, image_dir):
""" side by side comparison of image and reconstruction """
reconstructed = model.forward(sample_observations)
fig, axes = plt.subplots(
... | Python | zaydzuhri_stack_edu_python |
string This file contains all the classes you must complete for this project. You can use the test cases in agent_test.py to help during development, and augment the test suite with your own test cases to further test your code. You must test your agent's strength against a set of agents with known relative strength us... | """This file contains all the classes you must complete for this project.
You can use the test cases in agent_test.py to help during development, and
augment the test suite with your own test cases to further test your code.
You must test your agent's strength against a set of agents with known
relative strength usin... | Python | zaydzuhri_stack_edu_python |
comment Global modules here
import collections
import itertools
import time
comment Internal modules here
from src.pmml_exporter import *
class Apriori
begin
string Apriori algorithm to find frequent itemset and extract the association rules
function __init__ self transactions uniques min_sup=2.0 min_conf=1.5
begin
set... | # Global modules here
import collections
import itertools
import time
# Internal modules here
from src.pmml_exporter import *
class Apriori:
"""
Apriori algorithm to find frequent itemset and extract the association rules
"""
def __init__(self, transactions, uniques, min_sup=2.0, min_conf=1.5):
... | Python | zaydzuhri_stack_edu_python |
function getYearAvgs self oBY month_list monthIndex
begin
set lats = call getLats
set longs = call getLongs
for lat in range 0 shape at 0
begin
for long in range 0 shape at 1 1
begin
comment monthData is a 1 dimensional slice of the array containing
comment OLR averages for each month for the given (lat,long)
comment c... | def getYearAvgs(self, oBY, month_list, monthIndex):
lats = self.getLats()
longs = self.getLongs()
for lat in range(0, oBY.shape[0]):
for long in range(0, oBY.shape[1], 1):
#
# monthData is a 1 dimensional slice of the array containing
#... | Python | nomic_cornstack_python_v1 |
async function test_create_limit_sell_order self
begin
set trade_result = dict string error 10009 ; string description string TRADE_RETCODE_DONE ; string orderId 46870472
set trade = call AsyncMock return_value=trade_result
set actual = await call create_limit_sell_order string GBPUSD 0.07 1.0 0.9 2.0 dict string comme... | async def test_create_limit_sell_order(self):
trade_result = {
'error': 10009,
'description': 'TRADE_RETCODE_DONE',
'orderId': 46870472
}
client.trade = AsyncMock(return_value=trade_result)
actual = await api.create_limit_sell_order('GBPUSD', 0.07, 1.0... | Python | nomic_cornstack_python_v1 |
function create_hexagon self center_x center_y width
begin
set h_val = SQRT_3_DIV_4 * width
set width_quarter = width / 4
set width_half = width / 2
set ring = call Geometry wkbLinearRing
comment Draw hexagon clockwise, beginning with northwest vertice
call AddPoint center_x - width_quarter center_y + h_val
call AddPoi... | def create_hexagon(self, center_x, center_y, width):
h_val = SQRT_3_DIV_4 * width
width_quarter = width / 4
width_half = width / 2
ring = ogr.Geometry(ogr.wkbLinearRing)
# Draw hexagon clockwise, beginning with northwest vertice
ring.AddPoint(center_x - width_quarter, ce... | Python | nomic_cornstack_python_v1 |
import turtle
set screen = call Screen
set trtle = call Turtle
call shape string circle
call shapesize 10
function red
begin
call color string red
end function
function blue
begin
call color string blue
end function
function green
begin
call color string green
end function
function black
begin
call color string black
e... | import turtle
screen = turtle.Screen()
trtle = turtle.Turtle()
trtle.shape('circle')
trtle.shapesize(10)
def red():
trtle.color('red')
def blue():
trtle.color('blue')
def green():
trtle.color('green')
def black():
trtle.color('black')
screen.onkeypress(red,'r')
screen.onkeypress(blue,'b')
screen.o... | Python | zaydzuhri_stack_edu_python |
function update_role self role_id name
begin
set role = get get_session role_model role_id
if not role
begin
return none
end
try
begin
set name = name
merge role
commit get_session
info format LOGMSG_INF_SEC_UPD_ROLE role
end
except Exception as e
begin
error format LOGMSG_ERR_SEC_UPD_ROLE e
rollback get_session
return... | def update_role(self, role_id, name: str) -> Role | None:
role = self.get_session.get(self.role_model, role_id)
if not role:
return None
try:
role.name = name
self.get_session.merge(role)
self.get_session.commit()
log.info(const.LOGMSG_... | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
set strings1 = list string xxx string xxxxxxxxx string xxxxxxxxx string xxxxxxxxx string xxxxxxxx
for string in strings1
begin
if string xxx in string
begin
comment Search for the string in the list of strings
set index = index strings1 string
set strings1 at index = string [censored]
end
end | # encoding: utf-8
strings1 = ['xxx', 'xxxxxxxxx', 'xxxxxxxxx', 'xxxxxxxxx', 'xxxxxxxx']
for string in strings1:
if 'xxx' in string:
index = strings1.index(string) # Search for the string in the list of strings
strings1[index] = '[censored]' | Python | zaydzuhri_stack_edu_python |
import discord
from discord.ext import commands
from random import shuffle
from math import floor
comment initialize global variables
set aram_in_progress = false
class LeagueOfLegends extends Cog
begin
function __init__ self bot
begin
set bot = bot
end function
decorator call command
comment "Makes two team from the g... | import discord
from discord.ext import commands
from random import shuffle
from math import floor
aram_in_progress = False #initialize global variables
class LeagueOfLegends(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def teamup(self, ctx, *args : str): #"Ma... | Python | zaydzuhri_stack_edu_python |
function test_character_clean_name self
begin
call assertEquals name string
end function | def test_character_clean_name(self):
self.assertEquals(self.character.name, '') | Python | nomic_cornstack_python_v1 |
import MySQLdb
class Field extends object
begin
pass
end class
class MetaModel extends type
begin
set db_table_name = none
set fields = dict
function __init__ cls name bases attrs
begin
call __init__ name bases attrs
set fields = dict
for tuple key val in items __dict__
begin
if is instance val Field
begin
set fields... | import MySQLdb
class Field(object):
pass
class MetaModel(type):
db_table_name = None
fields = {}
def __init__(cls, name, bases, attrs):
super(MetaModel, cls).__init__(name, bases, attrs)
fields = {}
for key, val in cls.__dict__.items():
if isinstance(val, Field):... | Python | zaydzuhri_stack_edu_python |
function LnsIp self
begin
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocolstack.lnsip_ec48a5dd0e5aa7799a7f283d3de4499d import LnsIp
return call LnsIp self
end function | def LnsIp(self):
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocolstack.lnsip_ec48a5dd0e5aa7799a7f283d3de4499d import LnsIp
return LnsIp(self) | Python | nomic_cornstack_python_v1 |
function to_json_string list_dictionaries
begin
if list_dictionaries is none or length list_dictionaries is 0
begin
return string []
end
else
begin
return dumps list_dictionaries
end
end function | def to_json_string(list_dictionaries):
if list_dictionaries is None or len(list_dictionaries) is 0:
return '[]'
else:
return json.dumps(list_dictionaries) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
comment (995ms)
function largestPalindrome self n
begin
string :type n: int :rtype: int
if n == 1
begin
return 9
end
set tuple upper lower palindromeFound = tuple 10 ^ n - 1 10 ^ n - 1 - 1 false
set left = upper * upper / 10 ^ n
while not palindromeFound
begin
set palindrome = intege... | class Solution(object):
# (995ms)
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 9
upper, lower, palindromeFound= 10 ** n - 1, 10 ** (n-1) -1, False
left = upper * upper / (10**n)
while not palindrome... | Python | zaydzuhri_stack_edu_python |
function initMatrix self h_size v_size
begin
call initMatrix self h_size v_size
end function | def initMatrix(self,h_size,v_size):
Rnn.initMatrix(self,h_size,v_size) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import json
set DF = read csv string cities.csv sep=string ;
print head DF
set cList = call tolist
set cDict = dict
for ct in cList
begin
set tempDF = iloc at tuple slice : : slice 3 : 5 :
set tempList = list
for i in range 0 shape at 0
begin
set lat = iloc at i
set lon = iloc at i
append temp... | import pandas as pd
import json
DF = pd.read_csv('cities.csv',sep=';')
print(DF.head())
cList = DF.country.unique().tolist()
cDict = {}
for ct in cList:
tempDF = DF[ DF['country']==ct ].iloc[:,3:5]
tempList = []
for i in range(0,tempDF.shape[0]):
lat = tempDF.lat.iloc[i]
lon = tempDF.lon.il... | Python | zaydzuhri_stack_edu_python |
function get_next self
begin
return list comprehension call as_array for t in call GetNextAsList
end function | def get_next(self):
return [t.as_array() for t in self.depipeline.GetNextAsList()] | Python | nomic_cornstack_python_v1 |
import random
import pandas as pd
import numpy as np
function points_per_million players
begin
for player in players
begin
set ppm = player at 4 / player at 5
append player ppm
end
return players
end function
function remove_some_players init_list remove_list
begin
set res = list filter lambda i -> i not in remove_list... | import random
import pandas as pd
import numpy as np
def points_per_million(players):
for player in players:
ppm = player[4] / player[5]
player.append(ppm)
return players
def remove_some_players(init_list, remove_list):
res = list(filter(lambda i: i not in remove_list, init_list))
re... | Python | zaydzuhri_stack_edu_python |
import pymongo
import random
import datetime
import string
comment Text files taken from https://github.com/dominictarr/random-name
set myclient = call MongoClient string mongodb://127.0.0.1:27017/
set mydb = myclient at string GHRS
set blood = list string A+ string AB+ string B+ string O+ string A- string AB- string B... | import pymongo
import random
import datetime
import string
# Text files taken from https://github.com/dominictarr/random-name
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
mydb = myclient["GHRS"]
blood = ["A+", "AB+", "B+", "O+", "A-", "AB-", "B-", "O-"]
gender = ['Male', 'Female', 'Transgend... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import datetime
from sklearn import datasets , linear_model
comment from sklearn import cross_validation, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
comment import KFold
from sklearn.model_selection import KFold
from skle... | import pandas as pd
import numpy as np
import datetime
from sklearn import datasets, linear_model
# from sklearn import cross_validation, linear_model
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from sklearn.model_selection import KFold # import KFold
from sklearn.model_sel... | Python | zaydzuhri_stack_edu_python |
function getOrNone cls **kwargs
begin
try
begin
return get objects keyword kwargs
end
except DoesNotExist
begin
return none
end
end function | def getOrNone(cls, **kwargs):
try:
return cls.objects.get(**kwargs)
except cls.DoesNotExist:
return None | Python | nomic_cornstack_python_v1 |
function delete_inventory
begin
set strIDDel = strip input string Which ID would you like to delete?:
while ValueError
begin
try
begin
integer strIDDel
break
end
except ValueError
begin
set strIDDel = strip input string Error: ID must be numeric. Enter ID:
end
end
return strIDDel
end function | def delete_inventory():
strIDDel = input('Which ID would you like to delete?: ').strip()
while ValueError:
try:
int(strIDDel)
break
except ValueError:
strIDDel = input('Error: ID must be numeric. Enter ID: ').strip()
... | Python | nomic_cornstack_python_v1 |
function read_channel filename appliance
begin
set channel_to_read = read csv filename names=list string Time appliance delim_whitespace=true
set channel_to_read at string Time = call to_datetime channel_to_read at string Time unit=string s
return channel_to_read
end function | def read_channel(filename, appliance):
channel_to_read = pd.read_csv(filename, names=["Time", appliance], delim_whitespace=True)
channel_to_read['Time'] = pd.to_datetime(channel_to_read['Time'],unit='s')
return channel_to_read | Python | nomic_cornstack_python_v1 |
from collections import Counter
function task1 seq charToReturn
begin
set res = counter seq
return res at charToReturn
end function
function reverse data
begin
set res = string
for item in data at slice : : - 1
begin
set res = res + item
end
return res
end function
function task2 inFileName outFileName
begin
set dat... | from collections import Counter
def task1(seq, charToReturn):
res = Counter(seq)
return res[charToReturn]
def reverse(data):
res = ''
for item in data[::-1]:
res += item
return res
def task2(inFileName, outFileName):
data = readFile(inFileName)
writeFile(outFileName, reverse(data)... | Python | zaydzuhri_stack_edu_python |
function dim_max self
begin
set x = call dim_x
set y = call dim_y
set z = call dim_z
if x >= y and x >= z
begin
return x
end
else
if y >= x and y >= z
begin
return y
end
else
begin
return z
end
end function | def dim_max(self):
x = self.dim_x()
y = self.dim_y()
z = self.dim_z()
if (x >= y) and (x >= z):
return x
elif (y >= x) and (y >= z):
return y
else:
return z | Python | nomic_cornstack_python_v1 |
import numpy as np
import sys
import string
import tensorflow as tf
class Model
begin
function __init__ self sess name layer learning_rate=0.001 keep_prob=0.8
begin
set sess = sess
set name = name
set learning_rate = learning_rate
set dropout_rate = keep_prob
set layer = layer
call _build_net
end function
function _bui... | import numpy as np
import sys
import string
import tensorflow as tf
class Model:
def __init__(self, sess, name, layer, learning_rate=0.001, keep_prob=0.8):
self.sess = sess
self.name = name
self.learning_rate = learning_rate
self.dropout_rate = keep_prob
self.layer = layer... | Python | zaydzuhri_stack_edu_python |
function test_branch_ubuntu self
begin
set m = call amgx branch=string v2.1.0
assert equal string m string # AMGX branch v2.1.0 RUN apt-get update -y && \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ git \ make && \ rm -rf /var/lib/apt/lists/* RUN mkdir -p /var/tmp && cd /var/tmp && git c... | def test_branch_ubuntu(self):
m = amgx(branch='v2.1.0')
self.assertEqual(str(m),
r'''# AMGX branch v2.1.0
RUN apt-get update -y && \
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
git \
make && \
rm -rf /var/lib/apt/lists/*
RUN mkdir -p /var/tmp && cd... | Python | nomic_cornstack_python_v1 |
function getConnection sliver_type
begin
comment sliver_type comes from rec['type'] and is of the form sliver.{LXC,QEMU}
comment so we need to lower case to lxc/qemu
set vtype = lower split sliver_type string . at 1
set uri = vtype + string :///
if uri not in connections
begin
comment create connection
set conn = open ... | def getConnection(sliver_type):
# sliver_type comes from rec['type'] and is of the form sliver.{LXC,QEMU}
# so we need to lower case to lxc/qemu
vtype = sliver_type.split('.')[1].lower()
uri = vtype + ':///'
if uri not in connections:
# create connection
c... | Python | nomic_cornstack_python_v1 |
for i in range length m
begin
print m at i i
end
set i = i + 1 | for i in range(len(m)):
print(m[i],i)
i+=1
| Python | zaydzuhri_stack_edu_python |
from spacegrid import SpaceGrid
class SquareGrid extends SpaceGrid
begin
string Implements Moore neighborhood (orthogonal and diagonal) adjacency graph.
function _adjacencies self pos
begin
set tuple x y = pos
return call cull_bounds list tuple x - 1 y tuple x + 1 y tuple x y - 1 tuple x y + 1
end function
function _co... | from spacegrid import SpaceGrid
class SquareGrid(SpaceGrid):
"""
Implements Moore neighborhood (orthogonal and diagonal) adjacency graph.
"""
def _adjacencies(self, pos):
x, y = pos
return self.cull_bounds([(x-1, y),
(x+1, y),
... | Python | zaydzuhri_stack_edu_python |
function Str2Bool string
begin
if string == string True or string == string true
begin
return true
end
else
begin
return false
end
end function | def Str2Bool(string):
if string == 'True' or string == 'true':
return True
else:
return False | Python | nomic_cornstack_python_v1 |
from pymongo import MongoClient
from bson.json_util import dumps
from flask import jsonify
comment Here dumps used to convert the pymongo cursor to json.
class crud_operation
begin
function __init__ self
begin
set collection = string users
set database = string user_management
set client = call MongoClient string mongo... | from pymongo import MongoClient
from bson.json_util import dumps
from flask import jsonify
# Here dumps used to convert the pymongo cursor to json.
class crud_operation:
def __init__(self):
self.collection = 'users'
self.database = 'user_management'
self.client = MongoClient('mongodb://loc... | Python | zaydzuhri_stack_edu_python |
from rgbmatrix import Adafruit_RGBmatrix
import util
set matrix = call Adafruit_RGBmatrix 32 1
function livereading coord color
begin
set xycoords = call converttoxy coord
set x = integer xycoords at 0
set y = integer xycoords at 1
comment error in x coord? backwards, correcting
if y > 16
begin
set y = 16 - y - 16
end
... | from rgbmatrix import Adafruit_RGBmatrix
import util
matrix = Adafruit_RGBmatrix(32,1)
def livereading(coord, color):
xycoords = util.converttoxy(coord)
x = int(xycoords[0])
y = int(xycoords[1])
#error in x coord? backwards, correcting
if y > 16:
y = 16-(y-16)
else:
y = 16 + (16-y)
thiscolorrgb = util.hext... | Python | zaydzuhri_stack_edu_python |
function create_headers_from_zipkin_attrs zipkin_attrs
begin
if not zipkin_attrs or not is_sampled
begin
return
end
return dict string x-b3-traceid trace_id ; string x-b3-flags flags ; string x-b3-spanid span_id ; string x-b3-sampled string 1
end function | def create_headers_from_zipkin_attrs(zipkin_attrs):
if not zipkin_attrs or not zipkin_attrs.is_sampled:
return
return {
'x-b3-traceid': zipkin_attrs.trace_id,
'x-b3-flags': zipkin_attrs.flags,
'x-b3-spanid': zipkin_attrs.span_id,
'x-b3-sampled': '1',
} | Python | nomic_cornstack_python_v1 |
function rounds self
begin
set round = round + 1
end function | def rounds(self):
self.round += 1 | Python | nomic_cornstack_python_v1 |
comment // Time Complexity :O(m*n)
comment // Space Complexity :O(m*n)
comment // Did this code successfully run on Leetcode :yes
comment // Any problem you faced while coding this :no
comment // Your code here along with comments explaining your approach
class Solution
begin
function orangesRotting self grid
begin
set... | # // Time Complexity :O(m*n)
# // Space Complexity :O(m*n)
# // Did this code successfully run on Leetcode :yes
# // Any problem you faced while coding this :no
# // Your code here along with comments explaining your approach
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m=l... | Python | zaydzuhri_stack_edu_python |
function create_id component name
begin
return format string {}_{} name InstanceGuid
end function | def create_id(component, name):
return "{}_{}".format(name, component.InstanceGuid) | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[39]:
set mylist = list
set x = list string AMMAN string ZARQA string MAFRAQ string BALQA string IRBID string JARASH string AJLOUN string KARAK string TAFILA string MAAN string AQABA
set mylist = list string AMMAN string ZARQA string MAFRAQ string BALQA string IRBID string JARASH string... | # coding: utf-8
# In[39]:
mylist=[]
x=mylist=["AMMAN","ZARQA","MAFRAQ","BALQA","IRBID","JARASH","AJLOUN","KARAK","TAFILA","MAAN","AQABA"]
print(mylist)
print(len(mylist))
mylist.sort()
print(mylist)
| 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.