code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
comment a2 + b2 = c2
comment For example, 32 + 42 = 9 + 16 = 25 = 52.
comment There exists exactly one Pythagorean triplet for which a + b + c = 1000.
comment Find the product abc.
import time
set t0 = time
set maxi = 999
set found =... | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import time
t0 = time.time()
maxi = 999
found = 0
for a in range(1, maxi / 2):
... | Python | zaydzuhri_stack_edu_python |
function initializeProfile self path settings
begin
pass
end function | def initializeProfile(self, path, settings):
pass | Python | nomic_cornstack_python_v1 |
function test_14_file_content_types_unpublished self
begin
print __doc__
set kwargs = dictionary start_date=string 2015-11-01 end_date=string 2016-03-01
set stats_maker = call StatsMakerFiles keyword kwargs
set r = call get_datafile_content_type_counts_unpublished
comment check number of entries
assert equal length res... | def test_14_file_content_types_unpublished(self):
print (self.test_14_file_content_types_unpublished.__doc__)
kwargs = dict(start_date='2015-11-01',
end_date='2016-03-01')
stats_maker = StatsMakerFiles(**kwargs)
r = stats_maker.get_datafile_content_type_counts_unpubl... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Nov 29 2018 @author: PixelNew
while true
begin
print string I'm true! And I'm an infinite loop too, ha ha ha ha.....
end | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 29 2018
@author: PixelNew
"""
while True:
print("I'm true! And I'm an infinite loop too, ha ha ha ha.....\n")
| Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from matplotlib import pyplot as plt
set img = call imread string Train/Yellow/yellow1462.jpg
set hsv = call cvtColor img COLOR_BGR2HSV
comment rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
set hue_hist = call calcHist list hsv list 0 none list 180 list 0 180
set sat_hist = call calcHist list... | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("Train/Yellow/yellow1462.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
hue_hist = cv2.calcHist([hsv],[0],None,[180],[0,180])
sat_hist = cv2.calcHist([hsv],[1],None,[256],[0,256])
val_his... | Python | zaydzuhri_stack_edu_python |
function display_trending
begin
set df_trending = call get_trending
call print_rich_table df_trending headers=list columns show_index=false title=string Trending Stocks
end function | def display_trending():
df_trending = stocktwits_model.get_trending()
print_rich_table(
df_trending,
headers=list(df_trending.columns),
show_index=False,
title="Trending Stocks",
) | Python | nomic_cornstack_python_v1 |
comment (c) Tivole
comment Constanst
comment Your ID number on group list
set NUMBER_ON_TABLE = 7
comment How many number you want to take
set N = 100
comment Importing the libraries
import pandas as pd
import numpy as np
comment Importing dataset
set dataset = read csv string Random_Numbers.csv
set Y = values
sort Y
c... | # (c) Tivole
# Constanst
NUMBER_ON_TABLE = 7 # Your ID number on group list
N = 100 # How many number you want to take
# Importing the libraries
import pandas as pd
import numpy as np
# Importing dataset
dataset = pd.read_csv('Random_Numbers.csv')
Y = dataset.iloc[:N, NUMBER_ON_TABLE - 1].values
Y.sort()
# Distribu... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
class TwoLayerNet extends Module
begin
function __init__ self input_dim hidden_size num_classes
begin
string :param input_dim: input feature dimension :param hidden_size: hidden dimension :param num_classes: total number of classes
call __init__
set fc1 = linear input_dim hidden_size
... | import torch
import torch.nn as nn
class TwoLayerNet(nn.Module):
def __init__(self, input_dim, hidden_size, num_classes):
'''
:param input_dim: input feature dimension
:param hidden_size: hidden dimension
:param num_classes: total number of classes
'''
super(TwoLayer... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.image as mpimg
import numpy as np
set img = call imread string map.jpg
image show img extent=list 0 100 0 100
comment position dic
set pos = values
print pos
comment io dic
set io = values
set dic1 = dict
set dic2 = dict
for i in range length pos
b... | import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.image as mpimg
import numpy as np
img=mpimg.imread('map.jpg')
plt.imshow(img, extent=[0,100,0,100])
#position dic
pos = pd.read_csv('key points.csv')[['x', 'y']].values
print(pos)
#io dic
io = pd.read_csv('Random Forest.csv').values
dic1 = {}
d... | Python | zaydzuhri_stack_edu_python |
function test_name_for_guid_if_no_id self
begin
assert parse self dict string name string addon-name at string guid is none
end function | def test_name_for_guid_if_no_id(self):
assert self.parse({'name': 'addon-name'})['guid'] is None | Python | nomic_cornstack_python_v1 |
function plot_confusion_matrix cm class_names figsize=tuple 16 16 fontsize=12 normalize=false title=string Confusion matrix cmap=none fname=none show_scores=true noshow=false backend=string Agg format_string=none
begin
import matplotlib
call use backend
import matplotlib.pyplot as plt
if cmap is none
begin
set cmap = O... | def plot_confusion_matrix(
cm: np.ndarray,
class_names: List[str],
figsize: Tuple[int, int] = (16, 16),
fontsize: int = 12,
normalize: bool = False,
title: str = "Confusion matrix",
cmap=None,
fname=None,
show_scores: bool = True,
noshow: bool = False,
backend: str = "Agg",
... | Python | nomic_cornstack_python_v1 |
function _header_transformer self lines
begin
set needle = b'--%s\n' % boundary
set in_header = false
for line in lines
begin
if line == needle
begin
set in_header = true
end
if in_header
begin
assert line at - 1 == b'\n'
set line = line at slice : - 1 : + b'\r\n'
end
if line == b'\r\n'
begin
set in_header = false
en... | def _header_transformer(self, lines):
needle = b'--%s\n' % self.boundary
in_header = False
for line in lines:
if line == needle:
in_header = True
if in_header:
assert line[-1] == b'\n'
line = line[:-1] + b'\r\n'
... | Python | nomic_cornstack_python_v1 |
import openpyxl
set book = call load_workbook string F:\Raman\Work\Framework\PythonSeleniumFramework\ExcelFiles\data.xlsx
set sheet = active
comment sheet.cell(row=2, column=2).value = "Rahul"
comment print(sheet.cell(row=1, column=1).value)
comment print(sheet.max_row)
comment print(sheet.max_column)
comment print(she... | import openpyxl
book = openpyxl.load_workbook("F:\Raman\Work\Framework\PythonSeleniumFramework\ExcelFiles\data.xlsx")
sheet = book.active
# sheet.cell(row=2, column=2).value = "Rahul"
# print(sheet.cell(row=1, column=1).value)
#
# print(sheet.max_row)
#
# print(sheet.max_column)
#
# print(sheet['A5'].value)
Dict = {}
... | Python | zaydzuhri_stack_edu_python |
function SetStoreType self storeType
begin
set callResult = call _Call string SetStoreType storeType
end function | def SetStoreType(self, storeType):
callResult = self._Call("SetStoreType", storeType) | Python | nomic_cornstack_python_v1 |
import folium
import pandas
import io
set data = read csv string Volcanoes.txt
set lat = list data at string LAT
set lon = list data at string LON
set elev = list data at string ELEV
set data_json = read open string world.json string r encoding=string utf-8-sig
set html = string <h4>Volcano information:</h4> Height: %s... | import folium
import pandas
import io
data=pandas.read_csv("Volcanoes.txt")
lat=list(data["LAT"])
lon=list(data["LON"])
elev=list(data["ELEV"])
data_json = io.open("world.json",'r',encoding='utf-8-sig').read()
html = """<h4>Volcano information:</h4>
Height: %s m
"""
def color_producer(elevation):
if elevation<1000... | Python | zaydzuhri_stack_edu_python |
function getChildren self
begin
if not Children
begin
comment print 'reached leave node {0}'.format(self.CommID)
comment raw_input()
return list list list
end
set children = deque
set parent = deque
for c in range length Children
begin
append children Children at c
append parent CommID
end
set retval = tuple children... | def getChildren(self):
if not self.Children:
#print 'reached leave node {0}'.format(self.CommID)
#raw_input()
return [[], []]
children = deque()
parent = deque()
for c in range(len(self.Children)):
children.append(self.Children[c])
... | Python | nomic_cornstack_python_v1 |
comment Given a non-empty array of integers, find the top k elements which have the highest frequency in the array.
comment If two numbers have the same frequency then the larger number should be given preference.
comment Examples:
comment Input:
comment nums = {1,1,1,2,2,3},
comment k = 2
comment Output: {1, 2}
commen... | # Given a non-empty array of integers, find the top k elements which have the highest frequency in the array.
# If two numbers have the same frequency then the larger number should be given preference.
# Examples:
# Input:
# nums = {1,1,1,2,2,3},
# k = 2
# Output: {1, 2}
# Input:
# nums = {1,1,2,2,3,3,3,4},
# k = ... | Python | zaydzuhri_stack_edu_python |
string O programa recebe dois valores x e y. Imprime como eles foram inseridos e, depois, troca x por y.
set x = input string Digite o valor de x:
set y = input string E agora o valor de y:
set a = y
set b = x
print string Inicialmente x recebeu { x } e y recebeu { y }
print string Após a substituição, x é igual a { a ... | " O programa recebe dois valores x e y. Imprime como eles foram inseridos e, depois, troca x por y."
x = input('Digite o valor de x:\n')
y = input('E agora o valor de y:\n')
a = y;
b = x;
print(f'Inicialmente x recebeu {x} e y recebeu {y}')
print(f'Após a substituição,\nx é igual a {a} e y é igual a {b}') | Python | zaydzuhri_stack_edu_python |
function czd_csvs_to_dict input_path
begin
set output_dict = dict
set possible_dir_names = list string zircon_dimensions string grain_dimensions
set toplevel_dirs = list comprehension f for f in call scandir input_path if call is_dir and name in possible_dir_names
set grain_zircon_str = name
set dimensions_files = lis... | def czd_csvs_to_dict(input_path):
output_dict = {}
possible_dir_names = ['zircon_dimensions', 'grain_dimensions']
toplevel_dirs = [f for f in os.scandir(input_path)
if f.is_dir() and f.name in possible_dir_names]
grain_zircon_str = toplevel_dirs[0].name
dimensions_files = [f for... | Python | nomic_cornstack_python_v1 |
class Stack
begin
class Node
begin
function __init__ self
begin
set __data = none
end function
function input self data
begin
set __data = data
end function
function output self
begin
return __data
end function
end class
function __init__ self
begin
set stack = list
end function
function push self data
begin
if count ... | class Stack():
class Node():
def __init__(self):
self.__data = None
def input(self,data):
self.__data = data
def output(self):
return self.__data
def __init__(self):
self.stack = []
def push(self, data):
if (self.count()<4):
... | Python | zaydzuhri_stack_edu_python |
comment WITH RETURN
set tuple a b = tuple 1 2
print a b
function get_data
begin
set a = 10
set b = 20
print a b
return tuple a b
end function
set tuple a b = call get_data
print a b | #WITH RETURN
a,b=1,2
print(a,b)
def get_data():
a=10
b=20
print(a,b)
return a,b
a,b=get_data()
print(a,b)
| Python | zaydzuhri_stack_edu_python |
function BubbleSort a
begin
set length = length a
for i in range length
begin
for j in range 0 length - i - 1
begin
if a at j > a at j + 1
begin
set tmp = a at j
set a at j = a at j + 1
set a at j + 1 = tmp
end
end
end
return a
end function
function insertSort a
begin
set length = length a
set sorted_a = list
append s... | def BubbleSort(a):
length = len(a)
for i in range(length):
for j in range(0 , length - i - 1):
if a[j] > a[j + 1]:
tmp = a[j]
a[j] = a[j + 1]
a[j + 1] = tmp
return a
def insertSort(a):
length = len(a)
sorted_a = []
sorted_a.append(a[0])
for i in range(1,length):
new_in = a[i]
sub_len = len(... | Python | zaydzuhri_stack_edu_python |
comment importing tkinter
from tkinter import *
set root = call Tk
title root string Calculator
comment gave background color black
call configure bg=string #222
comment to make the gui window not resizable
call resizable false false
comment defined a global variable 'operator'
set operator = string
comment function f... | # importing tkinter
from tkinter import*
root = Tk()
root.title("Calculator")
# gave background color black
root.configure(bg='#222')
# to make the gui window not resizable
root.resizable(False,False)
# defined a global variable 'operator'
operator = ""
# function for displaying number when button is clicked
def ... | Python | zaydzuhri_stack_edu_python |
import re
comment open the original file
with open string original\_file.txt string r as file
begin
comment read the contents of the file
set contents = read file
comment use regex to split the contents by the delimiters
set sections = find all string BEGIN\n(.\*?)\nEND contents DOTALL
end
comment save each section in ... | import re
# open the original file
with open('original\_file.txt', 'r') as file:
# read the contents of the file
contents = file.read()
# use regex to split the contents by the delimiters
sections = re.findall(r'BEGIN\n(.\*?)\nEND', contents, re.DOTALL)
# save each section in a separate file | Python | flytech_python_25k |
comment Copyright (c) 2009-2012 Simon Kennedy <code@sffjunkie.co.uk>.
comment Licensed under the Apache License, Version 2.0 (the "License");
comment you may not use this file except in compliance with the License.
comment You may obtain a copy of the License at
comment http://www.apache.org/licenses/LICENSE-2.0
commen... | # Copyright (c) 2009-2012 Simon Kennedy <code@sffjunkie.co.uk>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | Python | zaydzuhri_stack_edu_python |
import math
import tensorflow as tf
import numpy as np
set HIDDEN_NODES_1 = 4
set HIDDEN_NODES_2 = 4
set x_input = call placeholder float32 shape=list none 2 name=string x-input
set y_input = call placeholder float32 shape=list none 1 name=string y-input
set W_hidden_1 = call Variable call truncated_normal list 2 HIDDE... | import math
import tensorflow as tf
import numpy as np
HIDDEN_NODES_1 = 4
HIDDEN_NODES_2 = 4
x_input = tf.placeholder(tf.float32,shape=[None,2],name="x-input")
y_input = tf.placeholder(tf.float32,shape=[None,1],name="y-input")
W_hidden_1 = tf.Variable(tf.truncated_normal([2,HIDDEN_NODES_1],stddev=1./math.sqrt(2)))
b... | Python | zaydzuhri_stack_edu_python |
comment >>>>> Files & Directories <<<<<
from pathlib import Path
comment Two types of paths
comment 1 Absolute Path - path of any file/directory in our hard disk
comment 2 Relative Path - path inside project's root folder
set path1 = call Path string email
if exists path1
begin
remove directory
end
else
begin
make dire... | # >>>>> Files & Directories <<<<<
from pathlib import Path
##
# Two types of paths
# 1 Absolute Path - path of any file/directory in our hard disk
# 2 Relative Path - path inside project's root folder
##
path1 = Path('email')
if path1.exists():
path1.rmdir()
else:
path1.mkdir()
path2 = Path() # Without any... | Python | zaydzuhri_stack_edu_python |
function join self new_channel nick pwd=none
begin
string Joins a new channel. Keyword arguments: new_channel: <str>; the channel to connect to nick: <str>; the nickname to use pwd: <str>; the (optional) password to use
call _send_packet dict string cmd string join ; string channel new_channel ; string nick call _forma... | def join(self, new_channel, nick, pwd=None):
"""Joins a new channel.
Keyword arguments:
new_channel: <str>; the channel to connect to
nick: <str>; the nickname to use
pwd: <str>; the (optional) password to use
"""
self._send_packet({"cmd": "join", "channel": new_... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Mon Dec 28 13:37:46 2020 @author: WickhamLee
import numpy as np
comment import time
import pandas as pd
comment -----------------------
comment dataframe_date_standard0
comment -----------------------
comment df_dictionary的index中有的日期,但df_input没有的话,在df_input以np.nan补充一行
fun... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 28 13:37:46 2020
@author: WickhamLee
"""
import numpy as np
# import time
import pandas as pd
#-----------------------
#dataframe_date_standard0
#-----------------------
#df_dictionary的index中有的日期,但df_input没有的话,在df_input以np.nan补充一行
def dataframe_date_standard0(df_input, df... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense , Conv2D , Flatten , MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
comment Specify image dimensions
set tuple img_width i... | import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
# Specify image dimensions
img_width, img_height = 15... | Python | jtatman_500k |
comment Дан словарь с балансом пользователей, пример:
comment balance = { 'user1': 100, 'user2': 500 }
comment В примере у user1 - 100 "денег", у user2 - 500.
comment Так же дан список transactions состоящий из словарей, каждый из которых транзакция.
comment Ключ транзакции - имя пользователя,
comment значение - количе... | # Дан словарь с балансом пользователей, пример:
# balance = { 'user1': 100, 'user2': 500 }
# В примере у user1 - 100 "денег", у user2 - 500.
# Так же дан список transactions состоящий из словарей, каждый из которых транзакция.
# Ключ транзакции - имя пользователя,
# значение - количество "денег". Положительное значение... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function partition self s
begin
set result = list
set path = list
comment 判断是否是回文串
function pending_s s
begin
set tuple l r = tuple 0 length s - 1
while l < r
begin
if s at l != s at r
begin
return false
end
set l = l + 1
set r = r - 1
end
return true
end function
comment 回溯函数,这里的index作为遍历到的索引位置,... | class Solution:
def partition(self, s: str) -> List[List[str]]:
result = []
path = []
# 判断是否是回文串
def pending_s(s):
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= ... | Python | zaydzuhri_stack_edu_python |
function test_post_with_unknown_cert self
begin
class Certificate extends object
begin
set failures = list string failures
set fingerprint = string fingerprint
set hostname = string example.com
set issuer = string issuer
set valid_from = string valid_from
set valid_until = string valid_until
end class
set cert = call C... | def test_post_with_unknown_cert(self):
class Certificate(object):
failures = ['failures']
fingerprint = 'fingerprint'
hostname = 'example.com'
issuer = 'issuer'
valid_from = 'valid_from'
valid_until = 'valid_until'
cert = Certifica... | Python | nomic_cornstack_python_v1 |
comment This is a header block example for lab 1.
comment You will need to supply the following information.
comment Name: Sydney
comment Instructor: Julie Workman
comment Section:05
print string Hello, Sydney. | # This is a header block example for lab 1.
#
# You will need to supply the following information.
#
# Name: Sydney
# Instructor: Julie Workman
# Section:05
#
print ("Hello, Sydney.")
| Python | zaydzuhri_stack_edu_python |
function plot_stations_map ax stns noText=false
begin
comment determine range to print based on min, max lat and lon of the data
set lat = list stns at string latitude
set lon = list stns at string longitude
set siz = list comprehension 2 ^ x / 1000 for x in stns at string flow_count
comment buffer to add to the range
... | def plot_stations_map(ax, stns, noText=False):
# determine range to print based on min, max lat and lon of the data
lat = list(stns['latitude'])
lon = list(stns['longitude'])
siz = [(2) ** (x / 1000) for x in stns['flow_count']]
margin = 0.01 # buffer to add to the range
lat_min = min(lat) - ma... | Python | zaydzuhri_stack_edu_python |
function update self instance validated_data
begin
set password = pop validated_data string password none
set profile_data = pop validated_data string profile dict
print string Pop profile profile_data
print string Pop password password
for tuple key value in items validated_data
begin
comment For the keys remaining in... | def update(self, instance, validated_data):
password = validated_data.pop('password', None)
profile_data = validated_data.pop('profile', {})
print("Pop profile",profile_data)
print("Pop password",password)
for (key, value) in validated_data.items():
# For the keys ... | Python | nomic_cornstack_python_v1 |
function on_turn self turn_state
begin
set game_state = call GameState config turn_state
comment gamelib.debug_write('Performing turn {} of your custom algo strategy'.format(game_state.turn_number))
comment game_state.suppress_warnings(True) #Uncomment this line to suppress warnings.
call starter_strategy game_state
ca... | def on_turn(self, turn_state):
game_state = gamelib.GameState(self.config, turn_state)
#gamelib.debug_write('Performing turn {} of your custom algo strategy'.format(game_state.turn_number))
#game_state.suppress_warnings(True) #Uncomment this line to suppress warnings.
self.starter_stra... | Python | nomic_cornstack_python_v1 |
function test_unknown_resource self
begin
with assert raises SystemExit
begin
set tuple args config = call parse_args split shlex format string notes search --resource xxx "something" --config-path {} config_fn
end
end function | def test_unknown_resource(self):
with self.assertRaises(SystemExit):
args, config = parse_args(shlex.split(
'notes search --resource xxx "something" --config-path {}'.format(self.config_fn)
)) | Python | nomic_cornstack_python_v1 |
function extract_javadoc modified_file_repo_dict verbose=1
begin
set return_dict = dict
if verbose > 0
begin
set num_modified_file_repo = length modified_file_repo_dict
end
for tuple idx_commit_hash commit_hash in enumerate keys modified_file_repo_dict
begin
comment for commit_hash in ['00a01dca6babded748869eb67133f66... | def extract_javadoc(modified_file_repo_dict, verbose=1):
return_dict = {}
if verbose>0:
num_modified_file_repo = len(modified_file_repo_dict)
for idx_commit_hash, commit_hash in enumerate(modified_file_repo_dict.keys()):
#for commit_hash in ['00a01dca6babded748869eb67133f66262a02013']:
... | Python | nomic_cornstack_python_v1 |
import hashlib
comment print(hashlib.algorithms_available)
comment print(hashlib.algorithms_guaranteed)
function md5_generator path
begin
with open path encoding=string utf-8 as file
begin
for line in file
begin
set line = strip line
set md5 = hex digest md5 encode line string utf-8
yield md5
end
end
end function
if __... | import hashlib
#print(hashlib.algorithms_available)
#print(hashlib.algorithms_guaranteed)
def md5_generator(path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
md5 = hashlib.md5(line.encode('utf-8')).hexdigest()
yield md5
if __name_... | Python | zaydzuhri_stack_edu_python |
function _strip_comments file_contents
begin
set lines_without_comments = list
for line in file_contents
begin
set comment_position = find line COMMENT_INDICATOR
if comment_position != - 1
begin
append lines_without_comments line at slice : comment_position :
end
else
begin
append lines_without_comments line
end
end
... | def _strip_comments(file_contents):
lines_without_comments = []
for line in file_contents:
comment_position = line.find(COMMENT_INDICATOR)
if comment_position != -1:
lines_without_comments.append(line[:comment_position])
else:
lines_without_comments.append(line)
... | Python | nomic_cornstack_python_v1 |
async function _do_request cls url headers=none account=none **request_args
begin
if headers is none
begin
set headers = if expression account is none then none else call _generate_auth_header
end
else
begin
raise call HekrValueError string headers expected=tuple string headers dict none got=headers
end
async_with call... | async def _do_request(cls, url: str, headers: Optional[Dict[str, str]] = None,
account: Optional['Account'] = None, **request_args):
if headers is None:
headers = None if account is None else account._generate_auth_header()
else:
raise HekrValueError('he... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import pandas as pd
import os
set MAP_FOLDER = string C://Users//piepalla//vodafone//files//
class Mapping
begin
function __init__ self
begin
set map1_path = join path MAP_FOLDER string 1.csv
set map2_path = join path MAP_FOLDER string 2.csv
set map3_path = join path MAP_FOLDER string 3.cs... | # -*- coding: utf-8 -*-
import pandas as pd
import os
MAP_FOLDER = "C://Users//piepalla//vodafone//files//"
class Mapping:
def __init__(self):
self.map1_path = os.path.join(MAP_FOLDER, "1.csv")
self.map2_path = os.path.join(MAP_FOLDER, "2.csv")
self.map3_path = os.path.join(MAP_FOLDER,... | Python | zaydzuhri_stack_edu_python |
function process_get_blockchain_score status json network_type
begin
assert status == 200
return call create_from_dto json network_type
end function | def process_get_blockchain_score(
status: int,
json: dict,
network_type: models.NetworkType,
) -> models.BlockchainScore:
assert status == 200
return models.BlockchainScore.create_from_dto(json, network_type) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment @Time : 2020/5/31 16:30
comment @Author : WH Python学的好,牢饭吃的饱。
comment @FileName: data01.py
comment @Email : oukouwh@163.com
comment @Software: PyCharm
string 单链表的构建和功能操作
comment 创建节点
class Node
begin
function __init__ self value next=none
begin
set value =... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/5/31 16:30
# @Author : WH Python学的好,牢饭吃的饱。
# @FileName: data01.py
# @Email : oukouwh@163.com
# @Software: PyCharm
'''
单链表的构建和功能操作
'''
# 创建节点
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class L... | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
set tuple h w n = map int split input
set count = n // h + 1
set floor = n % h
if floor == 0
begin
set count = count - 1
set floor = h
end
set p = string floor
if count < 10
begin
set p = p + string 0
end
set p = p + string count
print p
end | for i in range(n):
h,w,n = map(int,input().split())
count = n//h+1
floor = n%h
if(floor ==0):
count-=1
floor =h
p = str(floor)
if(count<10):
p+='0'
p+=str(count)
print(p) | Python | zaydzuhri_stack_edu_python |
function millerRabin n k
begin
if n < 2
begin
return false
end
if n % 2 == 0
begin
return false
end
set s = 0
set d = n - 1
while d % 2 == 0
begin
set s = s + 1
set d = d ? 1
end
for i in range k
begin
set rand = random integer 2 n - 2
set x = call powmod rand d n
if x == 1 or x == n - 1
begin
continue
end
for r in ran... | def millerRabin(n, k):
if n<2:
return False
if n%2==0:
return False
s = 0
d = n-1
while d%2==0:
s += 1
d >>= 1
for i in range(k):
rand = randint(2, n-2)
x = powmod(rand, d, n)
if x == 1 or x == n-1:
continue
for r in range(s):
isPrime = True
x =powmod(x,2,n)
if x==1:
return False... | Python | zaydzuhri_stack_edu_python |
function es_vocal letra
begin
return lower letra in list string a string e string i string o string u string A string E string I string O string U string á string é string í string ó string ú string Á string É string Í string Ó string Ú
end function
set letra = input string Introduce una letra por favor:
if call es_voc... | def es_vocal(letra):
return letra.lower() in ['a','e','i','o','u','A','E','I','O','U','á','é','í','ó','ú','Á','É','Í','Ó','Ú']
letra = input('Introduce una letra por favor: ')
if es_vocal(letra):
print(True)
else:
print(False) | Python | zaydzuhri_stack_edu_python |
set price = integer input string 料金を入力:
set number = integer input string 人数を入力:
set payment = integer price / number
print format string お支払いは{}円です payment | price=int(input('料金を入力:'))
number=int(input('人数を入力:'))
payment=int(price/number)
print('お支払いは{}円です'.format(payment))
| Python | zaydzuhri_stack_edu_python |
string name="Rajat" length=len(name) i=0 for n in range(-1,(-length-1),-1): print (name[i])," ",name[n] i+=1
comment for each loop
string for i in range(10, 0, -1): print (i)
set a = string ratan
set b = string jaiswal
set c = a + b
print c | '''name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print (name[i]),"\t",name[n]
i+=1'''
#for each loop
'''for i in range(10, 0, -1):
print (i)'''
a= "ratan"
b= "jaiswal"
c = a + b
print (c)
| Python | zaydzuhri_stack_edu_python |
string Voorbeelden gebruik van CBS Open Data v3 in Python https://www.cbs.nl/nl-nl/onze-diensten/open-data Auteur: Jolien Oomens Centraal Bureau voor de Statistiek In dit voorbeeld worden gemeentegrenzen gekoppeld aan geboortecijfers om een thematische kaart te maken.
import pandas as pd
import geopandas as gpd
import ... | """
Voorbeelden gebruik van CBS Open Data v3 in Python
https://www.cbs.nl/nl-nl/onze-diensten/open-data
Auteur: Jolien Oomens
Centraal Bureau voor de Statistiek
In dit voorbeeld worden gemeentegrenzen gekoppeld aan geboortecijfers om een
thematische kaart te maken.
"""
import pandas as pd
import geopandas as gpd
imp... | Python | zaydzuhri_stack_edu_python |
comment Poker hands
comment In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
comment High Card: Highest value card.
comment One Pair: Two cards of the same value.
comment Two Pairs: Two different pairs.
comment Three of a Kind: Three cards of the same v... | #Poker hands
#In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
#High Card: Highest value card.
#One Pair: Two cards of the same value.
#Two Pairs: Two different pairs.
#Three of a Kind: Three cards of the same value.
#Straight: All cards are consecuti... | Python | zaydzuhri_stack_edu_python |
function init
begin
print string This is a simple calculator, enter an equation and it'll be calculated, you can also perform operations on the number stored in memory
return 0
end function
function inputHandling
begin
set calcInput = input string Enter a calculation:
set calcInput = replace calcInput string string
if... | def init():
print("This is a simple calculator, enter an equation and it'll be calculated, you can also perform operations on "
"the number stored in memory")
return 0
def inputHandling():
calcInput = input("Enter a calculation: ")
calcInput = calcInput.replace(" ", "")
if ifExi... | Python | zaydzuhri_stack_edu_python |
function test_add_scaling_policy_at self mock_serial
begin
set returns = list list dict string count 0 none
set expected_at = string 2012-10-20T03:23:45
set pol = dict string cooldown 5 ; string type string schedule ; string name string scale up by 10 ; string change 10 ; string args dict string at expected_at
set d = ... | def test_add_scaling_policy_at(self, mock_serial):
self.returns = [[{'count': 0}], None]
expected_at = '2012-10-20T03:23:45'
pol = {'cooldown': 5,
'type': 'schedule',
'name': 'scale up by 10',
'change': 10,
'args': {'at': expected_at}}
... | Python | nomic_cornstack_python_v1 |
if 10.0 <= budget <= 100.0
begin
if sesason == string summer
begin
set spend = 0.3 * budget
print string Somewhere in Bulgaria
print string Camp - + string string %.2f % spend
end
else
if sesason == string winter
begin
set spend = 0.7 * budget
print string Somewhere in Bulgaria
print string Hotel - + string string %.2f... | if 10.00 <= budget <= 100.00:
if sesason == 'summer':
spend = 0.30 * budget
print('Somewhere in Bulgaria')
print('Camp - ' + str('%.2f' % spend))
elif sesason == 'winter':
spend = 0.70 * budget
print('Somewhere in Bulgaria')
print('Hotel - ' + str('%.2f' % spend))... | Python | zaydzuhri_stack_edu_python |
function test_types self
begin
call validate 1
for cls in tuple float str
begin
with assert raises TypeError
begin
call validate call cls 1
end
end
end function | def test_types(self):
values.Integer.validate(1)
for cls in (float, str):
with self.assertRaises(TypeError):
values.Integer.validate(cls(1)) | Python | nomic_cornstack_python_v1 |
function get_dico module
begin
from config import CFGS
if CFGS is none
begin
raise call TelemacException string This function only wors if a configuration is set
end
return join path call get_root string sources module module + string .dico
end function | def get_dico(module):
from config import CFGS
if CFGS is None:
raise TelemacException(\
"This function only wors if a configuration is set")
return path.join(CFGS.get_root(), 'sources', module, module+'.dico') | Python | nomic_cornstack_python_v1 |
function configure_dynamic_nat_route_map_rule device route_map_name pool_name
begin
set cmd = list format string ip nat inside source route-map {} pool {} route_map_name pool_name
try
begin
call configure cmd
end
except SubCommandFailure as e
begin
error e
raise call SubCommandFailure string Could not Configure dynamic... | def configure_dynamic_nat_route_map_rule(
device,
route_map_name,
pool_name
):
cmd = ["ip nat inside source route-map {} pool {}".format(
route_map_name,pool_name)]
try:
device.configure(cmd)
except SubCommandFailure as e:
log.error(e)
raise SubCommandFailu... | Python | nomic_cornstack_python_v1 |
function close_db error
begin
if has attribute g string sqlite_db
begin
close sqlite_db
end
end function | def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close() | Python | nomic_cornstack_python_v1 |
decorator call route string /users methods=list string GET
function get_users
begin
set users = all
return call jsonify list comprehension dict string Id id ; string Name name ; string Email email ; string Gender gender for user in users
end function | @app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'Id': user.id, 'Name': user.name, 'Email': user.email, 'Gender': user.gender} for user in users]) | Python | iamtarun_python_18k_alpaca |
import os
import numpy as np
import random
from datetime import datetime , timedelta
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mtp
import queue
function gen_datetime min_year=2000 max_year=year
begin
comment generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
set start = call datetim... | import os
import numpy as np
import random
from datetime import datetime, timedelta
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mtp
import queue
def gen_datetime(min_year=2000, max_year=datetime.now().year):
# generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
start ... | Python | zaydzuhri_stack_edu_python |
import json
function make_caipirinha sweetness_level
begin
comment Load the sweetness level from the JSON data
set sweetness_data = loads sweetness_level
set sweetness_level = sweetness_data at string sweetness_level
comment Calculate the amount of sugar based on the sweetness level
set sugar = sweetness_level / 10 * 2... | import json
def make_caipirinha(sweetness_level):
# Load the sweetness level from the JSON data
sweetness_data = json.loads(sweetness_level)
sweetness_level = sweetness_data["sweetness_level"]
# Calculate the amount of sugar based on the sweetness level
sugar = (sweetness_level / 10) * 2
# Print the recipe wi... | Python | jtatman_500k |
function walk self
begin
if exists path folder
begin
for tuple root_path _ f_files in walk folder
begin
yield tuple root_path f_files
if not recursive
begin
break
end
end
end
else
begin
print string [!e] Passed folder doesn't exist. Path: { folder } file=stdout
exit 0
end
end function | def walk(self):
if os.path.exists(self.folder):
for root_path, _, f_files in os.walk(self.folder):
yield root_path, f_files
if not self.recursive:
break
else:
print(f"[!e] Passed folder doesn't exist. Path: {self.folder}",
... | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
comment class ListNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution extends object
begin
function reorderList self head
begin
string :type head: ListNode :rtype: void Do not return anything, modify head in-place instead.
... | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from itertools import product
import matplotlib.pyplot as plt
import tensorflow as tf
function show_kernel kernel label=true digits=none text_size=28
begin
comment Format kernel
set kernel = array kernel
if digits is not none
begin
set kernel = round digits
end
comment Plot kernel
set cmap = call get... | import numpy as np
from itertools import product
import matplotlib.pyplot as plt
import tensorflow as tf
def show_kernel(kernel, label=True, digits=None, text_size=28):
# Format kernel
kernel = np.array(kernel)
if digits is not None:
kernel = kernel.round(digits)
# Plot kernel
cmap = plt.g... | Python | zaydzuhri_stack_edu_python |
string Program 7.1 Dynamically Build User Input as a List
function main
begin
print string Method 1: Building Dictionaries
set build_dictionary = dict
for i in range 0 2
begin
set dic_key = input string Enter key
set dic_val = input string Enter val
update build_dictionary dict dic_key dic_val
end
print string Diction... | """
Program 7.1
Dynamically Build User Input as a List
"""
def main():
print("Method 1: Building Dictionaries")
build_dictionary = {}
for i in range(0, 2):
dic_key = input("Enter key\n")
dic_val = input("Enter val\n")
build_dictionary.update({dic_key: dic_val})
print(f"Dictiona... | Python | zaydzuhri_stack_edu_python |
function transfer S T
begin
if call is_empty
begin
raise call Empty string Empty Stack
end
comment for i in range(len(S)):
comment T.push(S.pop())
comment OR :
while not call is_empty
begin
call push pop S
end
return tuple S T
end function | def transfer(S, T):
if S.is_empty():
raise Empty('Empty Stack')
# for i in range(len(S)):
# T.push(S.pop())
# OR :
while not S.is_empty():
T.push(S.pop())
return (S, T) | Python | nomic_cornstack_python_v1 |
from sklearn.feature_selection import chi2 , f_classif , mutual_info_classif
from sklearn.feature_selection import f_regression , mutual_info_regression
from sklearn.feature_selection import SelectKBest , SelectPercentile
class UnivariateFeatureSelction
begin
function __init__ self n_features problem_type scoring
begin... | from sklearn.feature_selection import chi2, f_classif, mutual_info_classif
from sklearn.feature_selection import f_regression, mutual_info_regression
from sklearn.feature_selection import SelectKBest, SelectPercentile
class UnivariateFeatureSelction:
def __init__(self, n_features, problem_type, scoring):
... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
from typing import Optional
class AuthenticationToken extends object
begin
set token_content : str
set expiration : Optional at datetime
function __init__ self token_content expiration
begin
set token_content = token_content
set expiration = expiration
end function
function is_expired self... | from datetime import datetime
from typing import Optional
class AuthenticationToken(object):
token_content: str
expiration: Optional[datetime]
def __init__(self, token_content: str, expiration: Optional[datetime]) -> None:
self.token_content = token_content
self.expiration = expiration
... | Python | zaydzuhri_stack_edu_python |
import pygame
from pygame.locals import RLEACCEL
from const import PATH_IMG_STONE1 , PATH_IMG_BRICK2 , PATH_IMG_BOX , PATH_IMG_ICE , PATH_IMG_WERT_WALL , PATH_IMG_HOR_WALL , PATH_IMG_ANGLE_LEFT_UP_WALL , PATH_IMG_ANGLE_RIGHT_UP_WALL , PATH_IMG_ANGLE_LEFT_DOWN_WALL , PATH_IMG_ANGLE_RIGHT_DOWN_WALL , PATH_IMG_TEXTURE_MOB... | import pygame
from pygame.locals import (
RLEACCEL,
)
from const import PATH_IMG_STONE1, PATH_IMG_BRICK2, PATH_IMG_BOX, \
PATH_IMG_ICE, PATH_IMG_WERT_WALL, PATH_IMG_HOR_WALL, \
PATH_IMG_ANGLE_LEFT_UP_WALL, PATH_IMG_ANGLE_RIGHT_UP_WALL, \
PATH_IMG_ANGLE_LEFT_DOWN_WALL, PATH_IMG_ANGLE_RIGH... | Python | zaydzuhri_stack_edu_python |
comment Has not yet been applied with functions to the main, but is
comment a work in progress to future goals.
import sys
from PyQt5 import QtGui , QtCore
class Window extends QMainWindow
begin
function __init__ self
begin
call __init__
call setGeometry 0 0 800 480
call setWindowTitle string DistoPod
comment self.setW... | #Has not yet been applied with functions to the main, but is
# a work in progress to future goals.
import sys
from PyQt5 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(0, 0, 800, 480)
self.setWindowTitle("DistoP... | Python | zaydzuhri_stack_edu_python |
function _validateUuid dErrors sName sValue
begin
set tuple sValue sError = call validateUuid sValue fAllowNull=true
if sError is not none
begin
set dErrors at sName = sError
end
return sValue
end function | def _validateUuid(dErrors, sName, sValue):
(sValue, sError) = ModelDataBase.validateUuid(sValue, fAllowNull = True);
if sError is not None:
dErrors[sName] = sError;
return sValue; | Python | nomic_cornstack_python_v1 |
function list_application_change request
begin
return call render request string tracking/listTrackingApplication.html dict string trackinglist call order_by string -Timestamp
end function | def list_application_change(request):
return render(request, "tracking/listTrackingApplication.html", {
'trackinglist': ApplicationTracking.objects.order_by('-Timestamp')
}) | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
import random
function city a
begin
if a == 1
begin
set a = string 大连
end
if a == 2
begin
set a = string 成都
end
return a
end function
set list = list
set b = 0
set c = 0
for i in range 888888
begin
set a = random integer 1 2
set a = call city a
if a == string 大连
begin
set b = b + 1
end
if a == str... | # coding:utf-8
import random
def city(a):
if a == 1:
a = '大连'
if a == 2:
a = '成都'
return a
list = []
b = 0
c = 0
for i in range(888888):
a = random.randint(1, 2)
a = city(a)
if a == '大连':
b += 1
if a == '成都':
c += 1
| Python | zaydzuhri_stack_edu_python |
from flask import Flask , request
set app = call Flask __name__
decorator call route string /
function index
begin
return string <h1>User Information</h1> <form action="/info" method="POST"> <input type="text" name="user" placeholder="User Name"> <input type="email" name="email" placeholder="Email Address"> <input type... | from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
return '''
<h1>User Information</h1>
<form action="/info" method="POST">
<input type="text" name="user" placeholder="User Name">
<input type="email" name="email" placeholder="Email Address">
<input type="pass... | Python | zaydzuhri_stack_edu_python |
function set self field value=none
begin
string [Edge|Vertex] establece datos del recurso
if value is none and is instance field dict
begin
call content field
end
if field and value
begin
set data at field = value
end
return self
end function | def set(self, field, value = None):
"""
[Edge|Vertex] establece datos del recurso
"""
if value is None and isinstance(field, dict):
self.content(field)
if field and value:
self.data[field] = value
return self | Python | jtatman_500k |
function get_e_greedy_policy self policy epsilon=0.0
begin
comment Get |A(s)|
set number_actions = length policy
comment Get the extra probability to divide over actions
set extra_probability = epsilon / number_actions
set best_action_list = list
set other_action_list = list
comment Get the maximum value in the polic... | def get_e_greedy_policy(self, policy, epsilon=0.0):
#Get |A(s)|
number_actions = len(policy)
#Get the extra probability to divide over actions
extra_probability = epsilon/number_actions
best_action_list = []
other_action_list = []
#Get the maximum value in the policy
max_value = max(policy.iteritems(), ... | Python | nomic_cornstack_python_v1 |
function get_employment_status self
begin
if ascender_data and string emp_status in ascender_data and ascender_data at string emp_status
begin
if ascender_data at string emp_status in EMP_STATUS_MAP
begin
return EMP_STATUS_MAP at ascender_data at string emp_status
end
end
return string
end function | def get_employment_status(self):
if self.ascender_data and 'emp_status' in self.ascender_data and self.ascender_data['emp_status']:
if self.ascender_data['emp_status'] in self.EMP_STATUS_MAP:
return self.EMP_STATUS_MAP[self.ascender_data['emp_status']]
return '' | Python | nomic_cornstack_python_v1 |
function get_file_content file_name
begin
with open file_name string r as f
begin
set content = read f
end
return content
end function
function vigenere_cipher content key
begin
set result = string
set i = 5
for character in content
begin
set snum = ordinal character - ordinal key at i
while snum < 32
begin
set snum =... | def get_file_content(file_name):
with open(file_name,'r') as f:
content = f.read()
return content
def vigenere_cipher(content , key):
result = ""
i = 5
for character in content:
snum = ord(character) - ord(key[i])
while (snum < 32):
snum += 95
... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment Instantiate a mixed-integer solver.
set solver = call Solver string SolveAssignmentProblemMIP CBC_MIXED_INTEGER_PROGRAMMING
comment Number of teams (h and i)
set n = 9
comment Number of rooms (j)
set r = 3
comment Number of timeslots (k)
set t = 4
comment Number of matches
set m = 4
comment ... | def main():
# Instantiate a mixed-integer solver.
solver = pywraplp.Solver('SolveAssignmentProblemMIP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Number of teams (h and i)
n = 9
# Number of rooms (j)
r = 3
# Number of timeslots (k)
t = 4
# Number ... | Python | nomic_cornstack_python_v1 |
function __init__ __self__ api_endpoint http_method query_time_format query_window_in_min end_time_attribute_name=none headers=none query_parameters=none query_parameters_template=none rate_limit_qps=none retry_count=none start_time_attribute_name=none timeout_in_seconds=none
begin
set __self__ string api_endpoint api_... | def __init__(__self__, *,
api_endpoint: str,
http_method: str,
query_time_format: str,
query_window_in_min: int,
end_time_attribute_name: Optional[str] = None,
headers: Optional[Any] = None,
query_para... | Python | nomic_cornstack_python_v1 |
function updateBets self sessionToken bets
begin
comment create elements for the update requests
set updates = string
for bet in bets
begin
set updates = updates + string <m0:UpdateBets> <betId>%i</betId> <newPrice>%.2f</newPrice> <newSize>%.2f</newSize> <oldPrice>%.2f</oldPrice> <oldSize>%.2f</oldSize> </m0:UpdateBet... | def updateBets(self, sessionToken, bets):
# create elements for the update requests
updates = ''
for bet in bets:
updates = updates + '''
<m0:UpdateBets>
<betId>%i</betId>
<newPrice>%.2f</newPrice>
<newSize>%... | Python | nomic_cornstack_python_v1 |
function critical self msg
begin
log 50 msg
end function | def critical(self, msg):
self.log(50, msg) | Python | nomic_cornstack_python_v1 |
function tf_ssd_bboxes_select_layer_all_classes predictions_layer localizations_layer select_threshold=none
begin
comment Reshape features: Batches x N x N_labels | 4
set p_shape = call get_shape predictions_layer
set predictions_layer = reshape tf predictions_layer stack list p_shape at 0 - 1 p_shape at - 1
set l_shap... | def tf_ssd_bboxes_select_layer_all_classes(predictions_layer, localizations_layer,
select_threshold=None):
# Reshape features: Batches x N x N_labels | 4
p_shape = extend_tensors.get_shape(predictions_layer)
predictions_layer = tf.reshape(predictions_layer,
... | Python | nomic_cornstack_python_v1 |
function find_module modulename filename=none
begin
import imp
import sys
import os
set full_path = list
if filename
begin
append full_path directory name path absolute path path filename
end
set full_path = full_path + path
set fname = call find_module modulename full_path
return fname at 1
end function | def find_module(modulename, filename=None):
import imp
import sys
import os
full_path = []
if filename:
full_path.append(os.path.dirname(os.path.abspath(filename)))
full_path += sys.path
fname = imp.find_module(modulename, full_path)
return fname[1] | Python | nomic_cornstack_python_v1 |
print call randomString | print(randomString()) | Python | jtatman_500k |
function join *parts
begin
string Join path name components, inserting ``/`` as needed. If any component is an absolute path (see :func:`isabs`), all previous components will be discarded. However, full URIs (see :func:`isfull`) take precedence over incomplete ones: .. code-block:: python >>> import pydoop.hdfs.path as... | def join(*parts):
"""
Join path name components, inserting ``/`` as needed.
If any component is an absolute path (see :func:`isabs`), all
previous components will be discarded. However, full URIs (see
:func:`isfull`) take precedence over incomplete ones:
.. code-block:: python
>>> impo... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Sat Apr 5 18:04:19 2014 @author: Mike
import pandas
import scipy.stats
import statsmodels.api as sm
from matplotlib import pyplot as plt
import numpy as np
function shapiro_wilk filepath parameter
begin
set df = read csv filepath
set array = df at parameter
set tuple w p ... | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 5 18:04:19 2014
@author: Mike
"""
import pandas
import scipy.stats
import statsmodels.api as sm
from matplotlib import pyplot as plt
import numpy as np
def shapiro_wilk(filepath, parameter):
df = pandas.read_csv(filepath)
array = df[parameter]
w, p = scipy.... | Python | zaydzuhri_stack_edu_python |
import h5py
import datetime
import pandas as pd
import numpy as np
import glob
class DataBase
begin
string " This class stores two datasets in the binary dailydata.hdf5: "weather_data" := matrix with every row representing a database entry with the respective properties. a new matrix is initialized with dimensions (400... | import h5py
import datetime
import pandas as pd
import numpy as np
import glob
class DataBase:
""""
This class stores two datasets in the binary dailydata.hdf5:
"weather_data" := matrix with every row representing a database entry with
the respective properties.
... | Python | zaydzuhri_stack_edu_python |
import json
import requests
from bs4 import BeautifulSoup
import os
comment 同文件夹自己写的statistics.py
from statistics import statist
set books = list
function crawl_data headers url
begin
string 爬取豆瓣读书top250的前100本书籍,并把每本书籍的信息写入json文件
try
begin
print url
set res = get requests url headers=headers
comment print(res.text)
se... | import json
import requests
from bs4 import BeautifulSoup
import os
from statistics import statist # 同文件夹自己写的statistics.py
books = []
def crawl_data(headers, url):
'''
爬取豆瓣读书top250的前100本书籍,并把每本书籍的信息写入json文件
'''
try:
print(url)
res = requests.get(url, headers=headers)
#print(... | Python | zaydzuhri_stack_edu_python |
function main
begin
set on_call = call OnCall API_KEY SCHEDULE_IDS
run
end function | def main():
on_call = OnCall(API_KEY, SCHEDULE_IDS)
on_call.run() | Python | nomic_cornstack_python_v1 |
function test_output_representation_unicode self unicode_representation_resolver obs wire target
begin
assert call output_representation obs wire == target
end function | def test_output_representation_unicode(
self, unicode_representation_resolver, obs, wire, target
):
assert unicode_representation_resolver.output_representation(obs, wire) == target | Python | nomic_cornstack_python_v1 |
function add_action_group_ids self
begin
return get pulumi self string add_action_group_ids
end function | def add_action_group_ids(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "add_action_group_ids") | Python | nomic_cornstack_python_v1 |
string Takes a file prints it then removes blank lines and outputs to the terminal.
comment FILE INPUT
comment Open a file for reading
set f = open string ../sandbox/test.txt string r
comment use "implicit" for loop:
comment if the object is a file, python will cycle over lines
for line in f
begin
print line
end
commen... | """ Takes a file prints it then removes blank lines and outputs to the terminal."""
###########################
# FILE INPUT
###########################
# Open a file for reading
f = open('../sandbox/test.txt', 'r')
#use "implicit" for loop:
#if the object is a file, python will cycle over lines
for line in f:
... | Python | zaydzuhri_stack_edu_python |
function InternalError message=none
begin
if message
begin
return call _InternalError message
end
else
if get ctx string app_stack
begin
return call internalerror
end
else
begin
return call _InternalError
end
end function | def InternalError(message=None):
if message:
return _InternalError(message)
elif ctx.get('app_stack'):
return ctx.app_stack[-1].internalerror()
else:
return _InternalError() | Python | nomic_cornstack_python_v1 |
comment Eff1b.py
comment Insertion sort
from gamegrid import *
import random
function cardValue card
begin
return call getHeight
end function
function updateGrid
begin
call removeAllActors
for i in range length startList
begin
call addActor startList at i call Location i 0
end
for i in range length targetList
begin
cal... | # Eff1b.py
# Insertion sort
from gamegrid import *
import random
def cardValue(card):
return card.getImage().getHeight()
def updateGrid():
removeAllActors()
for i in range(len(startList)):
addActor(startList[i], Location(i, 0))
for i in range(len(targetList)):
addActor(targetList[i], Locat... | Python | zaydzuhri_stack_edu_python |
function init_graph_display title=none aux_title=none size=4.0 graph_shape=string sqr graph_grid=none x_label=string y_label=string dark=false with_parens=true prob_axes=true axes=none num_genes=none
begin
if dark
begin
set color = string w
end
else
begin
set color = string k
end
comment need to allow for legend whil... | def init_graph_display(title=None, aux_title=None, size=4.0, \
graph_shape='sqr', graph_grid=None, x_label='', y_label='', \
dark=False, with_parens=True, prob_axes=True, axes=None, num_genes=None):
if dark:
color='w'
else:
color='k'
rect_scale_factor = 1.28 #need to allow for le... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
import os
import sys
import codecs
import urllib
import urllib2
import simplejson
from urllib2 import urlopen
from urllib import urlencode
set chinese_dict = dict string 操作系统 string 作业系统 ; string 计算机 string 电脑 ; string 源代码 string 源始码 ; string 文件 string 档案 ; string 工具栏 ... | #!/usr/bin/env python
# coding: utf-8
import os
import sys
import codecs
import urllib
import urllib2
import simplejson
from urllib2 import urlopen
from urllib import urlencode
chinese_dict = {
'操作系统': '作业系统',
'计算机': '电脑',
'源代码': '源始码',
'文件': '档案',
'工具栏': '工具列',
'快捷键': '捷径键',
'台式机': '桌上型电... | Python | zaydzuhri_stack_edu_python |
import math
set tuple n a b = map int split input
set MOD = 1000000000 + 7
set inv = list 1 1
set com = list 0 n
for i in range 2 max a b + 1
begin
append inv MOD - inv at MOD % i * MOD // i % MOD
append com com at i - 1 * n - i + 1 * inv at i % MOD
end
print power 2 n MOD - com at a - com at b - 1 % MOD | import math
n, a, b = map(int, input().split())
MOD = 1000000000 + 7
inv = [1, 1]
com = [0, n]
for i in range(2, max(a, b) + 1):
inv.append(MOD - inv[MOD % i] * (MOD // i) % MOD)
com.append(com[i - 1] * (n - i + 1) * inv[i] % MOD)
print((pow(2, n, MOD) - com[a] - com[b] - 1) % MOD)
| Python | zaydzuhri_stack_edu_python |
function aggregate data
begin
comment load data
comment Supply
set V1 = data at string V1
set V2 = data at string V2
set V3 = data at string V3
set V4 = data at string V4
comment Use
set U1 = data at string U1
set U2 = data at string U2
set U3 = data at string U3
set U4 = data at string U4
comment Final Demand
set Y1 =... | def aggregate(data):
# load data
V1 = data["V1"] # Supply
V2 = data["V2"]
V3 = data["V3"]
V4 = data["V4"]
U1 = data["U1"] # Use
U2 = data["U2"]
U3 = data["U3"]
U4 = data["U4"]
Y1 = data["Y1"] # Final Demand
Y2 = data["Y2"]
Y3 = data["Y3"]
Y4 = data["Y4"]
E1... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.