code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function element_wait self selector secs=1
begin
if string => not in selector
begin
raise call NameError string Positioning syntax errors, lack of '=>'.
end
set by = strip split selector string => at 0
set value = strip split selector string => at 1
set messages = format string Element: {0} not found in {1} seconds. se... | def element_wait(self, selector, secs=1):
if "=>" not in selector:
raise NameError("Positioning syntax errors, lack of '=>'.")
by = selector.split("=>")[0].strip()
value = selector.split("=>")[1].strip()
messages = 'Element: {0} not found in {1} seconds.'.format(selector, se... | Python | nomic_cornstack_python_v1 |
comment This is a sample Python script.
comment Press Shift+F10 to execute it or replace it with your code.
comment Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import hashlib
set mystring = input string enter your string:
set hash_obj = md5 encode mystring
print hex ... | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import hashlib
mystring = input ('enter your string:')
hash_obj = hashlib.md5(mystring.encode())
print(hash_obj.hexdi... | Python | zaydzuhri_stack_edu_python |
comment lancio tramite
comment mpirun -np N python taskAssignDisropt.py
from bundle_algo import BundleAlgorithm , DistanceScoreFunction
import time , sys , math
import numpy as np
from mpi4py import MPI
from disropt.agents import Agent
import argparse
from task_positions import load_positions
set start_time = time
set ... | # lancio tramite
# mpirun -np N python taskAssignDisropt.py
from bundle_algo import BundleAlgorithm, DistanceScoreFunction
import time, sys, math
import numpy as np
from mpi4py import MPI
from disropt.agents import Agent
import argparse
from task_positions import load_positions
start_time = time.time()
... | Python | zaydzuhri_stack_edu_python |
string Views for the customer section of the system. Views take a web request and return a web response.
from django.shortcuts import render , redirect
from core.models import Menu , Order , Payment , Seating
from django.views.decorators.csrf import ensure_csrf_cookie
decorator ensure_csrf_cookie
function index request... | """
Views for the customer section of the system. Views take a web request and return a web response.
"""
from django.shortcuts import render, redirect
from core.models import Menu, Order, Payment, Seating
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def index(request):
"""
... | Python | zaydzuhri_stack_edu_python |
comment Массив размером 2m + 1, где m — натуральное число,
comment заполнен случайным образом. Найдите в массиве медиану.
comment Медианой называется элемент ряда, делящий его на две равные части:
comment в одной находятся элементы, которые не меньше медианы,
comment в другой — не больше медианы.
from random import shu... | # Массив размером 2m + 1, где m — натуральное число,
# заполнен случайным образом. Найдите в массиве медиану.
# Медианой называется элемент ряда, делящий его на две равные части:
# в одной находятся элементы, которые не меньше медианы,
# в другой — не больше медианы.
from random import shuffle, randint
from numpy impo... | Python | zaydzuhri_stack_edu_python |
comment Lambda Functions
comment Lambda functions can have any number of arguments but only one expression.
comment The expression is evaluated and returned.
comment Lambda functions can be used wherever function objects are required.
set square = lambda x -> x * x
print call square 7
print call square 5
set odd_list =... | # Lambda Functions
## Lambda functions can have any number of arguments but only one expression.
## The expression is evaluated and returned.
# Lambda functions can be used wherever function objects are required.
square = lambda x: x * x
print(square(7))
print(square(5))
odd_list = [1,3,5,7,9,11,13,15,17,19,21,23,25... | Python | zaydzuhri_stack_edu_python |
function get_vul_info vul_info
begin
set packages = list
if get vul_info string fixes is none
begin
return packages
end
for fixes in vul_info at string fixes
begin
extend packages call get_package_os fixes
end
return packages
end function | def get_vul_info(vul_info):
packages = []
if vul_info.get('fixes') is None:
return packages
for fixes in vul_info['fixes']:
packages.extend(get_package_os(fixes))
return packages | Python | nomic_cornstack_python_v1 |
comment !/bin/python
comment this script will apply the protocol decoder and show me the message
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import low_pass_filter
set data = read csv string data_log.csv
set d = list data at string values_filtered
set tuple result timing = call decode_myproto... | #!/bin/python
#this script will apply the protocol decoder and show me the message
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import low_pass_filter
data = pd.read_csv('data_log.csv')
d = list(data['values_filtered'])
result,timing = low_pass_filter.decode_myprotocol_sync(d,11)
r = np.ara... | Python | zaydzuhri_stack_edu_python |
function str_to_date string
begin
return if expression string then string parse time string DATE_FORMAT else none
end function | def str_to_date(string):
return datetime.datetime.strptime(string, DATE_FORMAT) if string else None | Python | nomic_cornstack_python_v1 |
function embed_tokens_to_list markers tokens
begin
set tokens = tokens at slice : :
for marker in markers
begin
try
begin
set tokens at start_idx = string < { tag } > { tokens at start_idx }
set tokens at end_idx - 1 = string { tokens at end_idx - 1 } </ { tag } >
end
except IndexError as e
begin
exception string Un... | def embed_tokens_to_list(markers: List[NERMarker], tokens: List[str]) -> List[str]:
tokens = tokens[:]
for marker in markers:
try:
tokens[marker.start_idx] = f"<{marker.tag}>{tokens[marker.start_idx]}"
tokens[marker.end_idx - 1] = f"{tokens[marker.end_idx - 1]}</{marker.tag}>"
... | Python | nomic_cornstack_python_v1 |
import sys , re
import operator
import stemmer
from collections import defaultdict
set inFile = string
if length argv < 2
begin
print string Nesto nije ok
exit
end
else
begin
set inFile = argv at 1
end
set inp = open inFile encoding=string utf-8 mode=string r
set text = read inp
close inp
set text = sub string [\W_]+ ... | import sys,re
import operator
import stemmer
from collections import defaultdict
inFile=""
if len(sys.argv)<2:
print("Nesto nije ok")
sys.exit()
else:
inFile=sys.argv[1]
inp = open(inFile,encoding="utf-8",mode="r")
text = inp.read()
inp.close()
text = re.sub('[\W_]+',' ',text)
splits = tex... | Python | zaydzuhri_stack_edu_python |
function get_address self list_item
begin
set Address = named tuple string Address list string addr string city string state string zip
set extract = list comprehension text for text in stripped_strings
comment Sometimes a street address is not given
if length extract == 1
begin
set tuple addr rest = tuple none extract... | def get_address(self, list_item):
Address = namedtuple('Address', ['addr', 'city', 'state', 'zip'])
extract = [text for text in list_item.find('address').stripped_strings]
# Sometimes a street address is not given
if len(extract) == 1:
addr, rest = None, extract[0]
e... | Python | nomic_cornstack_python_v1 |
function to_representation self data
begin
comment Dealing with nested relationships, data can be a Manager,
comment so, first get a queryset from the Manager if needed
return list comprehension call to_representation item for item in data
end function | def to_representation(self, data):
# Dealing with nested relationships, data can be a Manager,
# so, first get a queryset from the Manager if needed
return [self.child.to_representation(item) for item in data] | Python | nomic_cornstack_python_v1 |
comment -*-coding:utf-8-*-
string A script to change pois to poi_clusters DBSCAN: https://www.cnblogs.com/tiaozistudy/p/dbscan_algorithm.html
import numpy as np
import math
import random
from scipy.spatial import KDTree
import arcpy
import sys
import time
set __version__ = string 1.5
set __author__ = string Yicong Li
c... | #-*-coding:utf-8-*-
'''
A script to change pois to poi_clusters
DBSCAN: https://www.cnblogs.com/tiaozistudy/p/dbscan_algorithm.html
'''
import numpy as np
import math
import random
from scipy.spatial import KDTree
import arcpy
import sys
import time
__version__ = '1.5'
__author__ = 'Yicong Li'
... | Python | zaydzuhri_stack_edu_python |
comment Count Letters
set letters = string ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
comment Write your unique_english_letters function here:
function unique_english_letters word
begin
set letters = string ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
set count = 0
set check = list
for letter in word... | #Count Letters
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Write your unique_english_letters function here:
def unique_english_letters(word):
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
count = 0
check = []
for letter in word:
if letter in letters and not letter ... | Python | zaydzuhri_stack_edu_python |
function collect_tasks_fn tn data
begin
if not call is_root_node
begin
set data at address = call GraphTask tn resources
end
end function | def collect_tasks_fn(
tn: TraversalNode, data: Dict[CollectionAddress, GraphTask]
) -> None:
if not tn.is_root_node():
data[tn.address] = GraphTask(tn, resources) | Python | nomic_cornstack_python_v1 |
async function agender self ctx image=none
begin
if not image
begin
set image = call image_lookup message
end
set flag = call agender
await call pride_flag_posting ctx flag image
end function | async def agender(self, ctx, image: roxbot.converters.AvatarURL = None):
if not image:
image = self.image_lookup(ctx.message)
flag = Flag.agender()
await self.pride_flag_posting(ctx, flag, image) | Python | nomic_cornstack_python_v1 |
class MQTTException extends BaseException
begin
function __init__ self message
begin
set message = message
end function
function __repr__ self
begin
return string MQTTException: { message }
end function
end class | class MQTTException(BaseException):
def __init__(self, message):
self.message = message
def __repr__(self):
return f'MQTTException: {self.message}'
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import random
import string
import unittest
from api import API
function generate_random_text l=10
begin
string Helper to generate random text for creating new tasks. This is helpful and will ensure that when you run your tests, a new text string is created. It is also good for determining... | #!/usr/bin/env python3
import random
import string
import unittest
from api import API
def generate_random_text(l=10):
""" Helper to generate random text for creating new tasks.
This is helpful and will ensure that when you run your tests,
a new text string is created. It is also good for determining
... | Python | zaydzuhri_stack_edu_python |
function radius self radius
begin
pass
end function | def radius(self, radius):
pass | Python | nomic_cornstack_python_v1 |
from django.db import models
comment Create your models here.
class Curso extends Model
begin
set codigo = call CharField max_length=6 primary_key=true
set nome = call CharField max_length=50
set professor = call CharField max_length=50
set creditos = call PositiveSmallIntegerField
function __str__ self
begin
set texto... | from django.db import models
# Create your models here.
class Curso(models.Model):
codigo=models.CharField(max_length=6, primary_key=True)
nome=models.CharField(max_length=50)
professor=models.CharField(max_length=50)
creditos=models.PositiveSmallIntegerField()
def __str__(self):
texto = "... | Python | zaydzuhri_stack_edu_python |
function vec_normal vec
begin
set n = square root sum generator expression x ^ 2 for x in vec or 1
return list comprehension x / n for x in vec
end function | def vec_normal(vec):
n = sqrt(sum(x ** 2 for x in vec)) or 1
return [x / n for x in vec] | Python | nomic_cornstack_python_v1 |
function get_n_gram self input n=2
begin
return list comprehension x for x in call ngrams call tokenize input n
end function | def get_n_gram(self, input , n = 2):
return [ x for x in ngrams(self.tokenize(input), n ) ] | Python | nomic_cornstack_python_v1 |
import requests
import json
set URL = string https://api.tfl.gov.uk/
function get_url url payload=none
begin
set url = url + string ?app_id=2a3e2338&app_key=240b28f5941f4c099fc40f5af851d5d6
set response = get requests url params=payload
set content = decode content string utf8
return content
end function
function get_j... | import requests
import json
URL = 'https://api.tfl.gov.uk/'
def get_url(url, payload=None):
url = url + '?app_id=2a3e2338&app_key=240b28f5941f4c099fc40f5af851d5d6'
response = requests.get(url, params=payload)
content = response.content.decode('utf8')
return content
def get_json_from_url(ur... | Python | zaydzuhri_stack_edu_python |
comment Prefill an array
comment https://www.codewars.com/kata/54129112fb7c188740000162
comment 04/11/2021
comment The final submitted function
function prefill n v=none
begin
try
begin
return list comprehension v for i in range integer n
end
except any
begin
raise call TypeError format string {} is invalid n
end
end f... | # Prefill an array
# https://www.codewars.com/kata/54129112fb7c188740000162
# 04/11/2021
# The final submitted function
def prefill(n,v=None):
try:
return [v for i in range(int(n))]
except:
raise TypeError("{} is invalid".format(n))
# Test code sample
#generated_array = prefill('0','2d')
#... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import random
function merge_sort items comp=lambda x y -> x <= y
begin
string 归并排序 :param items: :param comp: :return:
if length items < 2
begin
return items at slice : :
end
set mid = length items // 2
set left = call merge_sort items at slice : mid : co... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def merge_sort(items, comp=lambda x, y: x <= y):
"""
归并排序
:param items:
:param comp:
:return:
"""
if len(items) < 2:
return items[:]
mid = len(items) // 2
left = merge_sort(items[:mid], comp)
right = merge_sort... | Python | zaydzuhri_stack_edu_python |
from random import randint
function flip_coin flips
begin
set heads_count = 0
set tails_count = 0
for i in range 0 flips
begin
if random integer 0 1 == 0
begin
set heads_count = heads_count + 1
end
else
begin
set tails_count = tails_count + 1
end
end
set heads_probability = round heads_count / flips 1 * 100
set tails_p... | from random import randint
def flip_coin(flips):
heads_count = 0
tails_count = 0
for i in range(0, flips):
if (randint(0, 1) == 0):
heads_count += 1
else:
tails_count += 1
heads_probability = (round(heads_count/flips, 1) * 100)
tails_probability = (ro... | Python | zaydzuhri_stack_edu_python |
function _create_user self password **extra_fields
begin
try
begin
set user = model keyword extra_fields
call set_password password
save using=_db
return user
end
except any
begin
raise call ValueError string ValueError: Cannot create new user
end
end function | def _create_user(self, password, **extra_fields):
try:
user = self.model(**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
except:
raise ValueError('ValueError: Cannot create new user') | Python | nomic_cornstack_python_v1 |
async function timed_motd self
begin
try
begin
await call wait_until_ready
while not is_closed
begin
await sleep 10
for channelkey in motd_list
begin
set channel = call get_channel channelkey
if now > call fromtimestamp integer motd_list at channelkey at 1
begin
set message_id = 0
try
begin
async_for message in call lo... | async def timed_motd(self):
try:
await self.bot.wait_until_ready()
while not self.bot.is_closed:
await asyncio.sleep(10)
for channelkey in self.motd_list:
channel = self.bot.get_channel(channelkey)
if datetime.datet... | Python | nomic_cornstack_python_v1 |
function shift_down self idx end
begin
while idx < end
begin
set left = call index_left idx
set right = call index_right idx
set imin = call index_smaller arr left right end
if imin > end or arr at idx < arr at imin
begin
return
end
set tuple arr at idx arr at imin = tuple arr at imin arr at idx
set k1 = key
set keys a... | def shift_down(self, idx, end):
while idx < end:
left = index_left(idx)
right = index_right(idx)
imin = index_smaller(self.arr, left, right, end)
if imin > end or self.arr[idx] < self.arr[imin]:
return
self.arr[idx], self.arr[imin] = s... | Python | nomic_cornstack_python_v1 |
function save self path
begin
print string Saving model... %s % path
save self path
end function | def save(self, path):
print('Saving model... %s' % path)
torch.save(self, path) | Python | nomic_cornstack_python_v1 |
function lex_index n k lst
begin
string Return the lex index of a combination.. Args: n (int): the total number of options . k (int): The number of elements. lst (list): list Returns: int: returns int index for lex order Raises: VisualizationError: if length of list is not equal to k
if length lst != k
begin
raise call... | def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is n... | Python | jtatman_500k |
function websites self
begin
return dict string support call _getData at string supportURL ; string modpack call _getData at string websiteURL
end function | def websites(self):
return {
'support': self._getData()['supportURL'],
'modpack': self._getData()['websiteURL']
} | Python | nomic_cornstack_python_v1 |
function test_playwright_failure_to_initialize_browser_library sarge
begin
set cmd = string list executable string -m string Browser.entry string init
set side_effect = call mock_Command returncodes=dict cmd 1
with patch string cumulusci.cli.robot._is_package_installed return_value=false
begin
with raises ClickExceptio... | def test_playwright_failure_to_initialize_browser_library(sarge):
cmd = str([sys.executable, "-m", "Browser.entry", "init"])
sarge.Command.side_effect = mock_Command(returncodes={cmd: 1})
with mock.patch("cumulusci.cli.robot._is_package_installed", return_value=False):
with pytest.raises(
... | Python | nomic_cornstack_python_v1 |
function columnarTansposition_makeRectangleWithPlaintext_withkey plaintext key
begin
comment On purge le texte
set plaintext = call deponctuateMessage plaintext
comment On trouve la largeur du rectangle
set rectangleWidth = length key
comment Nombre de lignes pleines
set rectangleHeight = length plaintext // rectangleW... | def columnarTansposition_makeRectangleWithPlaintext_withkey(plaintext, key):
plaintext = deponctuateMessage(plaintext) # On purge le texte
rectangleWidth = len(key) # On trouve la largeur du rectangle
rectangleHeight = len(plaintext)//rectangleWidth # Nombre de lignes pleines
rectangleLastRowWidth = len(plainte... | Python | nomic_cornstack_python_v1 |
function token_occurrence poems tokenizer data_tag=string tok_tag=string save=true
begin
comment Counter
print string Encoding and counting
set token_count = counter
for segment in poems
begin
comment numerical value (encoding)
set encoded = encode tokenizer segment add_special_tokens=false
for e in encoded
begin
set... | def token_occurrence(poems, tokenizer, data_tag='', tok_tag='', save=True):
# Counter
print("Encoding and counting")
token_count = collections.Counter()
for segment in poems:
encoded = tokenizer.encode(segment, add_special_tokens=False) # numerical value (encoding)
for e in encoded:
... | Python | nomic_cornstack_python_v1 |
from collections import defaultdict as dd
function mex arr
begin
if diff == 1
begin
for i in range min arr max arr + 1
begin
if i not in arr
begin
return i + 1
end
end
end
return min arr + 1
end function
for _ in range integer input
begin
set tuple n q m = map int split input
set l = list map int split input
set diff =... | from collections import defaultdict as dd
def mex(arr):
if diff == 1:
for i in range(min(arr), max(arr)+1):
if i not in arr:
return i+1
return min(arr)+1
for _ in range(int(input())):
n, q, m = map(int, input().split())
l = list(map(int, input().split()))
diff... | Python | zaydzuhri_stack_edu_python |
function pmtfv pmt=none fval=none nrate=none nper=none pyr=1 noprint=true
begin
return call tvmm pval=0 fval=fval pmt=pmt nrate=nrate nper=nper due=1 pyr=pyr noprint=noprint
end function | def pmtfv(pmt=None, fval=None, nrate=None, nper=None, pyr=1, noprint=True):
return tvmm(pval=0, fval=fval, pmt=pmt, nrate=nrate, nper=nper, due=1, pyr=pyr, noprint=noprint) | Python | nomic_cornstack_python_v1 |
import random
function main
begin
set choices = list string rock string paper string scissor
set user_choice = false
while user_choice == false
begin
set cpu_choice = random choice choices
set user_choice = input string enter a choice (rock, paper, scissor):
print string cpu chose { cpu_choice }
if user_choice not in c... | import random
def main():
choices = ['rock', 'paper', 'scissor']
user_choice = False
while user_choice == False:
cpu_choice = random.choice(choices)
user_choice = input('enter a choice (rock, paper, scissor): ')
print(f'cpu chose {cpu_choice}')
if user_choice not in choices:
print('not a valid choice')
... | Python | zaydzuhri_stack_edu_python |
function stats e
begin
set email = if expression e then e else GIT_CONFIG at string email
set balance = call get_total_brownie_points email
set tuple today_income today_expenditure = call get_todays_stats email
set earned = call style string Today Earned: + string today_income fg=string green
set spent = call style str... | def stats(e):
email = e if e else broc.GIT_CONFIG['email']
balance = db.get_total_brownie_points(email)
today_income, today_expenditure = db.get_todays_stats(email)
earned = click.style('Today Earned: ' + str(today_income), fg='green')
spent = click.style('Today Spent: ' + str(today_expenditure), ... | Python | nomic_cornstack_python_v1 |
function testBasename self
begin
set result = call runProcedure string basename __path
assert equal result string example.ext
end function | def testBasename(self):
result = Template.runProcedure("basename", self.__path)
self.assertEqual(result, "example.ext") | Python | nomic_cornstack_python_v1 |
for item in zip mylist1 mylist2 mylist3
begin
print item
end | for item in zip(mylist1,mylist2,mylist3):
print(item) | Python | zaydzuhri_stack_edu_python |
import pickle
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
comment import some data to play with
set iris = call load_iris
set X = data
set y = target
set clf = logistic regre... | import pickle
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
# import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
clf = LogisticRegression... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
string Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST A... | # coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... | Python | jtatman_500k |
function test_rpc self
begin
set events = list comprehension event loop=loop for _ in range 2
set results = dict string input string ; string output string ; string n_results 0
set req = call ToyRpcInput
set val = string req val
set resp = call ToyRpcOutput
set ret = string resp val
set in_xpath = string I,/rw-dts-to... | def test_rpc(self):
events = [asyncio.Event(loop=self.loop) for _ in range(2)]
results = {
'input': '',
'output': '',
'n_results': 0,
}
req = toyyang.ToyRpcInput()
req.val = 'req val'
resp = toyyang.ToyRpcOutput()
resp.ret = '... | Python | nomic_cornstack_python_v1 |
comment !/bin/python3
import sys
function solve a b
begin
set A = 0
set B = 0
for x in range 3
begin
if a at x > b at x
begin
set A = A + 1
end
else
if a at x < b at x
begin
set B = B + 1
end
end
set result = string A + string + string B
return result
end function
set tuple a0 a1 a2 = split strip input string
set a = ... | #!/bin/python3
import sys
def solve(a,b):
A = B =0
for x in range(3):
if a[x] > b[x]:
A = A + 1
elif a[x] < b [x]:
B = B + 1
result = str(A) + ' ' + str(B)
return(result)
a0, a1, a2 = input().strip().split(' ')
a = [int(a0), int(a1), int(a2)]
b0, b1, b2 = input... | Python | zaydzuhri_stack_edu_python |
import keras
import numpy as np
from keras import layers
set model = sequential list dense units=1 input_shape=list 1
comment stochastic gradient descent
compile optimizer=string sgd loss=string mean_squared_error
comment y = 2x - 1
set xs = array list - 4.0 - 3.0 - 2.0 - 1.0 0.0 1.0 2.0 3.0 4.0 dtype=float
set ys = ar... | import keras
import numpy as np
from keras import layers
model = keras.Sequential([layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error') # stochastic gradient descent
# y = 2x - 1
xs = np.array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([... | Python | zaydzuhri_stack_edu_python |
function pyspex_version full=false githash=false
begin
if full
begin
return __version__
end
if githash
begin
set res = split __version__ string +g
if length res > 1
begin
return split res at 1 string . at 0
end
return string v + join string list comprehension string { integer x } for x in split res at 0 string .
end
r... | def pyspex_version(full=False, githash=False):
if full:
return __version__
if githash:
res = __version__.split('+g')
if len(res) > 1:
return res[1].split('.')[0]
return 'v' + ''.join([f'{int(x):02d}' for x in res[0].split('.')])
return __version__.split('+')[0] | Python | nomic_cornstack_python_v1 |
function flush self path
begin
set pickledict = dictionary trainlosses=trainlosses lrs=lrs costs=costs acc=acc confusion_matrices=confusion_matrices
set filename = path + string /blackboxpipe.pkl
with open filename string wb as handle
begin
dump pickledict handle protocol=HIGHEST_PROTOCOL
end
end function | def flush(self, path):
pickledict = dict(
trainlosses=self.trainlosses, lrs=self.lrs, costs=self.costs,
acc=self.acc, confusion_matrices=self.confusion_matrices)
filename = path + '/blackboxpipe.pkl'
with open(filename, 'wb') as handle:
pickle.dump(pickledict... | Python | nomic_cornstack_python_v1 |
from dataclasses import dataclass , field
from typing import Optional
from date import Date
from revision_label_string import RevisionLabelString
set __NAMESPACE__ = string http://autosar.org/schema/r4.0
decorator dataclass
class LifeCyclePeriod
begin
string This meta class represents the ability to specify a point of ... | from dataclasses import dataclass, field
from typing import Optional
from .date import Date
from .revision_label_string import RevisionLabelString
__NAMESPACE__ = "http://autosar.org/schema/r4.0"
@dataclass
class LifeCyclePeriod:
"""
This meta class represents the ability to specify a point of time within a
... | Python | zaydzuhri_stack_edu_python |
string 279. Perfect Squares Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. Exampl... | '''
279. Perfect Squares
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Exam... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from util import calcWaveletCoef , calcScalingCoef
function calcCoef target result
begin
for tuple tar res in zip target at tuple slice : : slice : : result at tuple slice : : slice : :
begin
set scl = call calcScalingCoef tar
set wav =... | import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from util import calcWaveletCoef, calcScalingCoef
def calcCoef(target, result):
for tar, res in zip(target[:, :], result[:, :]):
scl = calcScalingCoef(tar)
wav = calcWaveletCoef(tar)
res[:len(scl)] = scl
r... | Python | zaydzuhri_stack_edu_python |
comment This impor all necessary moduls we will need
import numpy as np
import pandas as pd
import math
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
import matplotlib.pyplot as pat
call use string fivethirtyeight
from loadingData import loadData
comment Loading data from 2012-01-01 to 2019-12-... | # This impor all necessary moduls we will need
import numpy as np
import pandas as pd
import math
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
import matplotlib.pyplot as pat
plt.style.use('fivethirtyeight')
from loadingData import loadData
# Loading data from 2012-01-01 to 2019-12-17
df = lo... | Python | zaydzuhri_stack_edu_python |
function bootstrapRedis serverName
begin
comment Install requirements
call sudo string DEBIAN_FRONTEND=noninteractive apt-get install -y redis-server
call deployConfigFiles dict string server-name serverName tuple string redis/redis.conf string /etc/redis/redis.conf
end function | def bootstrapRedis(serverName):
# Install requirements
sudo('DEBIAN_FRONTEND=noninteractive apt-get install -y '
'redis-server')
deployConfigFiles(
{'server-name': serverName},
('redis/redis.conf', '/etc/redis/redis.conf')) | Python | nomic_cornstack_python_v1 |
function cmdFileOutput *args **kwargs
begin
pass
end function | def cmdFileOutput(*args, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
function visualize_scatter df feat1=0 feat2=1 labels=2
begin
set colors = call Series list comprehension if expression label > 0 then string r else string b for label in df at labels
set ax = plot x=feat1 y=feat2 kind=string scatter c=colors
show
end function | def visualize_scatter(df, feat1=0, feat2=1, labels=2):
colors = pd.Series(['r' if label > 0 else 'b' for label in df[labels]])
ax = df.plot(x=feat1, y=feat2, kind='scatter', c=colors)
plt.show() | Python | nomic_cornstack_python_v1 |
function run argv=none
begin
set input_filename = string input.txt
set output_filename = string report.txt
comment project_id = os.environ['DATASTORE_PROJECT_ID']
comment credentials_file = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
comment client = datastore.Client.from_service_account_json(credentials_file)
set opt... | def run(argv=None):
input_filename = 'input.txt'
output_filename = 'report.txt'
# project_id = os.environ['DATASTORE_PROJECT_ID']
# credentials_file = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
# client = datastore.Client.from_service_account_json(credentials_file)
op... | Python | nomic_cornstack_python_v1 |
function poweroff_vm vm_id
begin
info string Powering off VM: %s... % vm_id
call bash string VBoxManage controlvm { vm_id } poweroff
end function | def poweroff_vm(vm_id):
logging.info("Powering off VM: %s..." % vm_id)
bash(f'VBoxManage controlvm {vm_id} poweroff') | Python | nomic_cornstack_python_v1 |
comment Original Author: sreekeshpadmanabhan@gmail.com
comment Implementation of Heapsort algorithms as described & analyzed from Introduction to Algorithms by CLRS
comment https://drive.google.com/file/d/121Ih7X4AMuo4239af91vRYXHpwBfVIaq/view?usp=sharing
import random
class HeapClass
begin
function __init__ self
begin... | # Original Author: sreekeshpadmanabhan@gmail.com
# Implementation of Heapsort algorithms as described & analyzed from Introduction to Algorithms by CLRS
# https://drive.google.com/file/d/121Ih7X4AMuo4239af91vRYXHpwBfVIaq/view?usp=sharing
import random
class HeapClass:
def __init__(self):
self.heap_size = ... | Python | zaydzuhri_stack_edu_python |
function addstr arg1 arg2
begin
return string arg1 + string arg2
end function | def addstr(arg1, arg2):
return str(arg1) + str(arg2) | Python | nomic_cornstack_python_v1 |
function train self corpus
begin
set lastToken = string #
for sentence in corpus
begin
for datum in data
begin
set token = word
set reverseBigramCount at token at lastToken = reverseBigramCount at token at lastToken + 1
set bigramCount at lastToken at token = bigramCount at lastToken at token + 1
set unigramCount at to... | def train(self, corpus):
lastToken = "#"
for sentence in corpus.corpus:
for datum in sentence.data:
token = datum.word
self.reverseBigramCount[token][lastToken] += 1
self.bigramCount[lastToken][token] += 1
self.unigramCount[token] += 1
self.total += 1
lastTo... | Python | nomic_cornstack_python_v1 |
comment https://practice.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1/?category[]=Mathematical&category[]=Arrays&category[]=Strings&category[]=Mathematical&category[]=Arrays&category[]=Strings&company[]=Amazon&company[]=Microsoft&company[]=Adobe&company[]=Samsung&company[]=Accolite&c... | # https://practice.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1/?category[]=Mathematical&category[]=Arrays&category[]=Strings&category[]=Mathematical&category[]=Arrays&category[]=Strings&company[]=Amazon&company[]=Microsoft&company[]=Adobe&company[]=Samsung&company[]=Accolite&company... | Python | zaydzuhri_stack_edu_python |
function inter_cost cluster
begin
function _p2p point
begin
set _freq_sum = 0
for pt in points
begin
if point != pt
begin
set _freq_sum = _freq_sum + call frequency pt
end
end
return _freq_sum
end function
return integer sum map _p2p points
end function | def inter_cost(cluster):
def _p2p(point):
_freq_sum = 0
for pt in cluster.points:
if point != pt:
_freq_sum += point.frequency(pt)
return _freq_sum
return int(sum(map(_p2p, cluster.points))) | Python | nomic_cornstack_python_v1 |
comment m = m.replace(" ", "")
set m = strip m
print m
set kucuk_course = lower course
print kucuk_course
set kactane_a = count website string a
print kactane_a
set basliyormu = starts with website string www
set bitiyormu = ends with website string com
print basliyormu
print bitiyormu
set varmı = find website string .... | # m = m.replace(" ", "")
m = m.strip()
print(m)
kucuk_course = course.lower()
print(kucuk_course)
kactane_a = website.count("a")
print(kactane_a)
basliyormu = website.startswith("www")
bitiyormu = website.endswith("com")
print(basliyormu)
print(bitiyormu)
varmı = website.find(".com")
print(varmı)
alfamı = course.... | Python | zaydzuhri_stack_edu_python |
string Embedding and captioning new images
import cPickle as pkl
import numpy
from PIL import Image
from PIL import ImageFile
import lasagne
import skimage.transform
from lasagne.layers import InputLayer , DenseLayer , NonlinearityLayer
from lasagne.layers import MaxPool2DLayer as PoolLayer
from lasagne.layers.corrmm i... | """
Embedding and captioning new images
"""
import cPickle as pkl
import numpy
from PIL import Image
from PIL import ImageFile
import lasagne
import skimage.transform
from lasagne.layers import InputLayer, DenseLayer, NonlinearityLayer
from lasagne.layers import MaxPool2DLayer as PoolLayer
from lasagne.layers.corrmm i... | Python | zaydzuhri_stack_edu_python |
function coinChange self amount coins
begin
string We can solve this efficiently using Dynamic programming , the intution is using 0-1 Knapsack problem 1) Build a Matrix of M[r][c] = [amount+1][len(coins)+1] 2) Fill the first row with zeros's (As sum 0 can be produced without taking any coin) 3) At each point M[c_amoun... | def coinChange(self, amount, coins):
"""
We can solve this efficiently using Dynamic programming , the intution is using 0-1 Knapsack problem
1) Build a Matrix of M[r][c] = [amount+1][len(coins)+1]
2) Fill the first row with zeros's (As sum 0 can be produced without taking any coin)
... | Python | nomic_cornstack_python_v1 |
function drag_hold self element_name=none
begin
set el1 = call get_web_element call get_element element_name
call auto_log_error format string Attempting to find element value '{}' element_name
set action0 = call move_to el1 10 200
set action1 = call move_to el1 200 10
set ma = call MultiAction driver
add ma action0 ac... | def drag_hold(self, element_name=None):
el1 = self.utils.get_web_element(self.get_element(element_name))
self.cl.auto_log_error("Attempting to find element value '{}'".format(element_name))
action0 = TouchAction().tap(el1).move_to(el1, 10, 200)
action1 = TouchAction().tap(el1).move_to(el... | Python | nomic_cornstack_python_v1 |
function repository_blob self sha **kwargs
begin
string Return a file by blob SHA. Args: sha(str): ID of the blob **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the server failed to perform the request Returns: dict: The b... | def repository_blob(self, sha, **kwargs):
"""Return a file by blob SHA.
Args:
sha(str): ID of the blob
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: I... | Python | jtatman_500k |
import numpy as np
import cv2
import pickle
comment Load the initial parameters
set filename = string watershed.pkl
set infile = open filename string rb
set init_values = load pickle infile
close infile
comment Initial parameters
set hue_labels = init_values at string hue_labels
set noise_kernel_dim = init_values at st... | import numpy as np
import cv2
import pickle
# Load the initial parameters
filename = 'watershed.pkl'
infile = open(filename,'rb')
init_values = pickle.load(infile)
infile.close()
# Initial parameters
hue_labels = init_values['hue_labels']
noise_kernel_dim = init_values['noise_kernel_dim']
morph_iterations = init_valu... | Python | zaydzuhri_stack_edu_python |
function from_callable cls obj
begin
set namespace = none
set arg_types = list
set var_arg_type = none
comment it's a class?
if is instance obj type
begin
try
begin
set sig = signature call _get_constructor obj or obj
end
except tuple TypeError ValueError
begin
set sig = none
end
set skip_arg = 1
end
else
begin
try
be... | def from_callable(cls, obj: Callable) -> 'Signature':
namespace = None
arg_types = []
var_arg_type = None
if isinstance(obj, type): # it's a class?
try:
sig = inspect.signature(_get_constructor(obj) or obj)
except (TypeError, ValueErr... | Python | nomic_cornstack_python_v1 |
function test_group_roles configure_ldap_auth_mode group_name group_data
begin
try
begin
set username = credentials at group_name at string username
set password = credentials at group_name at string password
end
except KeyError
begin
call fail string No match in credentials file for group "%s" % group_name
end
call lo... | def test_group_roles(configure_ldap_auth_mode, group_name, group_data):
try:
username = credentials[group_name]['username']
password = credentials[group_name]['password']
except KeyError:
pytest.fail('No match in credentials file for group "%s"' % group_name)
login(username, passwor... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
set str = string Holberton School
print str * 3
print str at slice 0 : - 7 : | #!/usr/bin/python3
str = "Holberton School"
print(str * 3)
print(str[0:-7])
| Python | zaydzuhri_stack_edu_python |
function get_all_dataset_summaries
begin
return call DatasetSummariesResponse threat_exchange_datasets=call _get_threat_exchange_datasets datastore_table threat_exchange_data_bucket_name threat_exchange_data_folder
end function | def get_all_dataset_summaries() -> DatasetSummariesResponse:
return DatasetSummariesResponse(
threat_exchange_datasets=_get_threat_exchange_datasets(
datastore_table,
threat_exchange_data_bucket_name,
threat_exchange_data_folder,
)
... | Python | nomic_cornstack_python_v1 |
function convert_examples_to_features examples seq_length tokenizer
begin
set features = list
for tuple ex_index example in enumerate examples
begin
set tokens_a = call tokenize text_a
set tokens_b = none
if text_b
begin
set tokens_b = call tokenize text_b
end
if tokens_b
begin
comment Modifies `tokens_a` and `tokens_... | def convert_examples_to_features(examples, seq_length, tokenizer):
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens... | Python | nomic_cornstack_python_v1 |
string Numerical Analysis Created by: Fig Newtons A collection of algoritms useful for numerical analysis.
string Horner's Method: Evaluates a polynomial at value x. Algorithmic Complexity: O(n) (as compared to O(n^2) multiplications and O(n) additions) Given a list of coefficients [a_0, a_1, ..., a_n] and a value x fo... | '''
Numerical Analysis
Created by: Fig Newtons
A collection of algoritms useful for numerical analysis.
'''
'''
Horner's Method:
Evaluates a polynomial at value x.
Algorithmic Complexity: O(n) (as compared to O(n^2) multiplications and O(n) additions)
Given a list of coefficients [a_0, a_1, ..., a_n]
... | Python | zaydzuhri_stack_edu_python |
comment %%
import os
comment 讀取 label.csv
import pandas as pd
comment 讀取圖片
from PIL import Image
import numpy as np
import torch
comment Loss function
import torch.nn.functional as F
comment 讀取資料
import torchvision.datasets as datasets
from torch.utils.data import Dataset , DataLoader
comment 載入預訓練的模型
import torchvisio... | #%%
import os
# 讀取 label.csv
import pandas as pd
# 讀取圖片
from PIL import Image
import numpy as np
import torch
# Loss function
import torch.nn.functional as F
# 讀取資料
import torchvision.datasets as datasets
from torch.utils.data import Dataset, DataLoader
# 載入預訓練的模型
import torchvision.models as models
# 將資料轉換成符合預訓練模型的形式... | Python | zaydzuhri_stack_edu_python |
function login_view request
begin
set mensaje = string
if call is_authenticated
begin
return call HttpResponseRedirect string /
end
else
begin
if method == string POST
begin
set form = call LoginForm POST
if call is_valid
begin
set next = POST at string next
set username = cleaned_data at string Nombre
set password = ... | def login_view(request):
mensaje = ""
if request.user.is_authenticated():
return HttpResponseRedirect('/')
else:
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
next = request.POST['next']
username = form... | Python | nomic_cornstack_python_v1 |
set garums = input string Garums?
set platums = input string Platums?
set augstums = input string Augstums?
set garums = decimal garums
set platums = decimal platums
set augstums = decimal augstums
print string Telpas izmērs ir { garums * platums * augstums } m3 | garums = input("Garums?")
platums = input("Platums?")
augstums = input("Augstums?")
garums = float(garums)
platums = float(platums)
augstums = float(augstums)
print(f"Telpas izmērs ir {garums*platums*augstums} m3") | Python | zaydzuhri_stack_edu_python |
function longest_common_subsequence s1 s2
begin
comment Initialize the matrix
set table = list comprehension list comprehension 0 for x in range length s2 + 1 for y in range length s1 + 1
comment Fill the matrix
for i in range length s1
begin
for j in range length s2
begin
if s1 at i == s2 at j
begin
set table at i + 1... | def longest_common_subsequence(s1, s2):
#Initialize the matrix
table=[[0 for x in range(len(s2)+1)] for y in range(len(s1)+1)]
#Fill the matrix
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i]==s2[j]:
table[i+1][j+1]=table[i][j]+1
else:
... | Python | jtatman_500k |
comment encoding: utf-8
import xlrd
from xlutils.copy import copy
class ExcelDriver extends object
begin
comment 相比于old_getTargets,使用了with...as..语句来代替try...except语句
function read_file_1 self filename1
begin
set readfilename1 = filename1
end function
function read_file_2 self filename2
begin
set readfilename2 = filename... | # encoding: utf-8
import xlrd
from xlutils.copy import copy
class ExcelDriver(object):
#相比于old_getTargets,使用了with...as..语句来代替try...except语句
def read_file_1(self,filename1):
self.readfilename1 = filename1
def read_file_2(self, filename2):
self.readfilename2 = filename2
def write_in_f... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment 使用Scoop进行科学计算
comment scoop是一个可扩展的Python并行计算库,https://scoop.readthedocs.io/en/0.7/install.html
comment python –m scoop name_file_scoop.py
string import math from random import random from scoop import futures from time import time def evaluate_points_in_circle(attempts): points_fallen_in_u... | #coding: utf-8
# 使用Scoop进行科学计算
#scoop是一个可扩展的Python并行计算库,https://scoop.readthedocs.io/en/0.7/install.html
#python –m scoop name_file_scoop.py
'''
import math
from random import random
from scoop import futures
from time import time
def evaluate_points_in_circle(attempts):
points_fallen_in_unit_disk = 0
for i... | Python | zaydzuhri_stack_edu_python |
with open string data0.txt string r encoding=string utf8 as f
begin
set data0 = read lines f
end
with open string data0.txt string r encoding=string utf8 as f
begin
comment ligne=f.readline()
set k = 0
set texte = string
set ligne = string o
while ligne != string
begin
set k = k + 1
set ligne = read line f
set texte ... | with open('data0.txt','r',encoding='utf8') as f:
data0=f.readlines()
with open('data0.txt','r',encoding='utf8') as f:
#ligne=f.readline()
k=0
texte=''
ligne='o'
while ligne!='':
k+=1
ligne=f.readline()
texte+=ligne.strip('\n')
texte+=';'
if k==16:
... | Python | zaydzuhri_stack_edu_python |
function add_table self rows cols width
begin
string Return a table of *width* having *rows* rows and *cols* columns, newly appended to the content in this container. *width* is evenly distributed between the table columns.
from table import Table
set tbl = call new_tbl rows cols width
call _insert_tbl tbl
return call ... | def add_table(self, rows, cols, width):
"""
Return a table of *width* having *rows* rows and *cols* columns,
newly appended to the content in this container. *width* is evenly
distributed between the table columns.
"""
from .table import Table
tbl = CT_Tbl.new_tbl... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Spyder Editor Este é um arquivo de script temporário.
import math
import numpy as np
import copy
from movimento import Movimento
from variaveisGlobais import VariaveisGlobais
class Tabuleiro
begin
function __init__ self tabuleiroConfiguracao=TABULEIRO_INICIAL
begin
comment CASO O CO... | # -*- coding: utf-8 -*-
"""
Spyder Editor
Este é um arquivo de script temporário.
"""
import math
import numpy as np
import copy
from movimento import Movimento
from variaveisGlobais import VariaveisGlobais
class Tabuleiro:
def __init__ (self, tabuleiroConfiguracao = VariaveisGlobais.TABULEIRO_INICIAL):
... | Python | zaydzuhri_stack_edu_python |
comment Archivos [Python]
comment Ejemplos de clase
comment Autor: Inove Coding School
comment Version: 2.0
import csv
function read_csv
begin
comment Abrir un archivo CSV
set csvfile = open string edificio.csv
comment Leer todos los datos y almacenarlos en una
comment lista de diccionarios
set edificio = list dict rea... | # Archivos [Python]
# Ejemplos de clase
# Autor: Inove Coding School
# Version: 2.0
import csv
def read_csv():
# Abrir un archivo CSV
csvfile = open('edificio.csv')
# Leer todos los datos y almacenarlos en una
# lista de diccionarios
edificio = list(csv.DictReader(csvfile))
... | Python | zaydzuhri_stack_edu_python |
from lib.preprocessing import books as books
from lib.preprocessing import data_for_training as data
import pandas as pd
function build_popularity_based_recommendations
begin
string Build popularity-based recommendations through summing up the rating counts per ISBN
set tuple ratings_explicit ratings_implicit = call se... | from lib.preprocessing import books as books
from lib.preprocessing import data_for_training as data
import pandas as pd
def build_popularity_based_recommendations():
"""Build popularity-based recommendations through summing up the rating counts per ISBN"""
ratings_explicit, ratings_implicit = data.separate_e... | Python | zaydzuhri_stack_edu_python |
function preprocess_image self batched_inputs opt=string
begin
set images = to batched_inputs at string images device
comment images = batched_inputs
call div_ pixel_std
return images
end function | def preprocess_image(self, batched_inputs, opt = ''):
images = batched_inputs["images"].to(self.device)
# images = batched_inputs
images.sub_(self.pixel_mean).div_(self.pixel_std)
return images | Python | nomic_cornstack_python_v1 |
import repository
import mocrepository
class Service
begin
function __init__ self usersrep groupsrep
begin
set usersrep = usersrep
set groupsrep = groupsrep
end function
function find_the_most_popular_friends_group self user_id token
begin
set res = dictionary
set friends_ids = call getUserFriends user_id token
for fri... | import repository
import mocrepository
class Service:
def __init__(self, usersrep : repository.UsersRepository, groupsrep : repository.GroupsRepository):
self.usersrep = usersrep
self.groupsrep = groupsrep
def find_the_most_popular_friends_group(self, user_id, token):
res = dict()
... | Python | zaydzuhri_stack_edu_python |
function error bot update error
begin
warning string Update "%s" caused error "%s" update error
end function | def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"', update, error) | Python | nomic_cornstack_python_v1 |
function get_absolute_path *args
begin
set directory = directory name path absolute path path __file__
return join path directory *args
end function | def get_absolute_path(*args):
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, *args) | Python | nomic_cornstack_python_v1 |
import parser , usables , player
set directional_dict = dict string n string north ; string e string east ; string s string south ; string w string west ; string nw string northwest ; string ne string northeast ; string sw string southwest ; string se string southeast
class Map
begin
function __init__ self name vowel_s... | import parser, usables, player
directional_dict = {"n": "north", "e": "east", "s": "south", "w": "west",
'nw': "northwest", "ne": "northeast", "sw": "southwest",
"se": "southeast"}
class Map:
def __init__(self, name, vowel_sound=False):
self.name = name
self... | Python | zaydzuhri_stack_edu_python |
from random import random , randint , randrange
comment print(random())
comment print(randint(1, 2))
comment print(randrange(1, 10, 2))
from sys import argv
function ot *args **kwargs
begin
for el in args
begin
print string сотрудник { el }
set vr = random integer 0 160
set st = random integer 1000 2000
set pr = random... | from random import random, randint, randrange
#print(random())
#print(randint(1, 2))
#print(randrange(1, 10, 2))
from sys import argv
def ot(*args, **kwargs):
for el in args:
print(f"сотрудник {el}")
vr = randint(0, 160)
st = randint(1000, 2000)
pr = randint(0, 10000)
if vr... | Python | zaydzuhri_stack_edu_python |
function always_zero state maximizer_player_num
begin
return 0
end function | def always_zero(state, maximizer_player_num):
return 0 | Python | nomic_cornstack_python_v1 |
import pandas as pd
import plotly.express as px
import numpy as np
import csv
function getDataSource data_path
begin
set Sleep = list
set Coffee = list
with open data_path as csv_file
begin
set csv_reader = dict reader csv_file
for row in csv_reader
begin
append Sleep decimal row at string Coffee in ml
append Coffee ... | import pandas as pd
import plotly.express as px
import numpy as np
import csv
def getDataSource(data_path):
Sleep=[]
Coffee=[]
with open(data_path) as csv_file:
csv_reader=csv.DictReader(csv_file)
for row in csv_reader:
Sleep.append(float(row["Coffee in ml"]))
... | Python | zaydzuhri_stack_edu_python |
string Implement a full convolutional network decoding class Paper used for this is https://arxiv.org/pdf/1411.4038.pdf
import tensorflow as tf
import cnn_basenet
comment import vgg_encoder
class FCNDecoder extends CNNBaseModel
begin
string Implement a full convolutional decoding class
function __init__ self phase
begi... | """
Implement a full convolutional network decoding class
Paper used for this is https://arxiv.org/pdf/1411.4038.pdf
"""
import tensorflow as tf
import cnn_basenet
#import vgg_encoder
class FCNDecoder(cnn_basenet.CNNBaseModel):
"""
Implement a full convolutional decoding class
"""
def __init__(self, ... | Python | zaydzuhri_stack_edu_python |
function _escape self val
begin
return replace replace replace replace replace val string & string & string < string < string > string > string ' string ' string " string "
end function | def _escape(self, val):
return val.replace("&", "&"). \
replace("<", "<"). \
replace(">", ">"). \
replace("'", "'"). \
replace('"', """) | Python | nomic_cornstack_python_v1 |
from functools import reduce
set DEFAULT_INPUT = string day10.txt
function part_1 loc=DEFAULT_INPUT
begin
with open loc as f
begin
set input_list = list comprehension integer n for n in split read line f string ,
end
set number_list = list range 256
set current_pos = 0
set skip_size = 0
for num in input_list
begin
set ... | from functools import reduce
DEFAULT_INPUT = 'day10.txt'
def part_1(loc=DEFAULT_INPUT):
with open(loc) as f:
input_list = [int(n) for n in f.readline().split(',')]
number_list = list(range(256))
current_pos = 0
skip_size = 0
for num in input_list:
offset = current_pos - 0
n... | Python | zaydzuhri_stack_edu_python |
function read_ctrlpts_from_txt self filename=string two_dimensional=true size_u=0 size_v=0
begin
comment Clean up the surface and control points lists, if necessary
call _reset_ctrlpts
call _reset_surface
comment Initialize the return value
set ret_check = true
comment Try opening the file for reading
try
begin
with o... | def read_ctrlpts_from_txt(self, filename='', two_dimensional=True, size_u=0, size_v=0):
# Clean up the surface and control points lists, if necessary
self._reset_ctrlpts()
self._reset_surface()
# Initialize the return value
ret_check = True
# Try opening the file for re... | Python | nomic_cornstack_python_v1 |
function signWithSecret self secret
begin
call link secret
call sign
end function | def signWithSecret(self, secret):
self.link(secret)
self.sign() | Python | nomic_cornstack_python_v1 |
class Solution
begin
function singleNumber self nums
begin
string :type nums: List[int] :rtype: int
comment l = len(nums)
comment if l == 1:
comment return nums[0]
comment result = 0
comment for num in nums:
comment result ^= num
comment return result
return 2 * sum set nums - sum nums
end function
end class | class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# l = len(nums)
# if l == 1:
# return nums[0]
# result = 0
# for num in nums:
# result ^= num
# return result
return 2 * s... | 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.