code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function create_model self opt
begin
comment Retrieve Model Backbone from Model File
set model = call get_model opt
comment Add Fully Connected Layers to Model
for _ in range fc_layers
begin
add model dense fc_width
end
comment Add Final Layer According to Num Actions
if num_actions == 2
begin
add model dense 9 activat... | def create_model(self, opt):
# Retrieve Model Backbone from Model File
model = get_model(opt)
# Add Fully Connected Layers to Model
for _ in range(opt.fc_layers):
model.add(Dense(opt.fc_width))
# Add Final Layer According to Num Actions
if self.num_actions ... | Python | nomic_cornstack_python_v1 |
import subprocess
comment subprocess module is to process things using your terminal
import optparse
comment optparse module is to add options to your command
import re
comment re module is to process regex code
import random
comment Adding options to your script
function get_argument
begin
set parser = call OptionPars... | import subprocess
# subprocess module is to process things using your terminal
import optparse
# optparse module is to add options to your command
import re
# re module is to process regex code
import random
#Adding options to your script
def get_argument():
parser = optparse.OptionParser()
parser.add_option("... | Python | zaydzuhri_stack_edu_python |
function GetQuests self
begin
return call GetQuests
end function | def GetQuests(self):
return(self.GetQuestLog().GetQuests()) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment Implement pow(x, n).
comment Link:
comment https://leetcode.com/problems/powx-n/
class Solution extends object
begin
function myPow self x n
begin
string :type x: float :type n: int :rtype: float
end function
end class | # -*- coding: utf-8 -*-
# Implement pow(x, n).
#
#
# Link:
# https://leetcode.com/problems/powx-n/
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from btdtwf import configuration , connect , main
import os
set testdir = directory name path __file__
set test_cfg_file = join path testdir string test_wf.cfg
function test_parse
begin
set cfg = parse configuration test_cfg_file
set wf = call interpret cfg
assert 3 == length input_nodes ms... | #!/usr/bin/env python
from btdtwf import configuration, connect, main
import os
testdir = os.path.dirname(__file__)
test_cfg_file = os.path.join(testdir, 'test_wf.cfg')
def test_parse():
cfg = configuration.parse(test_cfg_file)
wf = configuration.interpret(cfg)
assert 3 == len(wf.input_nodes), str(wf.inp... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import psycopg2
from datetime import timedelta , date
set continents = dict string 002 string Africa ; string 019 string Americas ; string 142 string Asia ; string 150 string Europe ; string 009 string Oceania
set countries = dict string 002 dict string EG string Egypt ; string SN st... | #!/usr/bin/python
import sys
import psycopg2
from datetime import timedelta, date
continents = {'002': 'Africa', '019': 'Americas', '142': 'Asia', '150': 'Europe', '009': 'Oceania'}
countries = {'002': {'EG': 'Egypt', 'SN': 'Senegal', 'ZW': 'Zimbabwe', 'AO': 'Angola', 'RW': 'Rwanda', 'BW': 'Botswana'},
... | Python | zaydzuhri_stack_edu_python |
function fat_prime a b
begin
for i in range max a b min a b - 1 - 1
begin
if call is_prime i
begin
return i
end
end
end function
function is_prime num
begin
for i in range 2 integer num ^ 0.5 + 1
begin
if num % i == 0
begin
return false
end
end
return true
end function | def fat_prime(a, b):
for i in range(max(a,b),min(a,b-1),-1):
if is_prime(i):
return i
def is_prime(num):
for i in range(2,int(num**0.5)+1):
if num%i==0:
return False
return True
| Python | zaydzuhri_stack_edu_python |
function empty_patch patch
begin
return shape at 0 == size
end function | def empty_patch(patch):
return np.argwhere(patch == -100).shape[0] == patch.size | Python | nomic_cornstack_python_v1 |
import random
comment Generate a random series of 10 unique numbers between 1 and 1000
set series = random sample range 1 1001 10
comment Custom sorting algorithm implementation
function custom_sort series
begin
set n = length series
for i in range n - 1
begin
for j in range 0 n - i - 1
begin
if series at j < series at... | import random
# Generate a random series of 10 unique numbers between 1 and 1000
series = random.sample(range(1, 1001), 10)
# Custom sorting algorithm implementation
def custom_sort(series):
n = len(series)
for i in range(n - 1):
for j in range(0, n - i - 1):
if series[j] < series[j + 1]:
... | Python | jtatman_500k |
comment import os
comment chemin = "/Users/AdrienCy/Desktop/Python_Udemy"
comment dossier = os.path.join(chemin, "dossier", "test")
comment print(dossier)
comment if.os.path.exists(dossier):
comment os.removedirs(dossier)
comment # pour créer un fichier et en meme temps voir s'il y existe
comment # if not os.path.exist... | # import os
# chemin = "/Users/AdrienCy/Desktop/Python_Udemy"
# dossier = os.path.join(chemin, "dossier", "test")
# print(dossier)
# if.os.path.exists(dossier):
# os.removedirs(dossier)
# # pour créer un fichier et en meme temps voir s'il y existe
# # if not os.path.exists(dossier):
# # os.makedirs(dos... | Python | zaydzuhri_stack_edu_python |
function available self
begin
return _available
end function | def available(self):
return self._available | Python | nomic_cornstack_python_v1 |
function meminfo_varsize_free self builder meminfo ptr
begin
call _require_nrt
set mod = module
set fnty = call FunctionType call VoidType list voidptr_t voidptr_t
set fn = call get_or_insert_function mod fnty string NRT_MemInfo_varsize_free
return call fn tuple meminfo ptr
end function | def meminfo_varsize_free(self, builder, meminfo, ptr):
self._require_nrt()
mod = builder.module
fnty = ir.FunctionType(ir.VoidType(),
[cgutils.voidptr_t, cgutils.voidptr_t])
fn = cgutils.get_or_insert_function(mod, fnty,
... | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data
begin
set left = none
set right = none
set data = data
end function
function insert self data
begin
comment Compare the new value with the parent node
if data
begin
if data < data
begin
if left is none
begin
set left = call Node data
end
else
begin
insert left data
end
end
e... | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left =... | Python | zaydzuhri_stack_edu_python |
function factorial_sum_list_old max_num=- 1
begin
comment Constants
comment factorials for digits 0-9
set factorials = tuple 1 1 2 6 24 120 720 5040 40320 362880
comment max_digits = (0, 3, 4, 6, 7, 8, 9, 9) # the max digit that can be used at each digit count,
comment e.g. 2-digit numbers can only use digits 0-4
comme... | def factorial_sum_list_old(max_num=-1):
# Constants
factorials = (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880) # factorials for digits 0-9
# max_digits = (0, 3, 4, 6, 7, 8, 9, 9) # the max digit that can be used at each digit count,
# e.g. 2-digit numb... | Python | nomic_cornstack_python_v1 |
comment Python Examples:
comment linked_list.py
comment Linked list implementation in Python.
comment Xavier Torrent Gorjon
class Element extends object
begin
string Class that represents nodes on the linked list.
function __init__ self data
begin
string Class constructor. Sets the data variable.
set __data = data
set ... | #####
# Python Examples:
# linked_list.py
#
# Linked list implementation in Python.
#
# Xavier Torrent Gorjon
#####
class Element(object):
"""Class that represents nodes on the linked list."""
def __init__(self, data):
"""Class constructor. Sets the data variable."""
self.__data = data
... | Python | zaydzuhri_stack_edu_python |
import math
set x = 16
function sqrt x
begin
set sqrt_val = 0
end function
comment Start from the left most digit in x
while sqrt_val * sqrt_val <= x
begin
comment if sqrt_val is equal to x,
comment return it
if sqrt_val * sqrt_val == x
begin
return sqrt_val
end
comment else continue the loop
set sqrt_val = sqrt_val + ... | import math
x = 16
def sqrt(x):
sqrt_val = 0
# Start from the left most digit in x
while sqrt_val * sqrt_val <= x:
# if sqrt_val is equal to x,
# return it
if (sqrt_val * sqrt_val == x):
return sqrt_val
# else continue the loop
sqrt_val = sqrt_val + 1
return sqrt_val - 1
# Driver Function
... | Python | jtatman_500k |
import tensorflow as tf
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import os
set environ at string KMP_DUPLICATE_LIB_OK = string True
class ParkingLotDetector extends object
begin
function __init__ self
begin
set PATH_TO_MODEL = string fine_tuned_model/frozen_inference_graph.pb
set de... | import tensorflow as tf
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
class ParkingLotDetector(object):
def __init__(self):
PATH_TO_MODEL = 'fine_tuned_model/frozen_inference_graph.pb'
self.detection_graph = tf.Gr... | Python | zaydzuhri_stack_edu_python |
comment lists: ordered, mutable,allows duplicate elements
set mylist = list string banana string cherry string apple
print mylist at - 1
for i in mylist
begin
print i
end
if string banana in mylist
begin
print string true
end
else
begin
print string false
end
print mylist
append mylist string lemon
insert mylist 1 stri... | #lists: ordered, mutable,allows duplicate elements
mylist =["banana","cherry","apple"]
print(mylist[-1])
for i in mylist:
print (i)
if "banana" in mylist:
print("true")
else: print("false")
print(mylist)
mylist.append("lemon")
mylist.insert(1,"blueberry")
print(len(mylist))
print("---------------------")
item=m... | Python | zaydzuhri_stack_edu_python |
function update_knowledge self loc loc_type
begin
update knowledge_gained dict loc loc_type
end function | def update_knowledge(self, loc, loc_type):
self.knowledge_gained.update({loc: loc_type}) | Python | nomic_cornstack_python_v1 |
comment 4. Napisz program, który wyświetli kolejne wyniki dla silni liczby naturalnej N
comment (N podane przez użytkownika, ale nie większe niż 8).
set natural_num = integer input string Podaj liczbę całkowitą od 0 do 8:
if natural_num < 0
begin
print string Liczba ujemna! Podaj liczbę między 0 a 8!
end
else
if natura... | # 4. Napisz program, który wyświetli kolejne wyniki dla silni liczby naturalnej N
# (N podane przez użytkownika, ale nie większe niż 8).
natural_num = int(input("Podaj liczbę całkowitą od 0 do 8: "))
if natural_num < 0:
print("Liczba ujemna! Podaj liczbę między 0 a 8!")
elif natural_num > 8:
print("Liczba więks... | Python | zaydzuhri_stack_edu_python |
comment tetris.py
from Tkinter import *
import random
import copy
function tetrisMousePressed canvas event
begin
pass
end function
comment calls appropriate function for each key press
function tetrisKeyPressed canvas event
begin
if keysym == string r
begin
call tetrisInit canvas
end
if isGameOver == false
begin
if key... | #tetris.py
from Tkinter import *
import random
import copy
def tetrisMousePressed(canvas, event):
pass
#calls appropriate function for each key press
def tetrisKeyPressed(canvas, event):
if (event.keysym == "r"):
tetrisInit(canvas)
if canvas.data.isGameOver == False:
if (event.keysym ... | Python | zaydzuhri_stack_edu_python |
function test_delete_namespaced_role_binding_restriction self
begin
pass
end function | def test_delete_namespaced_role_binding_restriction(self):
pass | Python | nomic_cornstack_python_v1 |
function get_overlapping_feats_from_record record start end strand all_types=list string CDS min_overlap=1 max_feats=none
begin
set target_loc = call FeatureLocation start end strand
set overlapping_feats = list
for f in features
begin
if type not in all_types
begin
continue
end
set _overlap_len = call get_FeatureLoca... | def get_overlapping_feats_from_record(
record, start, end, strand, all_types=['CDS'], min_overlap=1, max_feats=None):
target_loc = FeatureLocation(start, end, strand)
overlapping_feats = []
for f in record.features:
if f.type not in all_types:
continue
f._overlap_len = get_Fe... | Python | nomic_cornstack_python_v1 |
from etcd_client import EtcdClient
class DistributedCache extends object
begin
function __init__ self config_path key_prefix logger
begin
comment reconnect every 4 minutes
set etcd_client = call EtcdClient config_path key_prefix logger 240
set logger = logger
set key_prefix = key_prefix
set cache = dict
end function
f... | from etcd_client import EtcdClient
class DistributedCache(object):
def __init__(self, config_path, key_prefix, logger):
self.etcd_client = EtcdClient(config_path, key_prefix, logger, 240) # reconnect every 4 minutes
self.logger = logger
self.key_prefix = key_prefix
self.cache = {}... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python2.7
comment -*- coding: utf8 -*-
from numpy import ndarray
set EPSILON = 0.001
function almoste_equal a b absolute=false
begin
if is instance a bool or is instance b bool
begin
return a == b
end
if absolute
begin
set result = absolute a - b < EPSILON
end
else
begin
set result = a == 0 and c... | #! /usr/bin/env python2.7
# -*- coding: utf8 -*-
from numpy import ndarray
EPSILON = 0.001
def almoste_equal(a, b, absolute=False):
if isinstance(a, bool) or isinstance(b, bool):
return a == b
if absolute:
result = abs(a - b) < EPSILON
else:
result = ((a == 0 and almoste_zero(b))... | Python | zaydzuhri_stack_edu_python |
import random
function generate_random_string_without_repeats data
begin
set random_sample = random sample data length data
set random_string = join string random_sample
return random_string
end function
set data = list string H string e string l string l string o
set n = length data
set random_string = call generate_... | import random
def generate_random_string_without_repeats(data):
random_sample = random.sample(data, len(data))
random_string = ''.join(random_sample)
return random_string
data = ["H", "e", "l", "l", "o"]
n = len(data)
random_string = generate_random_string_without_repeats(data)
print(random_string) # Exa... | Python | greatdarklord_python_dataset |
function insertTag self name=none attrs=dict payload=list node=none
begin
set newnode = call Node tag=name parent=self attrs=attrs payload=payload node=node
append kids newnode
return newnode
end function | def insertTag(self, name=None, attrs={}, payload=[], node=None):
newnode = Node(tag=name, parent=self, attrs=attrs, payload=payload, node=node)
self.kids.append(newnode)
return newnode | Python | nomic_cornstack_python_v1 |
string https://leetcode.com/problems/generate-parentheses/ Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"]
class Solution
begin
function generateP... | """
https://leetcode.com/problems/generate-parentheses/
Given n pairs of parentheses, write a function to
generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
"""
class Solution:
def generate... | Python | zaydzuhri_stack_edu_python |
import sys
set input = readline
set ri = lambda -> integer input
comment rl = lambda: [int(x) if x.isdecimal() else x for x in input().split()]
comment rl = lambda: list(input().split()))
set rl = lambda -> map int split input
set rr = lambda N -> list comprehension list l for l in zip *[rl() for _ in range(N)]
set Y... | import sys
input = sys.stdin.readline
ri = lambda: int(input())
#rl = lambda: [int(x) if x.isdecimal() else x for x in input().split()]
#rl = lambda: list(input().split()))
rl = lambda: map(int,input().split())
rr = lambda N: [list(l) for l in zip(*[rl() for _ in range(N)])]
YN = lambda b: print('YES') if b else print(... | Python | zaydzuhri_stack_edu_python |
from Queue import LifoQueue as Stack
from collections import defaultdict
set inputlines = call splitlines
set num_testcases = inputlines at 0
set outputlist = list
set testcasenum = 1
set i = 1
while i < length inputlines
begin
set graphsize = integer inputlines at i
set adj_list = dictionary
set i = i + 1
for j in ra... | from Queue import LifoQueue as Stack
from collections import defaultdict
inputlines = open('A-large.in', 'r').read().splitlines()
num_testcases = inputlines[0]
outputlist = []
testcasenum = 1
i = 1
while i < len(inputlines):
graphsize = int(inputlines[i])
adj_list = dict()
i += 1
... | Python | zaydzuhri_stack_edu_python |
comment Test plotting routine for CP Generator
comment Steven Large
comment February 15th 2017
import matplotlib.pyplot as plt
function Plotting mod1 mod2
begin
set filename = string CP_Trajectory_ + mod1 + string _ + mod2 + string .dat
set file1 = open filename string r
set data1 = read lines file1
close file1
set Tim... | #Test plotting routine for CP Generator
#
#Steven Large
#February 15th 2017
import matplotlib.pyplot as plt
def Plotting(mod1,mod2):
filename = 'CP_Trajectory_' + mod1 + '_' + mod2 + '.dat'
file1 = open(filename,'r')
data1 = file1.readlines()
file1.close()
Time = []
Position = []
for index in range(len(d... | Python | zaydzuhri_stack_edu_python |
function stides data_set_1 data_set_2 mode
begin
if mode == 0
begin
set matrix = call distances data_set_1 data_set_2 weight_l weight_o weight_d weight_s weight_e
set result = call get_similarity matrix
return result at 1
end
else
if mode == 1
begin
set result_shift = 0
set result = list - 1 - 1
set factors = call get_... | def stides(data_set_1, data_set_2, mode):
if mode == 0:
matrix = pre.distances(data_set_1, data_set_2, settings.weight_l, settings.weight_o, settings.weight_d , settings.weight_s, settings.weight_e)
result = st.get_similarity(matrix)
return result[1]
elif mode == 1:
result_shift ... | Python | nomic_cornstack_python_v1 |
function delete_processed_messages self
begin
comment Build a list of messages that we can delete (i.e. successfully
comment processed)
set messages_to_delete = list
for message in messages
begin
if requested is true or duplicate is true and failed is false
begin
append messages_to_delete message
end
end
info string De... | def delete_processed_messages(self):
# Build a list of messages that we can delete (i.e. successfully
# processed)
messages_to_delete = list()
for message in self.messages:
if ((message.requested is True or message.duplicate is True) and
(message.failed is... | Python | nomic_cornstack_python_v1 |
function __len__ self
begin
return length img_infos
end function | def __len__(self):
return len(self.img_infos) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: UTF-8 -*-
import sys
import pandas as pd
import time
from datetime import date
from csv import writer
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from os import system , name
from time import sleep
from shutil import copyfile
import os
set document =... | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import pandas as pd
import time
from datetime import date
from csv import writer
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from os import system, name
from time import sleep
from shutil import copyfile
import os
document = pd.read_csv('da... | Python | zaydzuhri_stack_edu_python |
function time_left self time=none
begin
set time = time or now
return start - time
end function | def time_left(self, time=None):
time = time or now()
return self.start - time | Python | nomic_cornstack_python_v1 |
function as_widget self widget=none attrs=none only_initial=false
begin
set tuple html_layout field_names = call get_layout self
if is instance html_layout tuple tuple list
begin
set html = call as_widget attrs=html_layout at 1 only_initial=only_initial
set html_layout = html_layout at 0
end
else
begin
set html = call ... | def as_widget(self, widget=None, attrs=None, only_initial=False):
html_layout,field_names = self.field.get_layout(self)
if isinstance(html_layout,(tuple,list)):
html = super(CompoundBoundField,self).as_widget(attrs=html_layout[1],only_initial=only_initial)
html_layout = html_... | Python | nomic_cornstack_python_v1 |
function __get_table self bucket
begin
string Get table by bucket
set table_name = call convert_bucket bucket
if __dbschema
begin
set table_name = join string . tuple __dbschema table_name
end
return tables at table_name
end function | def __get_table(self, bucket):
"""Get table by bucket
"""
table_name = self.__mapper.convert_bucket(bucket)
if self.__dbschema:
table_name = '.'.join((self.__dbschema, table_name))
return self.__metadata.tables[table_name] | Python | jtatman_500k |
function assertHoliday self *args
begin
call _assertHoliday string holidays *args
end function | def assertHoliday(self, *args):
self._assertHoliday("holidays", *args) | Python | nomic_cornstack_python_v1 |
function delete
begin
set rst = check output string screen -X -S pinger quit shell=true
set rst = rst + check output string screen -ls shell=true
return rst
end function | def delete():
rst = subprocess.check_output("screen -X -S pinger quit", shell= True)
rst += subprocess.check_output("screen -ls", shell = True)
return rst | Python | nomic_cornstack_python_v1 |
import socket
import json
import time
import sys
import file_helper
set host = string 127.0.0.1
set port = 50000
set client_name = string Adam
set file_name = string test
set path = string files
function send fileToSend
begin
set command = dict string command string file_send_req ; string client_name client_name
set co... | import socket
import json
import time
import sys
import file_helper
host = "127.0.0.1"
port = 50000
client_name = "Adam"
file_name = 'test'
path = "files"
def send(fileToSend):
command = {
"command": "file_send_req",
"client_name": client_name
}
command["file_n... | Python | zaydzuhri_stack_edu_python |
string 方法一 1.导入 import 包名.模块名 2.调用功能 包名.模块名.功能()
comment import my_package.moudle1
comment my_package.moudle1.print_info()
string 方法二 必须在__init__.py文件中添加__al1__ = [],控制允许导入的模块列表。 然后可以使用 from 包 import * 通过模块名.方法可以调用
from my_package import *
call print_info | """
方法一
1.导入
import 包名.模块名
2.调用功能
包名.模块名.功能()
"""
# import my_package.moudle1
# my_package.moudle1.print_info()
"""
方法二
必须在__init__.py文件中添加__al1__ = [],控制允许导入的模块列表。
然后可以使用 from 包 import *
通过模块名.方法可以调用
"""
from my_package import *
moudle2.print_info()
| Python | zaydzuhri_stack_edu_python |
function _traverse_namespace self cursor namespaces
begin
for c in call get_children
begin
if kind in tuple CLASS_DECL STRUCT_DECL
begin
call _traverse_class c namespaces
end
else
if kind == FUNCTION_DECL and kind == FUNCTIONPROTO
begin
call _traverse_function c namespaces
end
else
if kind == NAMESPACE
begin
set child_... | def _traverse_namespace(self, cursor: Cursor, namespaces: List[Text]) -> None:
for c in cursor.get_children():
if c.kind in (CursorKind.CLASS_DECL, CursorKind.STRUCT_DECL):
self._traverse_class(c, namespaces)
elif (c.kind == CursorKind.FUNCTION_DECL and
c.type.kind == TypeKind.FUNCTI... | Python | nomic_cornstack_python_v1 |
function _update_linestyle_spec self
begin
set _linestyle_spec = if expression call _C line_style interp then line_style else string
end function | def _update_linestyle_spec(self):
self._linestyle_spec = (
self.line_style if _C(self.line_style, self.interp) else ''
) | Python | nomic_cornstack_python_v1 |
from django import http
from django.http.response import HttpResponse
from django.shortcuts import redirect , render
import markdown2
from random import randint
from import util
function index request
begin
return call render request string encyclopedia/index.html dict string entries call list_entries
end function
fun... | from django import http
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
import markdown2
from random import randint
from . import util
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def create(reque... | Python | zaydzuhri_stack_edu_python |
from sys import stdin
from collections import deque
function main
begin
set tuple n m k = map int split read line stdin
set a = list comprehension map int split read line stdin for _ in call xrange n
set q = list comprehension deque for _ in call xrange m
set maxlen = 0
set left = 0
set ans = list 0 * m
for tuple i x i... | from sys import stdin
from collections import deque
def main():
n, m, k = map(int, stdin.readline().split())
a = [map(int, stdin.readline().split()) for _ in xrange(n)]
q = [deque() for _ in xrange(m)]
maxlen = 0;
left = 0;
ans = [0] * m
for i, x in enumerate(a):
for j, y in enumera... | Python | zaydzuhri_stack_edu_python |
from Tree import *
function lowestCommonAncestorOfBST root p q
begin
if p == root or q == root
begin
return root
end
else
if val < root and val > root or val > root and val < root
begin
return root
end
else
if val < root
begin
return call lowestCommonAncestorOfBST left p q
end
else
begin
return call lowestCommonAncesto... | from Tree import *
def lowestCommonAncestorOfBST(root: TreeNode, p: TreeNode, q: TreeNode):
if p == root or q == root:
return root
elif p.val < root and q.val > root or p.val > root and q.val < root:
return root
elif p.val < root:
return lowestCommonAncestorOfBST(root.left, p, q)
... | Python | zaydzuhri_stack_edu_python |
function __convert_session self json_data
begin
if json_data is none
begin
return false
end
comment value_store = json.loads(json_text)
set value_store = json_data
if string user in value_store
begin
comment print value_store['user']
set user = call User self keyword value_store at string user
call metadata_retrieve
en... | def __convert_session(self, json_data):
if json_data is None:
return False
#value_store = json.loads(json_text)
value_store = json_data
if 'user' in value_store:
#print value_store['user']
self.user = User(self, **value_s... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment Created on Sun Jul 6 12:17:39 2014
comment Implemented in Python 3.4.0
comment Author: Yun-Jhong Wu
comment E-mail: yjwu@umich.edu
import numpy as np
function MatrixCompletion X Omega nu=1 rank=5 tol=0.0001 maxiters=1000
begin
string Matrix completion by augmented Lagrange multipli... | # -*- coding: utf-8 -*-
# Created on Sun Jul 6 12:17:39 2014
# Implemented in Python 3.4.0
# Author: Yun-Jhong Wu
# E-mail: yjwu@umich.edu
import numpy as np
def MatrixCompletion(X, Omega, nu=1, rank=5,
tol=1e-4, maxiters=1000):
"""
Matrix completion by augmented Lagrange multiplier
... | Python | zaydzuhri_stack_edu_python |
comment Here's a challenge for you to help you practice
comment See if you can fix the code below
comment There was a single quote inside the string
comment Use double quotes to enclosed the string
print string Why won't this line of code print.
comment There was a mistake in the function name
print string this line fa... | #Here's a challenge for you to help you practice
#See if you can fix the code below
#There was a single quote inside the string
#Use double quotes to enclosed the string
print("Why won't this line of code print.")
#There was a mistake in the function name
print('this line fails too!')
#Need to add () around the stri... | Python | zaydzuhri_stack_edu_python |
comment shape detection
import numpy as np
import cv2
set img = call imread string shapes.jpg
set imgray = call cvtColor img COLOR_BGR2GRAY
set tuple _ thresh = call threshold imgray 240 255 THRESH_BINARY
set tuple contours _ = call findContours thresh RETR_TREE CHAIN_APPROX_NONE
for contour in contours
begin
set appro... | # shape detection
import numpy as np
import cv2
img=cv2.imread('shapes.jpg')
imgray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,thresh=cv2.threshold(imgray,240,255,cv2.THRESH_BINARY)
contours,_=cv2.findContours(thresh,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for contour in contours:
approx=cv2.approxPolyDP(contour,0.01*c... | Python | zaydzuhri_stack_edu_python |
function move self movement ids tag=none
begin
set request = call construct_request method=value arguments=dict string ids ids tag=tag
return call send request
end function | def move(
self, movement: QueueMovement, ids: IdsArg, tag: int = None
) -> Response[Mapping[str, object]]:
request = construct_request(
method=movement.value, arguments={"ids": ids}, tag=tag
)
return self._connection.send(request) | Python | nomic_cornstack_python_v1 |
function read_matrix file_path sep=string
begin
set file = open file_path string r
set head_line = strip read line file
set output = dictionary
comment read the head
set names = list filter lambda x -> length x > 0 split head_line sep
comment read the single lines of the matrix
for line in read lines file
begin
set lin... | def read_matrix(file_path, sep=" "):
file = open(file_path, 'r')
head_line = file.readline().strip()
output = dict()
# read the head
names = list(filter(lambda x: len(x) > 0, head_line.split(sep)))
# read the single lines of the matrix
for line in file.readlines():
line = list(filt... | Python | nomic_cornstack_python_v1 |
function create_venues fn=string /src/redisu/ru101/data/venues.json
begin
import json
seed 94002
set f = open fn
set venues = load json f
for i in range length venues
begin
set v = venues at i
set attrs = dict string zone v at string zone
if string capacity in v
begin
set attrs at string capacity = v at string capacity... | def create_venues(fn="/src/redisu/ru101/data/venues.json"):
import json
random.seed(94002)
f = open(fn)
venues = json.load(f)
for i in range(len(venues)):
v = venues[i]
attrs = {'zone': v['zone']}
if 'capacity' in v:
attrs['capacity'] = v['capacity']
p.hmset(create_key_name("venue", v['v... | Python | nomic_cornstack_python_v1 |
with open string day_1_input.txt string rU as f
begin
set chars = read f
end
set pos = 0
for i in chars
begin
set pos = pos + 1
if i == string (
begin
set floor = floor + 1
end
else
comment print ' Going to {}'.format(floor)
if i == string )
begin
set floor = floor - 1
end
end
comment print ' Going to {}'.format(floor) | with open('day_1_input.txt', 'rU') as f:
chars = f.read()
pos = 0
for i in chars:
pos += 1
if i == '(':
floor += 1
# print ' Going to {}'.format(floor)
elif i == ')':
floor -= 1
# print ' Going to {}'.format(floor)
| Python | zaydzuhri_stack_edu_python |
from tabulate import tabulate
comment inicia a classe Personagem atribuindo valores iniciais aos atributos.
class Personagem
begin
function __init__ self nome=string Thiago nivel=string Estudante
begin
set __nome = nome
set __saude = 100
set __relacionamento = 100
set __dinheiro = 150
set __estresse = 0
set __xp = 0
se... | from tabulate import tabulate
# inicia a classe Personagem atribuindo valores iniciais aos atributos.
class Personagem:
def __init__(self, nome='Thiago', nivel='Estudante'):
self.__nome = nome
self.__saude = 100
self.__relacionamento = 100
self.__dinheiro = 150
self.__estres... | Python | zaydzuhri_stack_edu_python |
function fetch_weather_thread self
begin
call start_new_thread fetch_weather tuple
end function | def fetch_weather_thread(self):
thread.start_new_thread(self.fetch_weather, ()) | Python | nomic_cornstack_python_v1 |
import numpy as np
from pathlib import Path
from datetime import date
import argparse
import shutil
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
import torch.optim as optim
from torch.utils import data
import json
import src.utils.logger as logger
class Data... | import numpy as np
from pathlib import Path
from datetime import date
import argparse
import shutil
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
import torch.optim as optim
from torch.utils import data
import json
import src.utils.logger as logger
class ... | Python | zaydzuhri_stack_edu_python |
function main
begin
set f = open string input string r
set floor = 0
set list_floor = tuple read lines f at 0
for tuple index value in enumerate list_floor
begin
if value == string (
begin
set floor = floor + 1
end
else
if value == string )
begin
set floor = floor - 1
if floor == - 1
begin
print index + 1
end
end
end
e... | def main():
f = open('input', 'r')
floor = 0
list_floor = tuple(f.readlines()[0])
for index, value in enumerate(list_floor):
if value == '(':
floor += 1
elif value ==')':
floor -= 1
if floor ==-1: print(index+1)
if __name__ == '__main__': main(... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isValid self s
begin
set opened = list
if length s % 2 != 0
begin
return false
end
for i in s
begin
if i == string { or i == string ( or i == string [
begin
append opened i
end
else
if i == string } or i == string ) or i == string ]
begin
if length opened < 1
begin
return false
end
set la... | class Solution:
def isValid(self, s: str) -> bool:
opened = []
if(len(s)%2!=0):
return False
for i in s:
if (i=='{' or i =='(' or i=='['):
opened.append(i)
elif(i=='}' or i ==')' or i==']'):
if(len(opened)<1):
... | Python | zaydzuhri_stack_edu_python |
function _load_hdr self fileName delimiter iHdrLine
begin
set f = open fileName
set i = 0
for l in f
begin
if i == iHdrLine
begin
call dprint string DBUG:DataSrc:_load_hdr:type:%s % type l
return split l delimiter
end
set i = i + 1
end
raise call ImportError string DataSrc:_load_hdr: No header found
end function | def _load_hdr(self, fileName, delimiter, iHdrLine):
f = open(fileName)
i = 0
for l in f:
if (i == iHdrLine):
dprint("DBUG:DataSrc:_load_hdr:type:%s" %(type(l)))
return l.split(delimiter)
i += 1
raise ImportError("DataSrc:_load_hdr: ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment generate a bigram markov chain from killian's tweets
import re
import random
set model = dict
for line in open string tweets.txt string r
begin
set words = split re string \s+ line
set last_word = string START
for word in words
begin
if last_word in model and word in model at last_... | #!/usr/bin/env python
# generate a bigram markov chain from killian's tweets
import re
import random
model = {}
for line in open('tweets.txt', 'r'):
words = re.split('\s+', line)
last_word = 'START'
for word in words:
if last_word in model and word in model[last_word]:
model[last_word][word] += 1
... | Python | zaydzuhri_stack_edu_python |
set N = integer input
set SP = list comprehension split input for _ in range N
set M = sum map int generator expression p for tuple _ p in SP
set ans = list filter lambda a -> integer a at 1 * 2 > M SP
print if expression ans then ans at 0 at 0 else string atcoder | N = int(input())
SP = [input().split() for _ in range(N)]
M = sum(map(int, (p for _, p in SP)))
ans = list(filter(lambda a: int(a[1]) * 2 > M, SP))
print(ans[0][0] if ans else 'atcoder')
| Python | zaydzuhri_stack_edu_python |
function getElementName self
begin
return call ListOfParameters_getElementName self
end function | def getElementName(self):
return _libsbml.ListOfParameters_getElementName(self) | Python | nomic_cornstack_python_v1 |
function clear_cache
begin
set settings = call django_settings
if has attribute settings string COMPRESS_ROOT
begin
set cache_dir = COMPRESS_ROOT / COMPRESS_OUTPUT_DIR
end
end function
comment a safety check | def clear_cache():
settings = fabutils.django_settings()
if hasattr(settings, 'COMPRESS_ROOT'):
cache_dir = settings.COMPRESS_ROOT / settings.COMPRESS_OUTPUT_DIR
# a safety check | Python | nomic_cornstack_python_v1 |
function get_stats self
begin
string Get kitty stats as a dictionary
set resp = get requests string %s/api/stats.json % url
assert status_code == 200
return json resp
end function | def get_stats(self):
'''
Get kitty stats as a dictionary
'''
resp = requests.get('%s/api/stats.json' % self.url)
assert(resp.status_code == 200)
return resp.json() | Python | jtatman_500k |
function test_left_alignment self
begin
set block = call ScheduleBlock alignment_context=left_context
set block = append block call Play test_waveform0 d0
set block = append block call Play test_waveform1 d1
set ref_sched = call Schedule
set ref_sched = insert ref_sched 0 call Play test_waveform0 d0
set ref_sched = ins... | def test_left_alignment(self):
block = pulse.ScheduleBlock(alignment_context=self.left_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert... | Python | nomic_cornstack_python_v1 |
function valid_length row csv_schema
begin
set current_field = csv_schema at row at string Field Name
if length
begin
return length row at string Value Provided <= length
end
return true
end function | def valid_length(row, csv_schema):
current_field = csv_schema[row['Field Name']]
if current_field.length:
return len(row['Value Provided']) <= current_field.length
return True | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse as parse
from app.lyrics.lyrics import Lyrics
from website import LyricsWebsite
class AnimeLyrics extends LyricsWebsite
begin
function __init__ self
begin
call __init__ string AnimeLyrics string www.animelyrics.com
end function
function acc... | import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse as parse
from app.lyrics.lyrics import Lyrics
from ..website import LyricsWebsite
class AnimeLyrics(LyricsWebsite):
def __init__(self):
super().__init__("AnimeLyrics", "www.animelyrics.com")
def accept(self, url: str):
... | Python | zaydzuhri_stack_edu_python |
comment Python 的元组与列表类似,不同之处在于元组的元素不能修改。
comment 元组使用小括号,列表使用方括号。
comment 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
comment !/usr/bin/python
comment -*- coding:utf-8 -*-
comment @Time : 2019/12/14 9:27 下午
comment @Author : qinxi
comment @Site : www.iqinxi.com
comment @File : test1.py
comment 定义一个元组,括号不是必须的,逗号才是元组的关键。
set tuple = ... | #Python 的元组与列表类似,不同之处在于元组的元素不能修改。
#元组使用小括号,列表使用方括号。
#元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time : 2019/12/14 9:27 下午
# @Author : qinxi
# @Site : www.iqinxi.com
# @File : test1.py
#定义一个元组,括号不是必须的,逗号才是元组的关键。
tuple = (1,2,3,4,5,8,10)
tuple1 = 9,10,20,64
print(tuple) #... | Python | zaydzuhri_stack_edu_python |
function get_input_files self action
begin
set method_mapping = dict string access none ; string target _get_input_files_target ; string antitarget _get_input_files_antitarget ; string coverage _get_input_files_coverage ; string reference _get_input_files_reference ; string call _get_input_files_call ; string fix _get_... | def get_input_files(self, action):
method_mapping = {
"access": None,
"target": self._get_input_files_target,
"antitarget": self._get_input_files_antitarget,
"coverage": self._get_input_files_coverage,
"reference": self._get_input_files_reference,
... | Python | nomic_cornstack_python_v1 |
function reload self
begin
try
begin
set _data = call _request _self_link
end
except HTTPError as error
begin
warn string Reloading resource failed: { error }
end
end function | def reload(self,) -> None:
try:
self._data = self._request(self._self_link)
except requests.exceptions.HTTPError as error:
warnings.warn(f'Reloading resource failed: {error}') | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
from dados_basicos import Dados_basicos
set infos = list dict string campo string volume ; string valor 12345 dict string campo string br ; string valor 0.345 ; string porcentagem true ; string casas_decimais 1 dict string campo string renda ; string valor 283490
set objeto = call D... | # coding: utf-8
# In[1]:
from dados_basicos import Dados_basicos
infos = [
{'campo':'volume',
'valor':12345
},
{'campo':'br',
'valor':0.345,
'porcentagem':True,
'casas_decimais':1
},
{'campo':'renda',
'valor':283490,
}
]
objeto = Dados_basicos(infos)
objeto.imprime_... | Python | zaydzuhri_stack_edu_python |
function bubble_sort arr
begin
set n = length arr
for i in range n
begin
for j in range 0 n - i - 1
begin
if arr at j > arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j
end
end
end
end function
set array = list 9 8 11 5
call bubble_sort array
print array | def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
array = [9, 8, 11, 5]
bubble_sort(array)
print(array)
| Python | flytech_python_25k |
function test_encoder self
begin
from sosbeacon.utils import number_encode
set number = 123
set encoded = call number_encode number
assert equal encoded string b6
end function | def test_encoder(self):
from sosbeacon.utils import number_encode
number = 123
encoded = number_encode(number)
self.assertEqual(encoded, 'b6') | Python | nomic_cornstack_python_v1 |
function execute_command_with_timeout self command=string timeout=TIMEOUT receiver=none
begin
return call execute_remote_cmd_with_timeout telnet command timeout receiver
end function | def execute_command_with_timeout(self, command="", timeout=TIMEOUT,
receiver=None):
return LiteHelper.execute_remote_cmd_with_timeout(
self.telnet, command, timeout, receiver) | Python | nomic_cornstack_python_v1 |
for i in range n
begin
insert v i i + 1
end | for i in range(n):
v.insert(i, i + 1)
| Python | zaydzuhri_stack_edu_python |
import unittest
from datetime import datetime
comment rachel stern's user stories
comment code for us02
function us02 id name birthdate mardate gen
begin
if string parse time birthdate string %d %b %Y > string parse time mardate string %d %b %Y and gen == string her
begin
set error_wifeus02 = string Error US02: Marriag... | import unittest
from datetime import datetime
# rachel stern's user stories
# code for us02
def us02(id, name, birthdate, mardate, gen):
if ((datetime.strptime(birthdate, '%d %b %Y')) > (datetime.strptime(mardate, '%d %b %Y')) and gen == "her"):
error_wifeus02 = "Error US02: Marriage of " + name + " (" + id + "... | Python | zaydzuhri_stack_edu_python |
function __eq__ self other
begin
if not is instance other __class__
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool:
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
function normality_check x a=none reta=false alpha=0.05 showhist=true
begin
if is instance x list
begin
set x = call asarray x
end
else
if ndim == 2
begin
comment to 1d
set x = flatten x
end
else
if ndim > 2
begin
raise call RuntimeWarning string Array ndim > 2 should be 1-d
end
set xnonan = x at ? call isnan x
set tup... | def normality_check(x, a=None, reta=False, alpha=0.05, showhist=True):
if isinstance(x, list):
x = np.asarray(x)
elif x.ndim == 2:
x = x.flatten() # to 1d
elif x.ndim > 2:
raise RuntimeWarning("Array ndim > 2 should be 1-d")
xnonan = x[~np.isnan(x)]
W, pVa... | Python | nomic_cornstack_python_v1 |
class airport
begin
function __init__ self name
begin
set name = name
end function
end class
class flight
begin
function __init__ self fls src dest d
begin
set src = src
set dest = dest
set d = d
add fls list self
end function
function print self
begin
print name string to name d string miles
end function
end class
cla... | class airport:
def __init__( self, name ):
self.name=name
class flight:
def __init__( self, fls, src, dest, d ):
self.src = src
self.dest = dest
self.d = d
fls.add( [self] )
def print(self):
print( self.src.name, 'to', self.dest.name, self.d, 'miles' )
... | Python | zaydzuhri_stack_edu_python |
function censor text censored
begin
return replace text censored length censored * string *
end function
print call censor string sadsad kala abhdhd ufhdjw kala fdsf kala string kala
function censor text censor_word
begin
set censor = length censor_word * string *
set text = split text
for tuple index x in enumerate te... | def censor(text, censored):
return text.replace(censored, len(censored) * '*')
print(censor('sadsad kala abhdhd ufhdjw kala fdsf kala', 'kala'))
def censor(text, censor_word):
censor = len(censor_word) * '*'
text = text.split()
for index, x in enumerate(text):
if x == censor_word:
... | Python | zaydzuhri_stack_edu_python |
function set_mangaka self mangaka
begin
set __mangaka = mangaka
end function | def set_mangaka(self, mangaka):
self.__mangaka = mangaka | Python | nomic_cornstack_python_v1 |
function setup self
begin
comment read config from container, use service name as default prefix
set service_name = service_name
set config = get config string PROMETHEUS dict
set service_config = get config service_name dict
set prefix = get service_config string prefix service_name
comment initialize default metrics ... | def setup(self) -> None:
# read config from container, use service name as default prefix
service_name = self.container.service_name
config = self.container.config.get("PROMETHEUS", {})
service_config = config.get(service_name, {})
prefix = service_config.get("prefix", service_na... | Python | nomic_cornstack_python_v1 |
comment Function for Stacking of Images
import cv2
import numpy as np
function stackImages imgArray scale labels=list
begin
set rows = length imgArray
set cols = length imgArray at 0
set rowsAvail = is instance imgArray at 0 list
set width = shape at 1
set height = shape at 0
if rowsAvail
begin
for x in range rows
begi... | # Function for Stacking of Images
import cv2
import numpy as np
def stackImages(imgArray, scale, labels=[]):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvail = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvail:
... | Python | zaydzuhri_stack_edu_python |
string Calculate mock density and Poisson error in calculation.
from config import *
function main
begin
comment load the todo pointing list
set input_filename = rawdata_dir + string todo_list.dat
write stderr format string Loading from file {} ... input_filename
set input_file = open input_filename string rb
set todo_... | '''
Calculate mock density and Poisson error in calculation.
'''
from config import *
def main():
# load the todo pointing list
input_filename = rawdata_dir + 'todo_list.dat'
sys.stderr.write('Loading from file {} ...\n'.format(input_filename))
input_file = open(input_filename, 'rb')
todo_list... | Python | zaydzuhri_stack_edu_python |
comment Project Name:
comment Glass Carbide
comment By:
comment Michael Gailling
comment &&
comment Mustafa Butt
comment Organization:
comment WIMTACH
from PySide2.QtGui import QPixmap , Qt
from PySide2.QtWidgets import QFrame , QLabel , QVBoxLayout
class GCLogoView extends QFrame
begin
string Logo View Summary: A clas... | # Project Name:
# Glass Carbide
#
# By:
# Michael Gailling
# &&
# Mustafa Butt
#
# Organization:
# WIMTACH
#
from PySide2.QtGui import QPixmap, Qt
from PySide2.QtWidgets import QFrame, QLabel, QVBoxLayout
class GCLogoView(QFrame):
"""Logo View
Summary:
A class for GCLogoView that includes:
... | Python | zaydzuhri_stack_edu_python |
function testCachingMessagesWorks self
begin
set mail_service = call MailServiceStub
assert false _cached_messages
set message = call CreateRequest sender=string from@nowhere.com to=list string to@nowhere.com subject=string a subject body=string a body html=string <html>
call _Send call ToProto none DoNothing smtp pope... | def testCachingMessagesWorks(self):
mail_service = mail_stub.MailServiceStub()
self.assertFalse(mail_service._cached_messages)
message = self.CreateRequest(sender='from@nowhere.com',
to=['to@nowhere.com'],
subject='a subject',
... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function maxNumberOfBalloons self text
begin
set num_b = count text string b
set num_o = count text string o
set num_a = count text string a
set num_l = count text string l
set num_n = count text string n
set n_l = num_l // 2
set n_o = num_o // 2
set ret = list num_a num_b num_n n_l n_o
set a = min... | class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
num_b = text.count('b')
num_o = text.count('o')
num_a = text.count('a')
num_l = text.count('l')
num_n = text.count('n')
n_l = num_l // 2
n_o = num_o // 2
ret = [num_a, num_b, num_n, n_l, ... | Python | zaydzuhri_stack_edu_python |
function get_response_data response
begin
try
begin
return json response
end
except ValueError
begin
return content
end
end function | def get_response_data(response):
try:
return response.json()
except ValueError:
return response.content | Python | nomic_cornstack_python_v1 |
function target fct
begin
function wrapped *args **kwargs
begin
if not has attribute env string target
begin
set target = __name__
end
return call fct *args keyword kwargs
end function
return wrapped
end function | def target(fct):
def wrapped(*args, **kwargs):
if not hasattr(env, 'target'):
env.target = fct.__name__
return fct(*args, **kwargs)
return wrapped | Python | nomic_cornstack_python_v1 |
comment THIS SCRIPT CHECKS THE SIMULATIONS' AND DATA COUNTS IN ORDER TO SEE IF THE BACKGROUND
comment MODELING IS REASONABLE
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
import sys
import os
string wd='/Users/alberto/Desktop/XBOOTES/bootes2/6998/repro/out2/' bkg=fits.open(wd+'acisf0699... | # THIS SCRIPT CHECKS THE SIMULATIONS' AND DATA COUNTS IN ORDER TO SEE IF THE BACKGROUND
# MODELING IS REASONABLE
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
import sys
import os
'''
wd='/Users/alberto/Desktop/XBOOTES/bootes2/6998/repro/out2/'
bkg=fits.open(wd+'acisf06998_bkgmap.fits'... | Python | zaydzuhri_stack_edu_python |
import re
print find all string \d string abc123
comment Code executed. | import re
print(re.findall('\d', 'abc123'))
# Code executed.
| Python | flytech_python_25k |
function create_transport beaver_config file_config logger
begin
if get beaver_config string transport == string rabbitmq
begin
import beaver.rabbitmq_transport
set transport = call RabbitmqTransport beaver_config file_config logger
end
else
if get beaver_config string transport == string redis
begin
import beaver.redi... | def create_transport(beaver_config, file_config, logger):
if beaver_config.get('transport') == 'rabbitmq':
import beaver.rabbitmq_transport
transport = beaver.rabbitmq_transport.RabbitmqTransport(beaver_config, file_config, logger)
elif beaver_config.get('transport') == 'redis':
import b... | Python | nomic_cornstack_python_v1 |
comment Canguros:
comment atributos: edad, id
comment funciones: saltar(cantidad_de_saltos)
comment --> entradas: cantidad_de_saltos = cantidad de saltos del canguro
comment --> salidas :none
class Canguros
begin
function __init__ self edad_ingresada id_ingresado
begin
set edad = edad_ingresada
set id = id_ingresado
en... | # Canguros:
# atributos: edad, id
# funciones: saltar(cantidad_de_saltos)
# --> entradas: cantidad_de_saltos = cantidad de saltos del canguro
# --> salidas :none
class Canguros ():
def __init__(self,edad_ingresada,id_ingresado):
self.edad = edad_ingresada
self.id = id_ing... | Python | zaydzuhri_stack_edu_python |
function dataset
begin
return call DataFrame data=list list string Alice string R&D list string Bob string Accnt list string Claudia string R&D list string Rob string Service columns=list string Name string Department
end function | def dataset():
return pd.DataFrame(
data=[
['Alice', 'R&D'],
['Bob', 'Accnt'],
['Claudia', 'R&D'],
['Rob', 'Service']
],
columns=['Name', 'Department']
) | Python | nomic_cornstack_python_v1 |
import re
comment 3种常用匹配模式
comment 常见匹配方法
comment # 1、re.match(pattern,string)# 从目标字符串的开始进行匹配,
comment pattern='abc'
comment string='abcddddddefg123 python_3.5123abc'
comment result=re.match(pattern,string)
comment print(result) #左闭右开
comment print(result.span())#找到匹配信息的所在位置
comment print(result.group())#找到匹配的信息
commen... | import re
# 3种常用匹配模式
# 常见匹配方法
# # 1、re.match(pattern,string)# 从目标字符串的开始进行匹配,
# pattern='abc'
# string='abcddddddefg123 python_3.5123abc'
# result=re.match(pattern,string)
# print(result) #左闭右开
# print(result.span())#找到匹配信息的所在位置
# print(result.group())#找到匹配的信息
# # 2、re.search(pattern,string)
# pattern='123'
# string='a... | Python | zaydzuhri_stack_edu_python |
from pydantic import BaseModel , validator
class Region extends BaseModel
begin
set region_id : int
set region_name : str = none
decorator call validator string region_id
function region_id_validation cls v
begin
if not v >= 0 and is instance v int
begin
raise call ValueError string Id must be positive integer
end
retu... | from pydantic import BaseModel, validator
class Region(BaseModel):
region_id: int
region_name: str = None
@validator('region_id')
def region_id_validation(cls, v: int):
if not (v >= 0 and isinstance(v, int)):
raise ValueError('Id must be positive integer')
return v
| Python | zaydzuhri_stack_edu_python |
function main
begin
set in_fname = string i1.txt
set in_fname = string i1_eg.txt
set lines = split strip read open in_fname string
set timestamp = integer lines at 0
set buses = split strip lines at 1 string ,
set buses = list comprehension integer x for x in buses if x != string x
print timestamp
print buses
comment d... | def main():
in_fname = "i1.txt"
in_fname = "i1_eg.txt"
lines = open(in_fname).read().strip().split('\n')
timestamp = int(lines[0])
buses = lines[1].strip().split(',')
buses = [int(x) for x in buses if x != "x"]
print(timestamp)
print(buses)
# diff
min_wait = max(buses)
bus_i... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , Dropout , Flatten
from tensorflow.keras.layers import Conv2D , MaxPooling2D
comment Load the data
set tuple tuple x_train y_train tuple x_test y_test = call load... | import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
# Load the data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Build the m... | Python | iamtarun_python_18k_alpaca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.