code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function to_rna dna_sequence
begin
set dna = string GCTA
set rna = string CGAU
set trans_table = call maketrans dna rna
return call translate trans_table
end function | def to_rna(dna_sequence):
dna = 'GCTA'
rna = 'CGAU'
trans_table = str.maketrans(dna, rna)
return dna_sequence.translate(trans_table)
| Python | zaydzuhri_stack_edu_python |
function get_types self args
begin
if string include_type in args and include_type is not none
begin
set new_type_map = dict
for this_type in include_type
begin
try
begin
set new_type_map at this_type = type_map at this_type
end
except KeyError
begin
print string No such type: "%s". Use --help for valid types % this_t... | def get_types(self, args):
if "include_type" in args and args.include_type is not None:
new_type_map = {}
for this_type in args.include_type:
try:
new_type_map[this_type] = self.type_map[this_type]
except KeyError:
p... | Python | nomic_cornstack_python_v1 |
function seeing_empirical r s0 r0 a=1.5
begin
return call seeing_large_scale s0 r0 / 1 + 2 * s0 / r ^ a
end function | def seeing_empirical(r, s0, r0, a=1.5):
return seeing_large_scale(s0, r0) / (1 + (2 * s0 / r) ** a) | Python | nomic_cornstack_python_v1 |
function test_intext_links_tagging self
begin
with open join path DATA_ROOT string intext_links_tagging.html as f
begin
set tuple article raw_html = call extract_article_data f
set extracted_links = links
set tagged_urls = list call make_tagged_url string http://www.lameuse.be/vervietois2011 string www.lameuse.be/vervi... | def test_intext_links_tagging(self):
with open(os.path.join(DATA_ROOT, "intext_links_tagging.html")) as f:
article, raw_html = sudpresse.extract_article_data(f)
extracted_links = article.links
tagged_urls = [
make_tagged_url("http://www.lameuse.be/verviet... | Python | nomic_cornstack_python_v1 |
function evalpotential self X Y Z
begin
set EVAL = zeros like X
for b in beams
begin
set EVAL = EVAL + call b X Y Z
end
return EVAL * unitfactor
end function | def evalpotential( self, X, Y, Z):
EVAL = np.zeros_like(X)
for b in self.beams:
EVAL += b(X,Y,Z)
return EVAL* self.unitfactor | Python | nomic_cornstack_python_v1 |
class Solution
begin
function subdomainVisits self cpdomains
begin
set d = default dictionary int
for cpdomain in cpdomains
begin
set tuple times subdomain = split cpdomain string
set times = integer times
set subdomain = split subdomain string .
set res = pop subdomain
set d at res = d at res + times
for string in sub... | class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
d = defaultdict(int)
for cpdomain in cpdomains:
times, subdomain = cpdomain.split(" ")
times = int(times)
subdomain = subdomain.split(".")
res = subdomain.pop()
d... | Python | zaydzuhri_stack_edu_python |
function Clone self
begin
return call itkConnectedComponentImageFilterIUS2IUC2_Clone self
end function | def Clone(self) -> "itkConnectedComponentImageFilterIUS2IUC2_Pointer":
return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUS2IUC2_Clone(self) | Python | nomic_cornstack_python_v1 |
function account_name self account_name
begin
set _account_name = account_name
end function | def account_name(self, account_name):
self._account_name = account_name | Python | nomic_cornstack_python_v1 |
function get_spacy_entites self text
begin
string Pretrained (spaCy) Uses averaged preceptron Places, dates, people, organizations
comment NOTE: spaCy doc
set doc = call _language_model text
set entities = list comprehension dict string entity label_ ; string value text ; string start start_char ; string end end_char f... | def get_spacy_entites(self, text: str) -> list:
"""
Pretrained (spaCy)
Uses averaged preceptron
Places, dates, people, organizations
"""
# NOTE: spaCy doc
doc = self._language_model(text)
entities = [{"entity": ent.label_,
"value": en... | Python | jtatman_500k |
comment Version 2.1
import numpy as np
from numpy import linalg as la
import torch
import hw5_utils as utils
from scipy.stats import norm , mode
from scipy.stats import multivariate_normal as gauss
from collections import defaultdict
comment Problem 2 #################################
function k_means X k
begin
string ... | #Version 2.1
import numpy as np
from numpy import linalg as la
import torch
import hw5_utils as utils
from scipy.stats import norm, mode
from scipy.stats import multivariate_normal as gauss
from collections import defaultdict
################################# Problem 2 #################################
def k_means(X... | Python | zaydzuhri_stack_edu_python |
string A forward facing radar display
import pygame
from rotation import rotate_point
class ForwardSweep
begin
string A forward facing radar display
function __init__ self width height displaySurface targets range direction
begin
set _display_surf = displaySurface
set centre = tuple width // 2 height // 2
set max_space... | """A forward facing radar display"""
import pygame
from rotation import rotate_point
class ForwardSweep:
"""A forward facing radar display"""
def __init__(self, width, height, displaySurface, targets, range, direction):
self._display_surf = displaySurface
self.centre = (width//2, height//2)
... | Python | zaydzuhri_stack_edu_python |
function print_tree self
begin
print call to_string
end function | def print_tree(self):
print(self.root_node.to_string()) | Python | nomic_cornstack_python_v1 |
import os
from immune_time_series_class import immune_time_series
import subprocess
function cluster input_seqs_dirpath output_VJ_seqs_dirpath
begin
string This script uses 'immune_time_series_class.py' to go through the immune seqs and partition them into groups based upon their germline V and J gene assignment.
comme... | import os
from immune_time_series_class import immune_time_series
import subprocess
def cluster(input_seqs_dirpath, output_VJ_seqs_dirpath):
"""This script uses 'immune_time_series_class.py' to go through the immune seqs and partition them into groups based upon their germline V and J gene assignment."""
###### par... | Python | zaydzuhri_stack_edu_python |
function test_init_integration self
begin
set J2kWh = 1e-06 / 3.6
set vars_to_integrate = dict string Qflow J2kWh
set p = process mothers=mothers parameters=parameters sub_pars=sub_pars variables=variables sub_vars=sub_vars pp=pp integrate=vars_to_integrate
assert equal parameters dict string cap1 string c1.C ; string ... | def test_init_integration(self):
J2kWh = 1e-6/3.6
vars_to_integrate = {'Qflow':J2kWh}
p = Process(mothers=self.mothers, parameters=self.parameters,
sub_pars=self.sub_pars, variables=self.variables,
sub_vars=self.sub... | Python | nomic_cornstack_python_v1 |
from flask import Flask
from flask import jsonify
from flask import request
set app = call Flask __name__
set public_key = list
set secureSafe = dict string Torch string Creates Fire ; string Knife string Pointy ; string Rock string Useless Rock ; string Paper string You can write things here
decorator call route stri... | from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
public_key = []
secureSafe = {
'Torch' : 'Creates Fire',
'Knife' : 'Pointy',
'Rock' : 'Useless Rock',
'Paper' : 'You can write things here'
}
@app.route('/sendKey', methods=['POST'])
def assignPublic():... | Python | zaydzuhri_stack_edu_python |
string Requirements: In workon cv envirnment write the following pip3 install pyrebase pip3 install pyfcm pip3 install requests pip3 install python-firebase
from firebase import firebase
import json
from pyfcm import FCMNotification
import pyrebase
import time
class firebase_server
begin
function __init__ self
begin
se... | '''
Requirements:
In workon cv envirnment write the following
pip3 install pyrebase
pip3 install pyfcm
pip3 install requests
pip3 install python-firebase
'''
from firebase import firebase
import json
from pyfcm import FCMNotification
import pyrebase
import time
class firebase_server():
def __init__(self):
... | Python | zaydzuhri_stack_edu_python |
function __init__ self target_colour
begin
set colour = target_colour
end function | def __init__(self, target_colour: Tuple[int, int, int]) -> None:
self.colour = target_colour | Python | nomic_cornstack_python_v1 |
from project5 import app
from flask import request , render_template , jsonify
set messageData = list dict
set userData = list string bot
decorator call route string /flask
function hello_world name=none
begin
return call render_template string index.html name=name
end function
decorator call route string /flask/add m... | from project5 import app
from flask import request, render_template, jsonify
messageData = [{}]
userData = ["bot"]
@app.route('/flask')
def hello_world(name=None):
return render_template('index.html', name=name)
@app.route('/flask/add', methods=['GET', 'POST'])
def add():
print("in add")
print(request.meth... | Python | zaydzuhri_stack_edu_python |
function send self
begin
try
begin
set bytes_sent = call send data
remove output bytes_sent
end
except any
begin
set remove = true
clear output
end
end function | def send(self):
try:
bytes_sent = self.socket.send(self.output.data)
self.output.remove(bytes_sent)
except:
self.remove = True
self.output.clear() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import os , subprocess
class Msbuilder
begin
function __init__ self sln_path=string .\\ prj_name=string build_config=string Release devenv_path=string
begin
set possible_msbuild_path = list
set msbuild_path = none
set sln_path = sln_path
set prj_name = prj_name
set build_config = build_c... | # -*- coding: utf-8 -*-
import os, subprocess
class Msbuilder:
def __init__(self, \
sln_path = r".\\", \
prj_name = "", \
build_config = r"Release", \
devenv_path = ""):
self.possible_msbuild_path = []
self.msbuild_path = None
... | Python | zaydzuhri_stack_edu_python |
function _LookupDiskIndex self idx
begin
try
begin
return integer idx
end
except ValueError
begin
pass
end
for tuple i d in enumerate call GetInstanceDisks uuid
begin
if name == idx or uuid == idx
begin
return i
end
end
raise call OpPrereqError string Lookup of disk %r failed % idx
end function | def _LookupDiskIndex(self, idx):
try:
return int(idx)
except ValueError:
pass
for i, d in enumerate(self.cfg.GetInstanceDisks(self.instance.uuid)):
if d.name == idx or d.uuid == idx:
return i
raise errors.OpPrereqError("Lookup of disk %r failed" % idx) | Python | nomic_cornstack_python_v1 |
function _increase_counter cls
begin
set __counter = __counter + 1
end function | def _increase_counter(cls):
cls.__counter += 1 | Python | nomic_cornstack_python_v1 |
import yaml
class Game
begin
function __init__ self name_of_gamefile
begin
with open name_of_gamefile string r as gamefile
begin
set y = load yaml gamefile
set player_position = y at string player_position
set board = y at string board
end
set number_of_treasures_left = 0
for line in board
begin
if string # in line
beg... | import yaml
class Game:
def __init__(self, name_of_gamefile):
with open(name_of_gamefile, 'r') as gamefile:
y = yaml.load(gamefile)
self.player_position = y['player_position']
self.board = y['board']
number_of_treasures_left = 0
for line in... | Python | zaydzuhri_stack_edu_python |
function prediction home away stats model
begin
comment Define categorical variables and initiate year variable.
set categorical = list string buildUpPlaySpeedClass_home string buildUpPlayDribblingClass_home string buildUpPlayPassingClass_home string buildUpPlayPositioningClass_home string chanceCreationPassingClass_ho... | def prediction(home, away, stats, model):
# Define categorical variables and initiate year variable.
categorical = ['buildUpPlaySpeedClass_home', 'buildUpPlayDribblingClass_home',
'buildUpPlayPassingClass_home', 'buildUpPlayPositioningClass_home',
'chanceCreationPassingCl... | Python | nomic_cornstack_python_v1 |
function sample_elbo self inputs labels criterion sample_nbr complexity_cost_weight=1
begin
set loss = 0
for _ in range sample_nbr
begin
set outputs = call self inputs
set loss = loss + call criterion outputs labels
set loss = loss + call nn_kl_divergence * complexity_cost_weight
end
return loss / sample_nbr
end functi... | def sample_elbo(self, inputs, labels, criterion, sample_nbr, complexity_cost_weight=1):
loss = 0
for _ in range(sample_nbr):
outputs = self(inputs)
loss += criterion(outputs, labels)
loss += self.nn_kl_divergence() * complexity_cost_weight
return loss / sample... | Python | nomic_cornstack_python_v1 |
function parseFastaTarget fasta_file candidate_fasta_file target_size eval_and_print
begin
set fasta_file = list parse SeqIO fasta_file string fasta
set tuple seq_name sequence = tuple id string seq
set name = string %s:0-%s % tuple seq_name length sequence
set id_name = string C: + name
set sequence = upper sequence
s... | def parseFastaTarget(fasta_file, candidate_fasta_file, target_size, eval_and_print):
fasta_file = list(SeqIO.parse(fasta_file, 'fasta'))
seq_name, sequence = fasta_file[0].id, str(fasta_file[0].seq)
name = "%s:0-%s" % (seq_name, len(sequence))
id_name = "C:" + name
sequence = sequence.upper()
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Sep 18 14:03:20 2019 @author: abc47
import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import leastsq
comment 加载所有数据
function Load_All
begin
set load_path = string ./数据/原始数据
set data_dict = dict
set FileList = list fi... | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 14:03:20 2019
@author: abc47
"""
import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import leastsq
def Load_All():#加载所有数据
load_path=r"./数据/原始数据"
data_dict={}
FileList=list(filter(lambda x:(x[-4:]==".... | Python | zaydzuhri_stack_edu_python |
function print_report self
begin
comment Used to format the date into the desired one
set date = now
set year = string year
set month = call zfill 2
set day = string day
set hour = call zfill 2
set minute = call zfill 2
set st = day + string - + month + string - + year + string + hour + string : + minute
comment File ... | def print_report(self):
# Used to format the date into the desired one
date = datetime.datetime.now()
year = str(date.year)
month = str(date.month).zfill(2)
day = str(date.day)
hour = str(date.hour).zfill(2)
minute = str(date.minute).zfill(2)
st = day + ... | Python | nomic_cornstack_python_v1 |
function test_get_redirect_desktop self
begin
comment set up a test record
set snippet = call model_factory
set short_url = call encode_short_url id
save snippet
set res = call raw_get short_url headers=dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ... | def test_get_redirect_desktop(self):
# set up a test record
snippet = self.model_factory()
snippet.short_url = url_lib.encode_short_url(snippet.id)
snippet.save(snippet)
res = self.raw_get(
snippet.short_url,
headers={
'User-Agent': 'Mozill... | Python | nomic_cornstack_python_v1 |
function refresh self
begin
comment rebuild our coverage mapping
set tuple dirty_nodes dirty_functions = call _map_coverage
comment bake our coverage map
call _finalize dirty_nodes dirty_functions
comment update the coverage hash incase the hitmap changed
call _update_coverage_hash
end function | def refresh(self):
# rebuild our coverage mapping
dirty_nodes, dirty_functions = self._map_coverage()
# bake our coverage map
self._finalize(dirty_nodes, dirty_functions)
# update the coverage hash incase the hitmap changed
self._update_coverage_hash() | Python | nomic_cornstack_python_v1 |
function iddp_rid eps m n matvect
begin
set proj = call empty m + 1 + 2 * n * min m n + 1 order=string F
set tuple k idx proj ier = call iddp_rid eps m n matvect proj
if ier != 0
begin
raise _RETCODE_ERROR
end
set proj = reshape proj at slice : k * n - k : tuple k n - k order=string F
return tuple k idx proj
end func... | def iddp_rid(eps, m, n, matvect):
proj = np.empty(m + 1 + 2*n*(min(m, n) + 1), order='F')
k, idx, proj, ier = _id.iddp_rid(eps, m, n, matvect, proj)
if ier != 0:
raise _RETCODE_ERROR
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
return k, idx, proj | Python | nomic_cornstack_python_v1 |
comment version code c2eb1c41017f+
comment Please fill out this stencil and submit using the provided submission script.
import random
from GF2 import one
from vecutil import list2vec
from independence import rank
comment 1: (Task 7.7.1) Choosing a Secret Vector
function randGF2
begin
return random integer 0 1 * one
en... | # version code c2eb1c41017f+
# Please fill out this stencil and submit using the provided submission script.
import random
from GF2 import one
from vecutil import list2vec
from independence import rank
## 1: (Task 7.7.1) Choosing a Secret Vector
def randGF2(): return random.randint(0,1)*one
a0 = list2vec([one, one... | Python | zaydzuhri_stack_edu_python |
function port self
begin
return get pulumi self string port
end function | def port(self) -> float:
return pulumi.get(self, "port") | Python | nomic_cornstack_python_v1 |
function token_list_to_formatted_text token_list
begin
set result = list
for tuple token text in token_list
begin
append result tuple string class: + call _pygments_token_to_classname token text
end
return result
end function | def token_list_to_formatted_text(token_list):
result = []
for token, text in token_list:
result.append(('class:' + _pygments_token_to_classname(token), text))
return result | Python | nomic_cornstack_python_v1 |
function separa_trios lista
begin
set trios = list
set rascunho = list
set cont = 0
while cont < length lista
begin
if cont % 3 == 0 and cont > 0
begin
append trios copy rascunho
clear rascunho
end
append rascunho lista at cont
set cont = cont + 1
if cont == length lista
begin
append trios copy rascunho
end
end
retur... | def separa_trios(lista):
trios = []
rascunho = []
cont = 0
while cont < len(lista):
if cont % 3 == 0 and cont > 0:
trios.append(rascunho.copy())
rascunho.clear()
rascunho.append(lista[cont])
cont += 1
if cont == (len(lista)):
trios... | Python | zaydzuhri_stack_edu_python |
function node_id self
begin
return get pulumi self string node_id
end function | def node_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "node_id") | Python | nomic_cornstack_python_v1 |
function test_nsstring_with_run_command self
begin
call appkit_tester_impl nsstring_data_formatter_commands
end function | def test_nsstring_with_run_command(self):
self.appkit_tester_impl(self.nsstring_data_formatter_commands) | Python | nomic_cornstack_python_v1 |
comment to be used in blender
import bpy
import csv
set ob_curve = objects at string CurveObj2
set cu = data
set points = list
set lpoints = list
set rpoints = list
for spline in splines
begin
for point in bezier_points
begin
append points tuple co
append lpoints tuple handle_left
append rpoints tuple handle_right
e... | ## to be used in blender
import bpy
import csv
ob_curve = bpy.data.objects["CurveObj2"]
cu = ob_curve.data
points = []
lpoints = []
rpoints = []
for spline in cu.splines:
for point in spline.bezier_points:
points.append(tuple(point.co))
lpoints.append(tuple(point.handle_left))
rpoints.appe... | Python | zaydzuhri_stack_edu_python |
from numpy import random
class Agent
begin
function __init__ self
begin
set credence = uniform 0 1
set tuple k n = tuple 0 0
end function
function __str__ self
begin
return string credence = { round credence 2 } , k = { k } , n = { n }
end function
function experiment self n epsilon
begin
if credence > 0.5
begin
set k ... | from numpy import random
class Agent:
def __init__(self):
self.credence = random.uniform(0, 1)
self.k, self.n = 0, 0
def __str__(self):
return f"credence = {round(self.credence, 2)}, k = {self.k}, n = {self.n}"
def experiment(self, n, epsilon):
if self.credence > .5:
... | Python | zaydzuhri_stack_edu_python |
function _installCallbacks
begin
pass
end function | def _installCallbacks():
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Sep 3 23:01:08 2019 @author: lord
import pandas as pd
import numpy as np
set data_path = string /home/lord/cloud1.csv
set bid_amount = 180
set number_of_bidder = 10
set small_bidding_fees = 1
set spot_init_price = 110
set amt_inr = 0.1
se... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 23:01:08 2019
@author: lord
"""
import pandas as pd
import numpy as np
data_path = '/home/lord/cloud1.csv'
bid_amount = 180
number_of_bidder = 10
small_bidding_fees = 1
spot_init_price = 110
amt_inr = .1
max_bidding_amount = 70
data ... | Python | zaydzuhri_stack_edu_python |
import ftplib
import create_log
comment class to build up connection to FTP Server
class connectionToServer
begin
comment creates the connection to ftp server
function connectionToFTP self host user password path
begin
try
begin
set ftp = call FTP host
call login user password
call cwd path
return ftp
end
except any
be... | import ftplib
import create_log
#class to build up connection to FTP Server
class connectionToServer():
#creates the connection to ftp server
def connectionToFTP(self, host, user, password, path):
try:
self.ftp = ftplib.FTP(host)
self.ftp.login(user, password)
self.... | Python | zaydzuhri_stack_edu_python |
from pulp import *
import numpy as np
import sys
import datetime
comment Tests that all stable matchings are found using an IP (and pulp).
comment @author Frances
comment recording the duration
set start = now
comment inputting
set numMen = - 1
set menPrefs = list
set womenPrefs = list
set inFileName = argv at 1
set ... | from pulp import *
import numpy as np
import sys
import datetime
# Tests that all stable matchings are found using an IP (and pulp).
# @author Frances
# recording the duration
start = datetime.datetime.now()
# inputting
numMen = -1
menPrefs = []
womenPrefs = []
inFileName = sys.argv[1]
timeLimitSecs = int(sys.argv[... | Python | zaydzuhri_stack_edu_python |
from collections import namedtuple
set Constant = named tuple string OrgPropertyConstant list string display_name string property_name string default
set _COMPANY_NAME = call Constant display_name=string Company Name property_name=string company_name default=none
set _TEXT_LOGIN_MESSAGE = call Constant display_name=str... | from collections import namedtuple
Constant = namedtuple('OrgPropertyConstant', ['display_name', 'property_name', 'default'])
_COMPANY_NAME = Constant(display_name='Company Name', property_name='company_name', default=None)
_TEXT_LOGIN_MESSAGE = Constant(display_name='Text Login Message', property_name='text_login_... | Python | zaydzuhri_stack_edu_python |
function get_accounts self owner is_delegate=false commitment=Single encoding=string jsonParsed
begin
return if expression is_delegate then call get_token_accounts_by_delegate owner call TokenAccountOpts mint=pubkey encoding=encoding commitment else call get_token_accounts_by_owner owner call TokenAccountOpts mint=pubk... | def get_accounts(
self, owner: PublicKey, is_delegate: bool = False, commitment: Commitment = Single, encoding: str = "jsonParsed"
) -> RPCResponse:
return (
self._conn.get_token_accounts_by_delegate(
owner, TokenAccountOpts(mint=self.pubkey, encoding=encoding), commitmen... | Python | nomic_cornstack_python_v1 |
function date_trans_y x
begin
string 2017.1.09->2017/ 1/09
set date_list = split x string .
if integer date_list at 1 < 10
begin
return date_list at 0 + string / + string integer date_list at 1 + string / + date_list at 2
end
else
begin
return date_list at 0 + string / + date_list at 1 + string / + date_list at 2
end
e... | def date_trans_y(x):
"""2017.1.09->2017/ 1/09 """
date_list=x.split('.')
if(int(date_list[1])<10):
return date_list[0]+'/ '+str(int(date_list[1]))+'/'+date_list[2]
else:
return date_list[0]+'/'+date_list[1]+'/'+date_list[2] | Python | nomic_cornstack_python_v1 |
comment Tae Young Kevin Shin
comment Dr. Garrett's COSC 330A
comment Introduction to Database
comment 1st Assignment Submission
comment importing csv module
import csv
comment defining class storing csv data as OrderedDict format
class SalesReader
begin
function __init__ self filename
begin
set __data = list
set __key... | #Tae Young Kevin Shin
#Dr. Garrett's COSC 330A
#Introduction to Database
#1st Assignment Submission
#importing csv module
import csv
#defining class storing csv data as OrderedDict format
class SalesReader:
def __init__(self,filename):
self.__data=[]
self.__keys=[]
with open(f... | Python | zaydzuhri_stack_edu_python |
function check_pattern string
begin
set nums = split string
set nums = list comprehension integer num for num in nums
set curr = nums at 0
set count = 1
for num in nums at slice 1 : :
begin
if num == curr
begin
set count = count + 1
end
else
begin
if count > 1
begin
if count - 1 != curr
begin
return false
end
end
set... | def check_pattern(string):
nums = string.split()
nums = [int(num) for num in nums]
curr = nums[0]
count = 1
for num in nums[1:]:
if num == curr:
count += 1
else:
if count > 1:
if count - 1 != curr:
return False
... | Python | flytech_python_25k |
import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from models import Question , Choice
class QuestionMethodTest extends TestCase
begin
function test_was_published_recently_with_future_question self
begin
string was_published_recently() should... | import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from .models import Question, Choice
class QuestionMethodTest(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() shoul... | Python | zaydzuhri_stack_edu_python |
comment S4 Python3 client library
comment Copyright 2016 Ontotext AD
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
comment... | # S4 Python3 client library
# Copyright 2016 Ontotext AD
#
# 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 by applicable law o... | Python | zaydzuhri_stack_edu_python |
function cblast_workflow npclient neuronlist npc prev_features=none iterations=0 use_saved_types=true customtypes=dict postprocess=call scaled_process 0.5 0.5 list 0.4 0.4 0.2 sort_types=true minconn=3 roi_restriction=none
begin
if customtypes is not none and type customtypes == DataFrame
begin
set customtypes = dicti... | def cblast_workflow(npclient, neuronlist, npc,
prev_features=None, iterations=0,
use_saved_types=True, customtypes={}, postprocess=features.scaled_process(0.5, 0.5, [0.4,0.4,0.2]),
sort_types=True, minconn=3, roi_restriction=None):
if customtypes is not None and type(customtypes) == pd.... | Python | nomic_cornstack_python_v1 |
function get_cpu self
begin
return _cpu
end function | def get_cpu(self):
return self._cpu | Python | nomic_cornstack_python_v1 |
function _check_session_persistence_info self info
begin
if info at string type == SESSION_PERSISTENCE_APP_COOKIE
begin
if not get info string cookie_name
begin
raise call ValueError call _ string 'cookie_name' should be specified for %s session persistence. % info at string type
end
end
else
if string cookie_name in i... | def _check_session_persistence_info(self, info):
if info['type'] == lb_const.SESSION_PERSISTENCE_APP_COOKIE:
if not info.get('cookie_name'):
raise ValueError(_("'cookie_name' should be specified for %s"
" session persistence.") % info['type'])
... | Python | nomic_cornstack_python_v1 |
comment 1. Проанализировать скорость и сложность одного - трёх любых алгоритмов,
comment разработанных в рамках домашнего задания первых трех уроков.
comment Примечание: Результаты анализа сохранить в виде комментариев в файле с кодом.
comment 4. Найти сумму n элементов следующего ряда чисел:
comment 1, -0.5, 0.25, -0.... | # 1. Проанализировать скорость и сложность одного - трёх любых алгоритмов,
# разработанных в рамках домашнего задания первых трех уроков.
# Примечание: Результаты анализа сохранить в виде комментариев в файле с кодом.
# 4. Найти сумму n элементов следующего ряда чисел:
# 1, -0.5, 0.25, -0.125, ...
# Количество элемент... | Python | zaydzuhri_stack_edu_python |
function _process_downloaded_queue self
begin
try
begin
while not call empty
begin
set downloaded_youtube_id = get _downloaded_queue
call register_song downloaded_youtube_id
end
end
except OSError as e
begin
comment TODO: .empty() can cause an "handle is closed" error during termination.
comment Really, termination sho... | def _process_downloaded_queue(self):
try:
while not self._downloaded_queue.empty():
downloaded_youtube_id = self._downloaded_queue.get()
self._available_song_ids.register_song(downloaded_youtube_id)
except OSError as e:
# TODO: .empty() can cause a... | Python | nomic_cornstack_python_v1 |
from numpy import *
comment m^2+n^2, 2mn, m^2-n^2
set LIM = 1500000
set Count = zeros LIM + 1 int
function GCD a b
begin
while b > 0
begin
set c = a - a / b * b
set a = b
set b = c
end
return a
end function
set m = 1
set M2 = 1
while 2 * M2 < LIM
begin
set n = m % 2 + 1
while 2 * M2 + 2 * m * n < LIM and n < m
begin
if... | from numpy import *
# m^2+n^2, 2mn, m^2-n^2
LIM = 1500000; Count = zeros(LIM+1, int);
def GCD(a,b):
while (b > 0):
c = a-(a/b)*b;
a = b;
b = c;
return a;
m = 1; M2 = 1;
while (2*M2 < LIM):
n = m%2+1;
while (2*M2+2*m*n < LIM) and (n < m):
if GCD(m,n) ==... | Python | zaydzuhri_stack_edu_python |
class Rectangle
begin
function __init__ self width length
begin
set width = width
set length = length
end function
function get_area self
begin
return length * width
end function
function get_perimeter self
begin
return 2 * length + width
end function
end class | class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def get_area(self):
return self.length * self.width
def get_perimeter(self):
return 2*(self.length + self.width) | Python | jtatman_500k |
import requests
set url_1 = string http://httpbin.org/headers
set url_2 = string http://httpbin.org/ip
set url_3 = string http://httpbin.org/html
set url_4 = string http://httpbin.org/json
set url_5 = string http://httpbin.org/xml
set get_1 = call request string GET url_1
set get_2 = call request string GET url_2
set g... | import requests
url_1 = "http://httpbin.org/headers"
url_2 = "http://httpbin.org/ip"
url_3 = "http://httpbin.org/html"
url_4 = "http://httpbin.org/json"
url_5 = "http://httpbin.org/xml"
get_1 = requests.request("GET", url_1)
get_2 = requests.request("GET", url_2)
get_3 = requests.request("GET", url_3)
get_4 = request... | Python | zaydzuhri_stack_edu_python |
from Subfunctions import PrepareData
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipel... | from Subfunctions import PrepareData
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipel... | Python | zaydzuhri_stack_edu_python |
import unittest
import itertools
import random
import time
from collections import deque
comment Python 2.7
seed time
comment configuration
set MAX_LENGTH = 5000
set MAX_HIT_RATE = 67.0
function palindromes seed
begin
string Generates random palindromes using the characters in the seed string. Starts by generating pali... | import unittest
import itertools
import random
import time
from collections import deque
# Python 2.7
random.seed(time.time())
# configuration
MAX_LENGTH=5000
MAX_HIT_RATE=67.0
def palindromes(seed):
"""
Generates random palindromes using the characters in the seed string.
Starts by generating palindrom... | Python | zaydzuhri_stack_edu_python |
function post_change_email self data=none
begin
return post change_email_url data
end function | def post_change_email(self, data=None):
return self.client.post(self.change_email_url, data) | Python | nomic_cornstack_python_v1 |
function from_multiword cls wordform index token
begin
set wordform = wordform
set tuple pos status_pos = call get_pos wordform pos
if string _ in lemma and length split lemma string _ == length split wordform string _
begin
set default_lemma = split lemma string _ at index
end
else
begin
set default_lemma = lemma
end
... | def from_multiword(cls, wordform, index, token):
wordform = wordform
pos, status_pos = Token.get_pos(wordform, token.pos)
if '_' in token.lemma and len(token.lemma.split('_')) == len(token.wordform.split('_')):
default_lemma = token.lemma.split('_')[index]
else:
... | Python | nomic_cornstack_python_v1 |
import glob
import os
import fnmatch
import shutil
import sys
function iterfindfiles path fnexp
begin
for tuple root dirs files in walk path
begin
for filename in filter files fnexp
begin
yield join path root filename
end
end
end function
set i = 0
for filename in call iterfindfiles string ./input/ string *.SRT
begin
s... | import glob
import os
import fnmatch
import shutil
import sys
def iterfindfiles(path, fnexp):
for root, dirs, files in os.walk(path):
for filename in fnmatch.filter(files, fnexp):
yield os.path.join(root, filename)
i=0
for filename in iterfindfiles(r"./input/", "*.SRT"):
i=i+1
newfil... | Python | zaydzuhri_stack_edu_python |
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
from Model.analysis import Analysis
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIVi... | from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
from Model.analysis import Analysis
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIVi... | Python | zaydzuhri_stack_edu_python |
function event_channel_name self
begin
return get pulumi self string event_channel_name
end function | def event_channel_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "event_channel_name") | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
class scoreboard
begin
string Keeps a record of the score for the game. Types: self.set_counter : int --> max number of sets in a game is 3 self.point_counter : list --> keeps record of order in which points are scored Perhaps conside... | import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
class scoreboard():
"""
Keeps a record of the score for the game.
Types:
self.set_counter : int --> max number of sets in a game is 3
self.point_counter : list --> keeps record of order in which points are scored... | Python | zaydzuhri_stack_edu_python |
function merge arr startL endL startR endR
begin
set temp = list
set i = startL
set j = startR
while i <= endL and j <= endR
begin
if arr at i > arr at j
begin
append temp arr at j
set j = j + 1
end
else
begin
append temp arr at i
set i = i + 1
end
end
while i <= endL
begin
append temp arr at i
set i = i + 1
end
while... | def merge(arr, startL, endL, startR, endR):
temp = []
i = startL
j = startR
while(i <= endL and j <= endR):
if(arr[i] > arr[j]):
temp.append(arr[j])
j += 1
else:
temp.append(arr[i])
i += 1
while(i <= endL):
temp.append(arr[i])
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import pickle
import trueskill
set logs = load pickle open string meta/FILTERED_LOGS.pkl
set scores = dict
for tuple _idx _log in enumerate logs
begin
set sub_1 = integer _log at string submission_1
set sub_2 = integer _log at string submission_2
set winner = _log at string winner
try
begi... | #!/usr/bin/env python
import pickle
import trueskill
logs = pickle.load(open("meta/FILTERED_LOGS.pkl"))
scores = {}
for _idx, _log in enumerate(logs):
sub_1 = int(_log['submission_1'])
sub_2 = int(_log['submission_2'])
winner = _log['winner']
try:
score_1 = scores[sub_1]
except:
... | Python | zaydzuhri_stack_edu_python |
string @Project: deep-learning-with-keras-notebooks @Package @author: ly @date Date: 2019年08月01日 15:46 @Description: @URL: https://blog.csdn.net/junjun150013652/article/details/81331448 @version: V1.0
import numpy as np
import tensorflow as tf
set n_steps = 2
set n_inputs = 3
set n_neurons = 5
set X = call placeholder ... | '''
@Project: deep-learning-with-keras-notebooks
@Package
@author: ly
@date Date: 2019年08月01日 15:46
@Description:
@URL: https://blog.csdn.net/junjun150013652/article/details/81331448
@version: V1.0
'''
import numpy as np
import tensorflow as tf
n_steps = 2
n_inputs = 3
n_neurons = 5
X = tf.placeholder( tf.float3... | Python | zaydzuhri_stack_edu_python |
string Solution to Project Euler 026: Reciprocal cycles. Author: Yuhuang Hu Email : duguyue100
import numpy as np
function get_reminder n d
begin
string Get reminder.
if n == 0
begin
return 0
end
while n < d
begin
set n = n * 10
end
return n % d
end function
set max_length = 0
set max_number = 2
for d in call xrange 2 ... | """Solution to Project Euler 026: Reciprocal cycles.
Author: Yuhuang Hu
Email : duguyue100
"""
import numpy as np
def get_reminder(n, d):
"""Get reminder."""
if n == 0:
return 0
while (n < d):
n *= 10
return n % d
max_length = 0
max_number = 2
for d in xrange(2, 1001):
n = 1
... | Python | zaydzuhri_stack_edu_python |
function write_review request
begin
set form = ReviewForm
if method == string POST
begin
set form_data = dict string title POST at string title ; string description POST at string description ; string author POST at string author
set form = call ReviewForm form_data
if is_valid
begin
save
call success request string Re... | def write_review(request):
form = ReviewForm
if request.method == 'POST':
form_data = {
'title': request.POST['title'],
'description': request.POST['description'],
'author': request.POST['author'],
}
form = ReviewForm(form_data)
if form.is_v... | Python | nomic_cornstack_python_v1 |
function evaluate self test
begin
print string Testing model over test set
set metrics = call run_evaluate_compound test
set msg = join string - list comprehension format string {} {} k v for tuple k v in items metrics
print string
print msg
return metrics
end function | def evaluate(self, test):
print("Testing model over test set")
metrics = self.run_evaluate_compound(test)
msg = " - ".join(["{} {}".format(k, v) for k, v in metrics.items()])
print("\n")
print(msg)
return metrics | Python | nomic_cornstack_python_v1 |
function export_to_binary self filepath
begin
with open filepath mode=string wb as file
begin
dump self file
end
end function | def export_to_binary(self, filepath: str) -> None:
with open(filepath, mode='wb') as file:
dump(self, file) | Python | nomic_cornstack_python_v1 |
from graphviz import Digraph
import pydot_ng as pydot
from knock41 import func41 , Chunk
string edges = [(1,2),(1,3),(1,4),(3,4)] g = pydot.graph_from_edges(edges) g.write_jpeg('graph_from_edges_dot.jpg',prog = 'dot')
string b(class Chunk) in line下で 掛かり先のChunkの表層形:ingword = b.getSurword() 掛かり元のChunkの表層形:edword = line[b... | from graphviz import Digraph
import pydot_ng as pydot
from knock41 import func41, Chunk
"""
edges = [(1,2),(1,3),(1,4),(3,4)]
g = pydot.graph_from_edges(edges)
g.write_jpeg('graph_from_edges_dot.jpg',prog = 'dot')
"""
"""
b(class Chunk) in line下で
掛かり先のChunkの表層形:ingword = b.getSurword()
掛かり元のChunkの表層形:edword = line[b.g... | Python | zaydzuhri_stack_edu_python |
function createTestSuite self testsuitename testprojectid details=none parentid=none order=none checkduplicatedname=true actiononduplicatedname=BLOCK devkey=none
begin
return call _query string tl.createTestSuite devKey=devkey testsuitename=testsuitename testprojectid=testprojectid details=details parentid=parentid ord... | def createTestSuite(self, testsuitename, testprojectid, details=None, parentid=None, order=None, checkduplicatedname=True, actiononduplicatedname=DuplicateStrategy.BLOCK, devkey=None):
return self._query("tl.createTestSuite",\
devKey=devkey,\
testsuitename=testsuitename,\... | Python | nomic_cornstack_python_v1 |
import re
import os
import sys
import time
import pandas
import argparse
global args
function process_options
begin
global args
set parser = call ArgumentParser description=string Analyze structure
call add_argument string -p string --psiblast_file help=string PSI-BLAST file
call add_argument string -s string --structu... | import re
import os
import sys
import time
import pandas
import argparse
global args
def process_options():
global args
parser = argparse.ArgumentParser(description='Analyze structure')
parser.add_argument('-p', '--psiblast_file', help='PSI-BLAST file')
parser.add_argument('-s', '--structure_file', h... | Python | zaydzuhri_stack_edu_python |
string 문제: 정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오. 입력: 첫째 줄에 N과 X가 주어진다. (1 ≤ N, X ≤ 10,000) 둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다. 출력: X보다 작은 수를 입력받은 순서대로 공백으로 구분해 출력한다. X보다 작은 수는 적어도 하나 존재한다.
set tuple N X = map int split input
set res = list split inpu... | '''
문제:
정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.
입력:
첫째 줄에 N과 X가 주어진다. (1 ≤ N, X ≤ 10,000)
둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다.
출력:
X보다 작은 수를 입력받은 순서대로 공백으로 구분해 출력한다. X보다 작은 수는 적어도 하나 존재한다.
'''
N, X = map(int, input().split())
res = list(input().split()... | Python | zaydzuhri_stack_edu_python |
function get self kf_id
begin
set st = get query kf_id
if st is none
begin
call abort 404 format string could not find {} `{}` string study kf_id
end
return call jsonify st
end function | def get(self, kf_id):
st = Study.query.get(kf_id)
if st is None:
abort(404, 'could not find {} `{}`'
.format('study', kf_id))
return StudySchema().jsonify(st) | Python | nomic_cornstack_python_v1 |
function get_rec_count files dialect
begin
set rec_cnt = - 1
for _ in reader input files dialect
begin
set rec_cnt = rec_cnt + 1
end
close fileinput
return rec_cnt
end function | def get_rec_count(files: List[str],
dialect: csv.Dialect) -> Tuple[Optional[int], int]:
rec_cnt = -1
for _ in csv.reader(fileinput.input(files), dialect):
rec_cnt += 1
fileinput.close()
return rec_cnt | Python | nomic_cornstack_python_v1 |
function load_file path
begin
string Load a txt data file
set path = call Path path
set data = read lines open
comment remove comments and empty lines
set data = list comprehension l for l in data if length strip l and not starts with l string #
comment determine data shape
set n = length data
set m = length split stri... | def load_file(path):
'''Load a txt data file'''
path = pathlib.Path(path)
data = path.open().readlines()
# remove comments and empty lines
data = [l for l in data if len(l.strip()) and not l.startswith("#")]
# determine data shape
n = len(data)
m = len(data[0].strip().split())
res = ... | Python | jtatman_500k |
function run self
begin
set public_key = if expression get config string Notebook then public_key else string
if get config string Notebook
begin
set security_group = call get_security_groups project_id project_id at 0
if get launch_spec string SecurityGroupIds
begin
set launch_spec at string SecurityGroupIds = launch... | def run(self):
public_key = SSH(self.project_id).public_key if self.config.get('Notebook') else ''
if self.config.get('Notebook'):
security_group = common.get_security_groups(self.project_id, self.project_id)[0]
if self.launch_spec.get('SecurityGroupIds'):
self.... | Python | nomic_cornstack_python_v1 |
comment Problem Link - https://leetcode.com/problems/merge-two-sorted-lists/
string 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example 1: Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,... | #Problem Link - https://leetcode.com/problems/merge-two-sorted-lists/
'''
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
E... | Python | zaydzuhri_stack_edu_python |
function history uid form_name=none timestamp=none
begin
set user_email = call user_retrieve_email uid
try
begin
set fuid = call friendly_user_id_getter uid
end
except Exception
begin
set fuid = none
end
set current_state = call user_retrieve_state uid
comment No form name given, show history.
if form_name is none
begi... | def history(uid, form_name=None, timestamp=None):
user_email = hobj.storage.user_retrieve_email(uid)
try:
fuid = hobj.friendly_user_id_getter(uid)
except Exception:
fuid = None
current_state = hobj.storage.user_retrieve_state(uid)
# No form name given,... | Python | nomic_cornstack_python_v1 |
function predict_one self state
begin
set state = reshape np state list 1 _input_dim
return predict _model state
end function | def predict_one(self, state):
state = np.reshape(state, [1, self._input_dim])
return self._model.predict(state) | Python | nomic_cornstack_python_v1 |
import speech_recognition as sr
import TTS.wrapper as w
function get_mic mic_name
begin
string Get the index of the given microphone in our list of microphones. If it's not found, instead set the index to be the first microphone found. :param mic_name: The given name of the microphone to get :return: The microphone ind... | import speech_recognition as sr
import TTS.wrapper as w
def get_mic(mic_name):
"""
Get the index of the given microphone in our list of microphones.
If it's not found, instead set the index to be the first microphone found.
:param mic_name: The given name of the microphone to get
:return: The micr... | Python | zaydzuhri_stack_edu_python |
function turn_on self
begin
call socket_command string 2F A0 01 00 F + string _zone
end function | def turn_on(self):
self.socket_command("2F A0 01 00 F" + str(self._zone)) | Python | nomic_cornstack_python_v1 |
string You live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each of the 10 stops on the way. How long will the bus journey take? Alternatively, you could run to university. You jog the first mile at 7mph; then run the next two at15mph; before jogging the last at 7mph again. Will this be qui... | '''
You live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each of the 10 stops on the way.
How long will the bus journey take? Alternatively, you could run to university. You jog the first mile at 7mph;
then run the next two at15mph; before jogging the last at 7mph again.
Will this be quicke... | Python | zaydzuhri_stack_edu_python |
function forward_pass self x
begin
set x = x
return x * x > 0
end function | def forward_pass(self, x):
self.x = x
return x * (x > 0) | Python | nomic_cornstack_python_v1 |
comment Location.py
comment ------------
comment Abstract class implementing a geographical location
comment ------------
from math import sin , cos , sqrt , atan2 , radians
class Location extends object
begin
function __init__ self _id _long _lat
begin
set idLoc = _id
set longitude = _long
set latitude = _lat
end func... | # Location.py
#------------
# Abstract class implementing a geographical location
#------------
from math import sin, cos, sqrt, atan2, radians
class Location(object):
def __init__(self, _id, _long, _lat):
self.idLoc = _id
self.longitude = _long
self.latitude = _lat
def getId(self):
... | Python | zaydzuhri_stack_edu_python |
function decode_and_resize image_str_tensor size
begin
comment Output a grayscale (channels=1) image
set image = call decode_jpeg image_str_tensor channels=3
comment Note resize expects a batch_size, but tf_map supresses that index,
comment thus we have to expand then squeeze. Resize returns float32 in the
comment rang... | def decode_and_resize(image_str_tensor, size):
# Output a grayscale (channels=1) image
image = tf.image.decode_jpeg(image_str_tensor, channels=3)
# Note resize expects a batch_size, but tf_map supresses that index,
# thus we have to expand then squeeze. Resize returns float32 in the
... | Python | nomic_cornstack_python_v1 |
set dd = dict string one 1 ; string two 2 ; string three 3
print length d
key in d
value in values d
print copy | dd = {"one":1, "two":2, "three":3}
print(len(d))
key in d
value in d.values()
print(d.copy)
| Python | zaydzuhri_stack_edu_python |
function is_prime num
begin
if num < 2
begin
return false
end
for i in range 2 integer num ^ 0.5 + 1
begin
if num % i == 0
begin
return false
end
end
return true
end function
function product_of_four_primes
begin
set primes = list
set num = 2
while length primes < 4
begin
if call is_prime num
begin
append primes num
e... | def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def product_of_four_primes():
primes = []
num = 2
while len(primes) < 4:
if is_prime(num):
primes.append(num)
num +... | Python | jtatman_500k |
import csv
import sys
import webbrowser
import collections as coll
function find_listings records user_id
begin
comment find listings of users
set listings = set
for row in records
begin
if row at 3 == user_id
begin
add listings row at 0
end
end
return listings
end function
function find_travelers records listings
begi... | import csv
import sys
import webbrowser
import collections as coll
def find_listings(records, user_id):
# find listings of users
listings = set()
for row in records:
if row[3] == user_id:
listings.add(row[0])
return listings
def find_travelers(records, listings):
# find fell... | Python | zaydzuhri_stack_edu_python |
function get_packages package
begin
return list comprehension dirpath for tuple dirpath dirnames filenames in walk package if exists path join path dirpath string __init__.py
end function | def get_packages(package):
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))] | Python | nomic_cornstack_python_v1 |
function vim_insert_mode_np cmd
begin
set v = call VimMode
call set_insert_mode_np
insert actions cmd
end function | def vim_insert_mode_np(cmd: str):
v = VimMode()
v.set_insert_mode_np()
actions.insert(cmd) | Python | nomic_cornstack_python_v1 |
function parseerror self msg line=none
begin
string Emit parse error and abort assembly.
if line is none
begin
set line = sline
end
error string parse error: + msg + format string on line {} line
exit - 2
end function | def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) | Python | jtatman_500k |
function validate_file_option self args
begin
comment see if user wants us to generate a file for each object
if not exists path output_path
begin
raise call DirNoExistError string Invalid path: %s % output_path
end
set output_path = output_path
end function | def validate_file_option(self, args):
# see if user wants us to generate a file for each object
if not os.path.exists(args.output_path):
raise ddlexceptions.DirNoExistError("Invalid path: %s" % args.output_path)
self.output_path = args.output_path
| Python | nomic_cornstack_python_v1 |
function _walk_dirs self
begin
for project_name in keys new_source_paths
begin
comment print "-------- Now mapping ---- " + project_name
set search_path = root + project_name + string \Data
for tuple dirpath subdirs files in walk search_path
begin
for file in files
begin
set new_source_paths at project_name at file = d... | def _walk_dirs(self):
for project_name in self.new_source_paths.keys():
# print "-------- Now mapping ---- " + project_name
search_path = self.root + project_name + '\\Data'
for dirpath, subdirs, files in os.walk(search_path):
for file in files:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
set __author__ = string Nikolay Nezhevenko <nikolay.nezhevenko@gmail.com>
string A multithreaded proxy checker Given a file containing proxies, per line, in the form of ip:port, will attempt to establish a connection through each proxy to a provided URL. Duration o... | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Nikolay Nezhevenko <nikolay.nezhevenko@gmail.com>"
""" A multithreaded proxy checker
Given a file containing proxies, per line, in the form of ip:port, will attempt
to establish a connection through each proxy to a provided URL. Duration of
connection attempts ... | Python | zaydzuhri_stack_edu_python |
function iter_chunked self n
begin
Ellipsis
end function | def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]:
... | 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.