code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
string Created on Thu Jul 17 20:20:42 2014 @author: Noah
from IPython.parallel import Client
import numpy as np
import time
from functools import partial
set n = 500
set m = 2500
set rc = call Client
set dview = rc at slice : :
function f_open n
begin
set f = dictionary
for ii in range ... | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 17 20:20:42 2014
@author: Noah
"""
from IPython.parallel import Client
import numpy as np
import time
from functools import partial
n = 500
m = 2500
rc = Client()
dview = rc[:]
def f_open(n):
f = dict()
for ii in range(n):
filename = 'R_%s' % ii
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python2
import commands
import re
import cgi , os | #!/usr/bin/python2
import commands
import re
import cgi, os
| Python | zaydzuhri_stack_edu_python |
function image self
begin
return call imread image_path
end function | def image(self):
return cv2.imread(self.image_path) | Python | nomic_cornstack_python_v1 |
function calculate_emissions tap_water_usage
begin
comment Constant multiplier for emissions
set emissions_multiplier = 0.9
comment Calculate carbon dioxide emissions
set emissions = emissions_multiplier * tap_water_usage
return emissions
end function
comment Call the function with 10 tons of tap water usage
set result... | def calculate_emissions(tap_water_usage):
# Constant multiplier for emissions
emissions_multiplier = 0.9
# Calculate carbon dioxide emissions
emissions = emissions_multiplier * tap_water_usage
return emissions
# Call the function with 10 tons of tap water usage
result = calculate_emissions(10)
prin... | Python | dbands_pythonMath |
function applyByNode requestContext seriesList nodeNum templateFunction newName=none
begin
string Takes a seriesList and applies some complicated function (described by a string), replacing templates with unique prefixes of keys from the seriesList (the key is all nodes up to the index given as `nodeNum`). If the `newN... | def applyByNode(requestContext, seriesList, nodeNum, templateFunction,
newName=None):
"""
Takes a seriesList and applies some complicated function (described by
a string), replacing templates with unique prefixes of keys from the
seriesList (the key is all nodes up to the index given as ... | Python | jtatman_500k |
function rglob self pattern
begin
set pattern = call casefold pattern
set tuple drv root pattern_parts = call parse_parts tuple pattern
if drv or root
begin
raise call NotImplementedError string Non-relative patterns are unsupported
end
set selector = call _make_selector tuple string ** + tuple pattern_parts
for p in c... | def rglob(self, pattern):
pattern = self._flavour.casefold(pattern)
drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
if drv or root:
raise NotImplementedError("Non-relative patterns are unsupported")
selector = _make_selector(("**",) + tuple(pattern_parts))
... | Python | nomic_cornstack_python_v1 |
function strip_codes s
begin
string Strip all color codes from a string. Returns empty string for "falsey" inputs.
return sub string if expression s or s == 0 then string s else string
end function | def strip_codes(s: Any) -> str:
""" Strip all color codes from a string.
Returns empty string for "falsey" inputs.
"""
return codepat.sub('', str(s) if (s or (s == 0)) else '') | Python | jtatman_500k |
function isEditable self dt
begin
Ellipsis
end function | def isEditable(self, dt: ghidra.program.model.data.DataType) -> bool:
... | Python | nomic_cornstack_python_v1 |
function run_IPS self boolean
begin
if boolean
begin
try
begin
set getInfodata = call running_thread call IPS_Updater InstrumentAddress=IPS_Instrumentadress string IPS string control_IPS
call connect store_data_ips
comment getInfodata.sig_visaerror.connect(self.printing)
comment getInfodata.sig_assertion.connect(self.p... | def run_IPS(self, boolean):
if boolean:
try:
getInfodata = self.running_thread(IPS_Updater(InstrumentAddress=IPS_Instrumentadress),'IPS', 'control_IPS')
getInfodata.sig_Infodata.connect(self.store_data_ips)
# getInfodata.sig_visaerror.connect(self.pr... | Python | nomic_cornstack_python_v1 |
function get_incorrect_email emails
begin
set email_txt = none
try
begin
for email_txt in emails
begin
call validate_email email_txt
end
end
except tuple ValueError AttributeError
begin
return email_txt
end
return none
end function | def get_incorrect_email(emails: List[str]) -> Optional[str]:
email_txt = None
try:
for email_txt in emails:
validate_email(email_txt)
except (ValueError, AttributeError):
return email_txt
return None | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string @author: Jim Huang @contact:Jim_Huang@trendmicr.com @version: 1.0.0 @license: Apache Licence @file: 1-13.py @time: 2020/11/19 10:53
comment 猴子吃桃
set peach = 1
for _ in range 9
begin
set peach = 2 * peach + 1
end
print peach | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jim Huang
@contact:Jim_Huang@trendmicr.com
@version: 1.0.0
@license: Apache Licence
@file: 1-13.py
@time: 2020/11/19 10:53
"""
# 猴子吃桃
peach = 1
for _ in range(9):
peach = 2 *(peach+1)
print(peach)
| Python | zaydzuhri_stack_edu_python |
function filter_existing_comparisons session run comparisons program version fragsize=none maxmatch=false kmersize=none minmatch=none
begin
set logger = call getLogger __name__
set existing_comparisons = call get_comparison_dict session
debug string Existing comparisons %s existing_comparisons
set comparisons_to_run = ... | def filter_existing_comparisons(
session,
run,
comparisons,
program,
version,
fragsize: Optional[int] = None,
maxmatch: Optional[bool] = False,
kmersize: Optional[int] = None,
minmatch: Optional[float] = None,
) -> List:
logger = logging.getLogger(__name__)
existing_comparis... | Python | nomic_cornstack_python_v1 |
function _get_db_data self
begin
log string _get_db_data
set data = list
set cursor = find helios_col
for entry in cursor
begin
set element = dict string start call millis_to_time integer entry at string start at slice 6 : - 2 : ; string geoHash entry at string point at string geohash at slice : 7 :
comment 'end': s... | def _get_db_data(self):
self.log("_get_db_data")
data = []
cursor = self.helios_col.find()
for entry in cursor:
element = {
'start': self.millis_to_time(int(entry['start'][6:-2])),
# 'end': self.millis_to_time(int(entry['end'][6:-2])),... | Python | nomic_cornstack_python_v1 |
function __mul__ self other
begin
if type other != InstanceType
begin
return call ProdFunction self call Const other
end
return call ProdFunction self other
end function | def __mul__(self, other):
if type(other) != types.InstanceType:
return ProdFunction(self, Const(other))
return ProdFunction(self, other) | Python | nomic_cornstack_python_v1 |
function get_execution_count self
begin
return 0
end function | def get_execution_count(self):
return 0 | Python | nomic_cornstack_python_v1 |
function watch_namespaced_pod_list_with_http_info self namespace **kwargs
begin
set all_params = list string namespace string pretty string label_selector string field_selector string watch string resource_version string timeout_seconds
append all_params string callback
append all_params string _return_http_data_only
s... | def watch_namespaced_pod_list_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
... | Python | nomic_cornstack_python_v1 |
function test_output_spell_error
begin
set output = call text_quality text=x
assert spell_error at 0 >= 0.14 and spell_error at 0 <= 0.16
end function | def test_output_spell_error():
output = text_quality(text=x)
assert output.spell_error[0]>=0.14 and output.spell_error[0]<=0.16 | Python | nomic_cornstack_python_v1 |
function __init__ __self__ config_map_key_ref=none field_ref=none resource_field_ref=none secret_key_ref=none
begin
if config_map_key_ref is not none
begin
set __self__ string config_map_key_ref config_map_key_ref
end
if field_ref is not none
begin
set __self__ string field_ref field_ref
end
if resource_field_ref is no... | def __init__(__self__, *,
config_map_key_ref: Optional['outputs.CSIIsilonSpecDriverControllerEnvsValueFromConfigMapKeyRef'] = None,
field_ref: Optional['outputs.CSIIsilonSpecDriverControllerEnvsValueFromFieldRef'] = None,
resource_field_ref: Optional['outputs.CSIIsilon... | Python | nomic_cornstack_python_v1 |
import argparse
import math
import sys
from collections import defaultdict
import csv
from ortools.sat.python import cp_model
function solve n_spheres n_piles num_search_workers
begin
set positioned = dict
set weights = list comprehension i + 1 ^ 3 for i in range n_spheres
comment If the sum of the sphere weights cann... | import argparse
import math
import sys
from collections import defaultdict
import csv
from ortools.sat.python import cp_model
def solve(n_spheres, n_piles, num_search_workers):
positioned = {}
weights = [(i + 1) ** 3 for i in range(n_spheres)]
# If the sum of the sphere weights cannot be evenly divided ... | Python | zaydzuhri_stack_edu_python |
function on_train_epoch_begin self run_context
begin
for cb in _callbacks
begin
call on_train_epoch_begin run_context
end
end function | def on_train_epoch_begin(self, run_context):
for cb in self._callbacks:
cb.on_train_epoch_begin(run_context) | Python | nomic_cornstack_python_v1 |
function promedioponderado pc1 pc2 pc3 pc4 ep ef
begin
set pp = pc1 + pc2 + pc3 + pc4 / 4 + ep + ef / 3
return pp
end function
function condicioncurso pp
begin
return if expression pp >= 12 then string aprobado else string desaprobado
end function
set aprobados = 0
set desaprobados = 0
for nota in Notas
begin
set nota ... | def promedioponderado(pc1,pc2,pc3,pc4,ep,ef) :
pp=(((pc1+pc2+pc3+pc4)/4)+ep+ef)/3
return pp
def condicioncurso(pp):
return"aprobado" if pp>=12 else "desaprobado"
aprobados=0
desaprobados=0
for nota in Notas:
nota["PP"]=promedioponderado(nota["PC1"],nota["PC2"],nota["PC3"],nota["PC4"],nota["EF"],nota["EP"]) | Python | zaydzuhri_stack_edu_python |
function GetImageURL value_1 value_2
begin
seed absolute value_1 + absolute value_2
comment Random number generation.
return random integer 1 1000000
end function | def GetImageURL(value_1, value_2):
seed(abs(value_1)+abs(value_2))
return randint(1, 1000000) #Random number generation. | Python | nomic_cornstack_python_v1 |
from car_manager_4 import Car
import unittest
class CarTest extends TestCase
begin
function setUp self
begin
set car = call Car 2007 string Mercedes 10 70
end function
function test_constructor self
begin
assert equal 2007 make
assert equal string Mercedes model
assert equal 10 fuel_consumption
assert equal 70 fuel_cap... | from car_manager_4 import Car
import unittest
class CarTest(unittest.TestCase):
def setUp(self) -> None:
self.car = Car(2007, "Mercedes", 10, 70)
def test_constructor(self):
self.assertEqual(2007, self.car.make)
self.assertEqual("Mercedes", self.car.model)
self.assertEqual(10... | Python | zaydzuhri_stack_edu_python |
function filter self predicate
begin
return call FilterChannel self predicate
end function | def filter(self, predicate):
return FilterChannel(self, predicate) | Python | nomic_cornstack_python_v1 |
function cancel self
begin
set cancelled = true
end function | def cancel(self):
self.cancelled = True | Python | nomic_cornstack_python_v1 |
function create_two_str self sent
begin
set words = split sent string
set window = string
if length words > 2
begin
comment load first 2 words in window
set window = window + format string {} {} words at 0 words at 1
comment add words to sentence starters
append sentence_starters window
comment reset window
set window... | def create_two_str(self, sent):
words = sent.split(' ')
window = ''
if len(words) > 2:
# load first 2 words in window
window += '{} {}'.format(words[0], words[1])
# add words to sentence starters
self.sentence_starters.append(window)
# reset window
window = ''... | Python | nomic_cornstack_python_v1 |
function on_success self data
begin
comment only want to collect English-language tweets
if data at string lang == string en
begin
append tweets data
print string received tweet # length tweets
end
with open string C:/Users/Rossco/desktop/twitter.txt string a encoding=string utf-8 as saveFile
begin
write saveFile strin... | def on_success(self, data):
# only want to collect English-language tweets
if data['lang'] == 'en':
tweets.append(data)
print("received tweet #", len(tweets))
with open('C:/Users/Rossco/desktop/twitter.txt','a', encoding='utf-8') as saveFile:
save... | Python | nomic_cornstack_python_v1 |
comment raise.py
function make_except
begin
print string 函数开始...
comment int("AAAAA") # int 函数内抛出异常
comment raise ValueError # 触发ValueError类型的异常
raise ZeroDivisionError
print string 函数结束
end function
try
begin
call make_except
print string make_except 调用完毕!
end
except ValueError
begin
print string make_except 函数调用发生异常
... | # raise.py
def make_except():
print("函数开始...")
# int("AAAAA") # int 函数内抛出异常
# raise ValueError # 触发ValueError类型的异常
raise ZeroDivisionError
print("函数结束")
try:
make_except()
print("make_except 调用完毕!")
except ValueError:
print("make_except 函数调用发生异常")
print("程序正常退出!")
| Python | zaydzuhri_stack_edu_python |
comment Para testar, basta executar o arquivo. Ele possui uma bateria de testes ao
comment final.
comment A.
comment Crie uma função que receba um inteiro com a quantidade de alunos e retorne
comment uma string na forma "O número de alunos é <qtd>". Se a quantidade de alunos
comment for maior que 10, no lugar de <qtd>,... | # Para testar, basta executar o arquivo. Ele possui uma bateria de testes ao
# final.
# A.
# Crie uma função que receba um inteiro com a quantidade de alunos e retorne
# uma string na forma "O número de alunos é <qtd>". Se a quantidade de alunos
# for maior que 10, no lugar de <qtd>, deve aparecer "muitos", senão, é ... | Python | zaydzuhri_stack_edu_python |
function setAllData self newdata daysList monthDates
begin
set listdata = newdata
set daysList = daysList
set monthDates = monthDates
call beginResetModel
call endResetModel
end function | def setAllData(self, newdata, daysList, monthDates):
self.listdata = newdata
self.daysList = daysList
self.monthDates = monthDates
self.beginResetModel()
self.endResetModel() | Python | nomic_cornstack_python_v1 |
import os
from sys import platform as plt
from argparse import ArgumentParser
from gtagger import gTagger
function parse_args
begin
set parser = call ArgumentParser description=string Tag metadata into song files
call add_argument string sources type=str nargs=string + help=string source file(s) or folder(s)
call add_a... | import os
from sys import platform as plt
from argparse import ArgumentParser
from .gtagger import gTagger
def parse_args():
parser = ArgumentParser(description='Tag metadata into song files')
parser.add_argument('sources', type=str, nargs='+', help='source file(s) or folder(s)')
parser.add_argument('--que... | Python | zaydzuhri_stack_edu_python |
function get_html_friendly_identifier self
begin
return replace replace identifier string . string _ string / string _
end function | def get_html_friendly_identifier(self):
return self.identifier.replace(".", "_").replace("/", "_") | Python | nomic_cornstack_python_v1 |
function next_window signals window_size stride
begin
set c_win = 0
while c_win + window_size <= length signals at 0
begin
set w = list comprehension list signals at i at slice c_win : c_win + window_size : for i in range length signals
yield list comprehension item for subsignal in w for item in subsignal
set c_win = ... | def next_window(signals, window_size, stride):
c_win = 0
while c_win + window_size <= len(signals[0]):
w = [list(signals[i][c_win:c_win + window_size])
for i in range(len(signals))]
yield [item for subsignal in w for item in subsignal]
c_win += stride | Python | nomic_cornstack_python_v1 |
function nfvi_reject_instance_action instance_uuid message context
begin
set cmd_id = call invoke_plugin string reject_instance_action instance_uuid message context
return cmd_id
end function | def nfvi_reject_instance_action(instance_uuid, message, context):
cmd_id = _compute_plugin.invoke_plugin('reject_instance_action',
instance_uuid, message, context)
return cmd_id | Python | nomic_cornstack_python_v1 |
comment scrapy模块的安装,常用指令实战,爬虫项目编写,使用scrapy编写当当网商品数据爬虫实战
comment scrapy模块的安装
comment 0-升级pip:python -m pip install --upgrade pip(网络安装)
comment 1-安装wheel :pip install wheel(网络安装)
comment 2-安装lxml(下载安装,下载后,进入改库的所在地,pip install 全文件名就可安装)
comment 3-安装twisted(下载安装)
comment 4-pip install scarpy(网络安装)
comment 5-下载安装pywin32并且配置... | #scrapy模块的安装,常用指令实战,爬虫项目编写,使用scrapy编写当当网商品数据爬虫实战
#scrapy模块的安装
#0-升级pip:python -m pip install --upgrade pip(网络安装)
#1-安装wheel :pip install wheel(网络安装)
#2-安装lxml(下载安装,下载后,进入改库的所在地,pip install 全文件名就可安装)
#3-安装twisted(下载安装)
#4-pip install scarpy(网络安装)
#5-下载安装pywin32并且配置(配置:将安装好的pywin32复制到c盘的window/system32中)
#scrapy的使用
#创建项... | Python | zaydzuhri_stack_edu_python |
function GetContentWindow self
begin
return call FindWindow string content
end function | def GetContentWindow(self):
return self.FindWindow("content") | Python | nomic_cornstack_python_v1 |
function _parseNumber raw type line_number line_text
begin
try
begin
return type raw
end
except ValueError
begin
raise call TimingSyntaxError string bad_ + __name__ tuple line_number line_text
end
end function | def _parseNumber(raw, type, line_number, line_text):
try:
return type(raw)
except ValueError:
raise TimingSyntaxError('bad_' + type.__name__, (line_number, line_text)) | Python | nomic_cornstack_python_v1 |
from typing import Union , TypeVar , Any
from math import sqrt
set Number = Union at tuple int float
class ComplexNumber
begin
function __init__ self real imaginary
begin
set real : Number = real
set imaginary : Number = imaginary
end function
function __eq__ self other
begin
if is instance other type self
begin
return... | from typing import Union, TypeVar, Any
from math import sqrt
Number = Union[int, float]
class ComplexNumber:
def __init__(self, real: Number, imaginary: Number):
self.real: Number = real
self.imaginary: Number = imaginary
def __eq__(self, other: object) -> bool:
if isinstance(other, ... | Python | zaydzuhri_stack_edu_python |
function set_result bool1
begin
if bool1 == false
begin
set result = 0
end
else
begin
set result = 1
end
return result
end function | def set_result(bool1):
if bool1 == False:
result = 0
else:
result = 1
return result
| Python | jtatman_500k |
function cli ctx device baud_rate address verbosity
begin
set obj at string device = device
set obj at string baud_rate = baud_rate
set obj at string address = address
comment set verbosity. Do it jankily because life is too short.
comment pylint: disable=eval-used
eval format string logger.setLevel(logging.{}) verbosi... | def cli(ctx,
device,
baud_rate,
address,
verbosity
):
ctx.obj['device'] = device
ctx.obj['baud_rate'] = baud_rate
ctx.obj['address'] = address
# set verbosity. Do it jankily because life is too short.
eval("logger.setLevel(logging.{})".format(verbosity)) #pylint: ... | Python | nomic_cornstack_python_v1 |
function slaveof self *args **kwargs
begin
raise call RedisClusterException string SLAVEOF is not supported in cluster mode
end function | def slaveof(self, *args, **kwargs) -> NoReturn:
raise RedisClusterException("SLAVEOF is not supported in cluster mode") | Python | nomic_cornstack_python_v1 |
function last_draw_stats self
begin
return dictionary comprehension k : last_draw_stats at k for tuple k v in items subsamplers if get attribute v string last_draw_stats none is not none
end function | def last_draw_stats(self):
return {k: v.last_draw_stats[k] for k, v in self.subsamplers.items()
if getattr(v, 'last_draw_stats', None) is not None} | Python | nomic_cornstack_python_v1 |
function get self request
begin
set params = query_params
comment look for the module mentioned, if it's there log the rating, if not then return
set mod = filter module=params at string module prof=params at string prof semester=params at string semester year=params at string year
if mod
begin
set rating = call Rating... | def get(self, request):
params = request.query_params
# look for the module mentioned, if it's there log the rating, if not then return
mod = ModuleInstance.objects.all().filter(module=params["module"], prof=params["prof"],
semester=params["seme... | Python | nomic_cornstack_python_v1 |
function _handle_template_end self
begin
string Handle the end of a template at the head of the string.
if _context ? TEMPLATE_NAME
begin
if not _context ? HAS_TEXT ? HAS_TEMPLATE
begin
call _fail_route
end
end
else
if _context ? TEMPLATE_PARAM_KEY
begin
call _emit_all call _pop
end
set _head = _head + 1
return call _p... | def _handle_template_end(self):
"""Handle the end of a template at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
elif self._context & contexts.TEMPLATE_PARAM... | Python | jtatman_500k |
function plot
begin
set view = get args string view string iso
comment delegating to celery because mayavi's plotting can't be done
comment on a flask thread.
comment fig = regression.plot(view)
set result = call delay view
try
begin
set fig = get result
end
except UntrainedException
begin
return string Error: please t... | def plot():
view = request.args.get("view", "iso")
# delegating to celery because mayavi's plotting can't be done
# on a flask thread.
# fig = regression.plot(view)
result = plot_async.delay(view)
try:
fig = result.get()
except regression.UntrainedException:
return "Error: pl... | Python | nomic_cornstack_python_v1 |
function enthalpy temp pres
begin
set g = call liq_g 0 0 temp pres
set g_t = call liq_g 1 0 temp pres
set h = g - temp * g_t
return h
end function | def enthalpy(temp,pres):
g = liq_g(0,0,temp,pres)
g_t = liq_g(1,0,temp,pres)
h = g - temp*g_t
return h | Python | nomic_cornstack_python_v1 |
function load_cells main_gt_data regions region_names
begin
set cells = dict
set cell_ids = unique main_gt_data at slice 1 : :
for cell_id in cell_ids
begin
set default cells cell_id dict
for tuple region region_name in zip regions region_names
begin
set indices = where call multiply main_gt_data region == cell_id
s... | def load_cells(main_gt_data, regions, region_names):
cells = {}
cell_ids = np.unique(main_gt_data)[1:]
for cell_id in cell_ids:
cells.setdefault(cell_id, {})
for region, region_name in zip(regions, region_names):
indices = np.where(np.multiply(main_gt_data, region) == cell_id)
... | Python | nomic_cornstack_python_v1 |
function resize image
begin
comment gets the current width and height of the image
set tuple height width = shape at slice : 2 :
comment don't resize if already the same width and height
if height != HEIGHT or width != WIDTH
begin
return call resize image tuple WIDTH HEIGHT
end
return image
end function | def resize(image):
# gets the current width and height of the image
height, width = image.shape[:2]
# don't resize if already the same width and height
if height != HEIGHT or width != WIDTH:
return cv2.resize(image, (WIDTH, HEIGHT))
return image | Python | nomic_cornstack_python_v1 |
function plot_msd msd h_exp
begin
set tuple fig ax = call subplots 1 2 figsize=tuple 10 10
set av_msd = mean np msd axis=0
for p in array range 0 shape at 0 step=1
begin
for t in array range 0 shape at 1 step=1
begin
plot t msd at tuple p t string bx
plot t av_msd at t string ro
end
end
call set_xlabel string Time lag ... | def plot_msd(msd, h_exp):
fig, ax = plt.subplots(1, 2, figsize = (10, 10))
av_msd = np.mean(msd, axis = 0)
for p in np.arange(0, msd.shape[0], step = 1):
for t in np.arange(0, msd.shape[1], step = 1):
ax[0].plot(t, msd[p, t], 'bx')
ax[1].plot(t, av_msd[t], 'ro')
ax[0].s... | Python | nomic_cornstack_python_v1 |
from typing import Dict
from address_converter import column_name_to_number
from xmlutils import XmlElement , try_parse
from cell import Cell
import src.excel.xlsx.workbook as wb
import src.excel.xlsx.sheet as st
class Row extends XmlElement
begin
function __init__ self sheet element
begin
call __init__ element
set _sh... | from typing import Dict
from .address_converter import column_name_to_number
from .xmlutils import XmlElement, try_parse
from .cell import Cell
import src.excel.xlsx.workbook as wb
import src.excel.xlsx.sheet as st
class Row(XmlElement):
def __init__(self, sheet: 'st.Sheet', element: XmlElement):
super()... | Python | zaydzuhri_stack_edu_python |
import copy
from data_manipulation_functions import normalise_data , get_data , prepare_data_for_predicting_price_considering_only_time , get_real_price_based_on_date , eliminate_unneccesary_fields_of_data
from validations import *
from matplotlib import pyplot as plt
function get_value_of_function sample slopes interc... | import copy
from data_manipulation_functions import normalise_data, get_data, prepare_data_for_predicting_price_considering_only_time,get_real_price_based_on_date,eliminate_unneccesary_fields_of_data
from validations import *
from matplotlib import pyplot as plt
def get_value_of_function(sample,slopes,intercept):... | Python | zaydzuhri_stack_edu_python |
comment 面试题68:树中两个节点的最低公共祖先
comment 1. 假如树是二叉搜索树
comment 二叉树的问题,一般要用递归解决。
comment 如果p,q都在root的左子树,则解就在左子树,反之解在右子树。
comment 如果p和q一个在左子树,一个在右子树,那么解就是root。
comment 这里无须区分到底找到的是p还是q,只要找到一个即可返回该结点。
comment 在某结点的左子树上找到了p,不继续深入查找了,在该结点右子树未找到q,题目保证一定有祖先,所以q一定在p的后代里。
comment 遍历到空节点表明没找到,遍历到p或者q就说明找到了,这是递归的两种边界情况。
comment 递归的主体如... | # 面试题68:树中两个节点的最低公共祖先
# 1. 假如树是二叉搜索树
# 二叉树的问题,一般要用递归解决。
# 如果p,q都在root的左子树,则解就在左子树,反之解在右子树。
# 如果p和q一个在左子树,一个在右子树,那么解就是root。
# 这里无须区分到底找到的是p还是q,只要找到一个即可返回该结点。
# 在某结点的左子树上找到了p,不继续深入查找了,在该结点右子树未找到q,题目保证一定有祖先,所以q一定在p的后代里。
# 遍历到空节点表明没找到,遍历到p或者q就说明找到了,这是递归的两种边界情况。
# 递归的主体如上所述,只在左子树上找到了则返回左子树,两棵子树都找到了则返回root。
# 由于递归的性质,遍历到... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class LabelEncoder
begin
function __init__ self starting_val=0
begin
set starting_val = starting_val
end function
function fit self data data_cols
begin
comment pass in string columns
if shape at 1 != length data_cols
begin
raise exception string Number of columns doesn't correspond to data shape.
en... | import numpy as np
class LabelEncoder:
def __init__(self, starting_val=0):
self.starting_val = starting_val
def fit(self, data, data_cols):
# pass in string columns
if data.shape[1] != len(data_cols):
raise Exception("Number of columns doesn't correspond to data shape.")
... | Python | zaydzuhri_stack_edu_python |
function _qti_gtab
begin
seed 123
set n_dir = 30
set hsph_initial = call HemiSphere theta=pi * call rand n_dir phi=2 * pi * call rand n_dir
set tuple hsph_updated _ = call disperse_charges hsph_initial 100
set directions = vertices
set bvecs = vertical stack list zeros 3 + list comprehension directions for _ in range 4... | def _qti_gtab():
np.random.seed(123)
n_dir = 30
hsph_initial = HemiSphere(
theta=np.pi * np.random.rand(n_dir),
phi=2 * np.pi * np.random.rand(n_dir))
hsph_updated, _ = disperse_charges(hsph_initial, 100)
directions = hsph_updated.vertices
bvecs = np.vstack([np.zeros(3)] + [direc... | Python | nomic_cornstack_python_v1 |
function test_names_pattern_column_MultiIndex df_multi
begin
with raises ValueError
begin
call pivot_longer index=string name names_pattern=string (.+)(.)
end
end function | def test_names_pattern_column_MultiIndex(df_multi):
with pytest.raises(ValueError):
df_multi.pivot_longer(index="name", names_pattern=r"(.+)(.)") | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set tuple a b = map str split input
append lst_letter a
append lst_code b
set l = length b
if l < Min
begin
set Min = l
end
end
set string = input
while length string > 0
begin
set temp = string at slice : Min :
set x = Min
while count lst_code temp == 0
begin
set temp = temp + string at x
set ... | for i in range(n):
a, b = map(str, input().split())
lst_letter.append(a)
lst_code.append(b)
l = len(b)
if l < Min:
Min = l
string = input()
while len(string) > 0:
temp = string[:Min]
x = Min
while lst_code.count(temp) == 0:
temp += string[x]
x += 1
out += lst... | Python | zaydzuhri_stack_edu_python |
comment Convolutional Neural Network
comment Same convolultion Formula:
string n_out = (n_in + 2p - K)/s + 1 n_in : no of input features n_out: no of output features k: convolution kernel size p: convolution padding size s: convolution stride size
import torch
import torch.nn as nn
import torch.optim as optim
import to... | # Convolutional Neural Network
# Same convolultion Formula:
'''
n_out = (n_in + 2p - K)/s + 1
n_in : no of input features
n_out: no of output features
k: convolution kernel size
p: convolution padding size
s: convolution stride size
'''
import torch
import torch.nn as nn
import torch.optim as... | Python | zaydzuhri_stack_edu_python |
from puzzle8 import *
set tiles = list 1 2 3 8 0 4 7 6 5
function numWrongTiles state
begin
set misplaced_tiles = 0
if state == 247893796
begin
return 0
end
else
begin
for i in range 9
begin
if call getTile state i == 0
begin
pass
end
else
if call getTile state i != tiles at i
begin
set misplaced_tiles = misplaced_tile... | from puzzle8 import *
tiles = [1, 2, 3, 8, 0, 4, 7, 6, 5]
def numWrongTiles(state):
misplaced_tiles = 0
if state == 247893796:
return 0
else:
for i in range(9):
if (getTile(state,i) == 0):
pass
elif (getTile(state, i) != tiles[i]):
m... | Python | zaydzuhri_stack_edu_python |
from collections import OrderedDict
from typing import Dict , Set , List
class Entities
begin
string Class of java object entity dependencies
function __init__ self file_path packages=none
begin
if packages is none
begin
set packages = list
end
set deps : Dict at tuple str Set at str = dict
set circular_deps : List a... | from collections import OrderedDict
from typing import Dict, Set, List
class Entities:
"""Class of java object entity dependencies"""
def __init__(self, file_path: str, packages=None):
if packages is None:
packages = []
self.deps: Dict[str, Set[str]] = {}
self.circular_dep... | Python | zaydzuhri_stack_edu_python |
function displayLiveVideo request sourceShortName=none
begin
set GET_ACTIVE_EPISODE_METHOD = call getClassByName XGDS_VIDEO_GET_ACTIVE_EPISODE
set episode = call GET_ACTIVE_EPISODE_METHOD
if not episode
begin
call add_message request ERROR string There is no live video.
return call redirect reverse string error
end
set... | def displayLiveVideo(request, sourceShortName=None):
GET_ACTIVE_EPISODE_METHOD = getClassByName(settings.XGDS_VIDEO_GET_ACTIVE_EPISODE)
episode = GET_ACTIVE_EPISODE_METHOD()
if not episode:
messages.add_message(request, messages.ERROR, 'There is no live video.')
return redirect(reverse('erro... | Python | nomic_cornstack_python_v1 |
comment Cross validation takes a number of different samples
comment So it is like running train_test_split multiple times
comment In order to eliminate some of the high variance of the estimates
comment Of out of sample predictions.
comment So it runs the model several times, with different samples each time
comment I... | #Cross validation takes a number of different samples
#So it is like running train_test_split multiple times
#In order to eliminate some of the high variance of the estimates
#Of out of sample predictions.
#So it runs the model several times, with different samples each time
#Imports
from sklearn.datasets import load... | Python | zaydzuhri_stack_edu_python |
from flask_login import UserMixin
from sqlalchemy.orm import relationship
from database import Base
from sqlalchemy import Column , String
class User extends Base UserMixin
begin
set __tablename__ = string users
set username = call Column call String 50 unique=true
set email = call Column call String 100 unique=true
se... | from flask_login import UserMixin
from sqlalchemy.orm import relationship
from .database import Base
from sqlalchemy import Column, String
class User(Base, UserMixin):
__tablename__ = 'users'
username = Column(String(50), unique=True)
email = Column(String(100), unique=True)
first_name = Column(Stri... | Python | zaydzuhri_stack_edu_python |
from PyQt5.QtCore import Qt , QRect , QPoint , QSize
import numpy as np
class CoordinateConverter
begin
set scrWidth = 400
set scrHeight = 400
set scale = 50
function __init__ self
begin
set centerX = scrWidth / 2
set centerY = scrHeight / 2
end function
function convertRectToScr self x y width height
begin
set left = ... | from PyQt5.QtCore import Qt, QRect, QPoint, QSize
import numpy as np
class CoordinateConverter:
scrWidth = 400
scrHeight = 400
scale = 50
def __init__(self):
self.centerX = CoordinateConverter.scrWidth / 2
self.centerY = CoordinateConverter.scrHeight / 2
def convertRectToScr(self... | Python | zaydzuhri_stack_edu_python |
string Script to plot results of SpinningUp Tests author: Chirag date: 14-02-2019
from matplotlib import pyplot as plt
import sys
import json
if length argv < 2
begin
print string Please enter the path of progress.txt as an argument
end
else
begin
set path = argv at 1
set title = string
with open path + string /config... | ''' Script to plot results of SpinningUp Tests author: Chirag date: 14-02-2019 '''
from matplotlib import pyplot as plt
import sys
import json
if len(sys.argv) < 2:
print('Please enter the path of progress.txt as an argument')
else:
path = sys.argv[1]
title = ''
with open(path + '/config.json', 'r') as config_file... | Python | zaydzuhri_stack_edu_python |
function chunks l n
begin
for i in range 0 length l n
begin
yield l at slice i : i + n :
end
end function | def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n] | Python | nomic_cornstack_python_v1 |
function merge_sort self
begin
function split_list base_list
begin
string Split original list into two lists.
if length base_list < 2
begin
return base_list
end
set middle = length base_list // 2
set front = call split_list base_list at slice : middle :
set back = call split_list base_list at slice middle : :
return ... | def merge_sort(self):
def split_list(base_list):
"""Split original list into two lists."""
if len(base_list) < 2:
return base_list
middle = len(base_list) // 2
front = split_list(base_list[:middle])
back = split_list(base_list[middle:]... | Python | nomic_cornstack_python_v1 |
comment Julio Claros
comment 114153234
comment 2018-05-11
comment Exercise
class ChessPiece
begin
function __init__ self name color rank file
begin
set name = name
set color = color
set rank = rank
set file = file
end function
function position self
begin
return tuple file rank
end function
function move self new_file ... | # Julio Claros
# 114153234
# 2018-05-11
# Exercise
class ChessPiece:
def __init__(self, name, color, rank, file):
self.name = name
self.color = color
self.rank = rank
self.file = file
def position(self):
return self.file, self.rank
def move(self, new_file, new_ra... | Python | zaydzuhri_stack_edu_python |
import rypto
set a = replace string 69 73 20 74 68 69 73 20 68 65 61 76 65 6e string string
set b = replace string 6e 6f 20 69 74 27 73 20 69 6f 77 61 21 21 string string
set c = call h2bin a
set d = call h2bin b | import rypto
a = '69 73 20 74 68 69 73 20 68 65 61 76 65 6e'.replace(' ','')
b = "6e 6f 20 69 74 27 73 20 69 6f 77 61 21 21".replace(' ','')
c = rypto.h2bin(a)
d = rypto.h2bin(b)
| Python | zaydzuhri_stack_edu_python |
function _on_update self value name
begin
set in_record = _out_records at all_record_names at name
set value
set tuple index field = _in_records at in_record
if tune_feedback_status is true
begin
try
begin
set offset_record = _offset_pvs at name
set value = value + get offset_record
end
except KeyError
begin
pass
end
e... | def _on_update(self, value, name):
in_record = self._out_records[self.all_record_names[name]]
in_record.set(value)
index, field = self._in_records[in_record]
if self.tune_feedback_status is True:
try:
offset_record = self._offset_pvs[name]
valu... | Python | nomic_cornstack_python_v1 |
from enum import Enum
class BaseLabel extends Enum
begin
string Utility class to inherit from and use as type hint/validation. Implementations: Labels, FormattedLabels
pass
end class
class Labels extends BaseLabel
begin
string Common application label implementations.
set DAMBROLOGY = string Dambrology
set NEW_STUDY = ... | from enum import Enum
class BaseLabel(Enum):
"""Utility class to inherit from and use as type hint/validation.
Implementations: Labels, FormattedLabels"""
pass
class Labels(BaseLabel):
"""Common application label implementations."""
DAMBROLOGY = 'Dambrology'
NEW_STUDY = 'Nuevo Estudio'
... | Python | zaydzuhri_stack_edu_python |
function get_position mass_sun mass_planet ecc semi mean_anomaly incl argument longitude delta_t=0.0 ? day
begin
set kepler = call new_kepler
call initialize_from_elements mass=mass_sun + mass_planet semi=semi ecc=ecc mean_anomaly=mean_anomaly
call transform_to_time time=delta_t
set r = call get_separation_vector
set v... | def get_position(mass_sun, mass_planet, ecc, semi, mean_anomaly, incl, argument, longitude, delta_t=0.|units.day):
kepler = new_kepler()
kepler.initialize_from_elements(mass=(mass_sun+mass_planet),
semi=semi,
ecc=ecc,
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string Output current weather
from lib import pywapi
import util
function get_weather loc=string 90034
begin
set weather = call get_weather_from_google loc
set fields = dict
try
begin
set h = right strip split weather at string current_conditions at string humidity at - 1 string %
set fields a... | #!/usr/bin/python
"Output current weather"
from lib import pywapi
import util
def get_weather(loc='90034'):
weather = pywapi.get_weather_from_google(loc)
fields = {}
try:
h = weather['current_conditions']['humidity'].split()[-1].rstrip('%')
fields['humidity'] = h
except:
pass
try:
wind = w... | Python | zaydzuhri_stack_edu_python |
function where_in self column wheres=list
begin
if not wheres
begin
set _wheres = _wheres + tuple call QueryExpression 0 string = 1 string value_equals
end
else
if is instance wheres QueryBuilder
begin
set _wheres = _wheres + tuple call QueryExpression column string IN call SubSelectExpression wheres
end
else
begin
set... | def where_in(self, column, wheres=[]):
if not wheres:
self._wheres += ((QueryExpression(0, "=", 1, "value_equals")),)
elif isinstance(wheres, QueryBuilder):
self._wheres += (
(QueryExpression(column, "IN", SubSelectExpression(wheres))),
)
else... | Python | nomic_cornstack_python_v1 |
from tkinter import *
from env_logic import *
import time
comment from random import *
set SIZE = 500
set GRID_LEN = 4
set GRID_PADDING = 10
set BACKGROUND_COLOR_GAME = string #92877d
set BACKGROUND_COLOR_CELL_EMPTY = string #9e948a
set BACKGROUND_COLOR_DICT = dict 2 string #eee4da ; 4 string #ede0c8 ; 8 string #f2b179... | from tkinter import *
from env_logic import *
import time
# from random import *
SIZE = 500
GRID_LEN = 4
GRID_PADDING = 10
BACKGROUND_COLOR_GAME = "#92877d"
BACKGROUND_COLOR_CELL_EMPTY = "#9e948a"
BACKGROUND_COLOR_DICT = { 2:"#eee4da", 4:"#ede0c8", 8:"#f2b179", 16:"#f59563", \
32:"#f67c5... | Python | zaydzuhri_stack_edu_python |
function load_ground_truth_tracks path=string /mnt/storage/beesbook/learning_data/learning_fragments_framediff17_dataset20150918_Truth.p N=none detection_feature_fn=none track_feature_fn=none
begin
set scale = 3.0 / 50.0
set static_H = array list list scale 0 0 list 0 scale 0 list 0 0 1.0 dtype=float32
with open path s... | def load_ground_truth_tracks(path="/mnt/storage/beesbook/learning_data/learning_fragments_framediff17_dataset20150918_Truth.p",
N=None,
detection_feature_fn=None,
track_feature_fn=None):
scale = 3.0 / 50.0
static_H... | Python | nomic_cornstack_python_v1 |
function configuration_job_properties_dependents_values_add_with_http_info self id value_id dependent_id dependent_job_property_value_id **kwargs
begin
set all_params = list string id string value_id string dependent_id string dependent_job_property_value_id
append all_params string callback
append all_params string _r... | def configuration_job_properties_dependents_values_add_with_http_info(self, id, value_id, dependent_id, dependent_job_property_value_id, **kwargs):
all_params = ['id', 'value_id', 'dependent_id', 'dependent_job_property_value_id']
all_params.append('callback')
all_params.append('_return_http_da... | Python | nomic_cornstack_python_v1 |
function cineTimeChanged self
begin
comment Insure timepoint is an integer (should always succeed, in place for possible errors)
try
begin
set new_timepoint = integer get cine_timepoint_cbox
end
except any
begin
return false
end
comment Import the cine model at the selected timepoint (updates landmarks)
call importCine... | def cineTimeChanged(self):
# Insure timepoint is an integer (should always succeed, in place for possible errors)
try:
new_timepoint = int(self.cine_timepoint_cbox.get())
except:
return(False)
# Import the cine model at the selected timepoint (updates landmarks)
self.mri_model.importCine(timepoint = new... | Python | nomic_cornstack_python_v1 |
comment Depth-first Search
comment You're given a Node class that has a name and an array of optional
comment children nodes. When put together, nodes form a simple tree-like
comment structure.
comment Implement the depthFirstSearch method on the Node class, which takes
comment in an empty array, traverses the tree usi... | #
# Depth-first Search
# You're given a Node class that has a name and an array of optional
# children nodes. When put together, nodes form a simple tree-like
# structure.
#
# Implement the depthFirstSearch method on the Node class, which takes
# in an empty array, traverses the tree using the Depth-first Search
# appr... | Python | zaydzuhri_stack_edu_python |
import turtle
function draw_example
begin
set window = call Screen
call bgcolor string black
comment brad
set brad = call Turtle
call shape string turtle
call color string black
call speed 2
call right 180
call forward 100
call color string white
call forward 200
call left 90
call forward 200
call left 90
call forward ... | import turtle
def draw_example():
window = turtle.Screen()
window.bgcolor("black")
#brad
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("black")
brad.speed(2)
brad.right(180)
brad.forward(100)
brad.color("white")
brad.forward(200)
brad.left(90)
brad.f... | Python | zaydzuhri_stack_edu_python |
function statistics
begin
return tuple call render_template string statistics.html 200
end function | def statistics():
return render_template('statistics.html'), 200 | Python | nomic_cornstack_python_v1 |
comment python "incrementing" a character string?
print character ordinal string a + 1
comment b | # python "incrementing" a character string?
print(chr(ord('a')+1))
# b
| Python | zaydzuhri_stack_edu_python |
function configure self attributes
begin
log string SquidConfiguration.configure started
if not enabled
begin
log string squid not enabled
log string SquidConfiguration.configure completed
return true
end
if ignored
begin
log string Ignored, returning True
log string SquidConfiguration.configure completed
return true
e... | def configure(self, attributes):
self.log('SquidConfiguration.configure started')
if not self.enabled:
self.log('squid not enabled')
self.log('SquidConfiguration.configure completed')
return True
if self.ignored:
self.log('Ignored, returning True... | Python | nomic_cornstack_python_v1 |
function GemInstall gem_list
begin
return execute list string gem string install + gem_list
end function | def GemInstall(gem_list):
return Execute(['gem', 'install'] + gem_list) | Python | nomic_cornstack_python_v1 |
comment save the vectorized reviews to future use
import json
import utils
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import re , string
from getarguments import file_city_name
comment get the corpus
with open string data/ + file_cit... | # save the vectorized reviews to future use
import json
import utils
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import re, string
from getarguments import file_city_name
# get the corpus
with open('data/' + file_city_name + '_users... | Python | zaydzuhri_stack_edu_python |
function collection_article user_id article_id
begin
set article = first filter by query db_session Article article_id=article_id
set result = all
if user_id == user_id
begin
return string fail
end
else
if length result > 0
begin
return string already
end
else
begin
set collection_article = call Collection_Article user... | def collection_article(user_id, article_id):
article = db_session.query(Article).filter_by(
article_id=article_id).first()
result = db_session.query(Collection_Article).filter(and_(
Collection_Article.user_id == user_id, Collection_Article.article_id == article_id)).all()
if article.user_id... | Python | nomic_cornstack_python_v1 |
function ul items
begin
return format string <ul>{}</ul> join string list comprehension format string <li>{}</li> x for x in items
end function
assert string <ul><li>One</li><li>Two</li><li>Three</li></ul> == call ul list string One string Two string Three | def ul(items):
return "<ul>{}</ul>".format("".join(["<li>{}</li>".format(x) for x in items]))
assert "<ul><li>One</li><li>Two</li><li>Three</li></ul>" == ul(['One', 'Two', 'Three']) | Python | zaydzuhri_stack_edu_python |
function list_reports
begin
return call _ensure_list call request string report/list at string reports at string report
end function | def list_reports():
return _ensure_list(request('report/list')['reports']['report']) | Python | nomic_cornstack_python_v1 |
function test_repeat_consumer_reg self
begin
set email = string test_repeat_consumer_reg@example.com
set consumer = call Consumer email=email consumer_zip_postal=string 12550 site_id=2
save
comment Different zip:
set post_data = dict string email email ; string consumer_zip_postal string 12601
set response = post rever... | def test_repeat_consumer_reg(self):
email = 'test_repeat_consumer_reg@example.com'
consumer = Consumer(email=email, consumer_zip_postal='12550',
site_id=2)
consumer.save()
# Different zip:
post_data = {'email': email, 'consumer_zip_postal': '12601'}
response ... | Python | nomic_cornstack_python_v1 |
import requests
import json
import random
import sys
set tag = argv at 1
set ratedlow = integer argv at 2
set ratedhigh = integer argv at 3
set alltags = list split tag string ,
set callurl = string
for i in range length alltags
begin
if i == 0
begin
set callurl = callurl + string tags= + alltags at i
end
else
begin
s... | import requests
import json
import random
import sys
tag=sys.argv[1]
ratedlow=int(sys.argv[2])
ratedhigh = int(sys.argv[3])
alltags=list(tag.split(","))
callurl=""
for i in range(len(alltags)):
if(i==0):
callurl=callurl + "tags="+alltags[i]
else:
callurl=callurl + ";"+alltags[i]
result=requests... | Python | zaydzuhri_stack_edu_python |
function test_defines_correct_capabilities self
begin
set dev = device string default.gaussian wires=1
set cap = call capabilities
set capabilities = dict string model string cv ; string supports_finite_shots true ; string returns_probs false ; string returns_state false ; string supports_analytic_computation true ; st... | def test_defines_correct_capabilities(self):
dev = qml.device("default.gaussian", wires=1)
cap = dev.capabilities()
capabilities = {
"model": "cv",
"supports_finite_shots": True,
"returns_probs": False,
"returns_state": False,
"support... | Python | nomic_cornstack_python_v1 |
import json
set user_data = dict string Name string John ; string Age 25 ; string City string New York
function store_user_data data
begin
with open string user_data.json string w as f
begin
dump data f
end
end function
function get_user_data
begin
with open string user_data.json as f
begin
return load json f
end
end f... | import json
user_data = {"Name": "John", "Age": 25, "City": "New York"}
def store_user_data(data):
with open('user_data.json', 'w') as f:
json.dump(data, f)
def get_user_data():
with open('user_data.json') as f:
return json.load(f)
# store data in JSON file
store_user_data(user_data)
# get ... | Python | iamtarun_python_18k_alpaca |
import socket
import json , time
from threading import Thread
import talking
import dbmanager
import crawler
from bs4 import BeautifulSoup
import requests
import re
import random
set PORT = 4455
set getWork = dumps dict string cmd string AnyWork
comment 'cmd':'found_sites',
comment 'parm':['www.fdsgf.de','https://fsfgd... | import socket
import json, time
from threading import Thread
import talking
import dbmanager
import crawler
from bs4 import BeautifulSoup
import requests
import re
import random
PORT = 4455
getWork = json.dumps({
'cmd':'AnyWork'
#'cmd':'found_sites',
#'parm':['www.fdsgf.de','https:... | Python | zaydzuhri_stack_edu_python |
comment The purpose of this program is to act as an implementation of RSA.
comment As such, it will generate two large primes p and q, then the public keys n and e, and the private key d.
comment From here users can input plaintext to encrypt with the created RSA system.
comment Created by Benjamin Ellis for the purpos... | # The purpose of this program is to act as an implementation of RSA.
# As such, it will generate two large primes p and q, then the public keys n and e, and the private key d.
# From here users can input plaintext to encrypt with the created RSA system.
# Created by Benjamin Ellis for the purpose of CS378 HW7.
# Du... | Python | zaydzuhri_stack_edu_python |
function NestedDictValues dictionary
begin
for value in values dictionary
begin
if is instance value dict
begin
yield from call NestedDictValues value
end
else
begin
yield value
end
end
end function | def NestedDictValues(dictionary):
for value in dictionary.values():
if isinstance(value, dict):
yield from NestedDictValues(value)
else:
yield value | Python | nomic_cornstack_python_v1 |
function get_2d_background object=string UDF_06001 clip=100
begin
import time
import numpy as np
import emcee
import unicorn.hudf as hudf
comment twod = unicorn.reduce.Interlace2D('PRIMO-1101_06001.2D.fits')
comment twod = unicorn.reduce.Interlace2D('UDF_06001.2D.fits')
set twod = call Interlace2D string %s.2D.fits % o... | def get_2d_background(object = 'UDF_06001', clip=100):
import time
import numpy as np
import emcee
import unicorn.hudf as hudf
#twod = unicorn.reduce.Interlace2D('PRIMO-1101_06001.2D.fits')
#twod = unicorn.reduce.Interlace2D('UDF_06001.2D.fits')
twod = unicorn.reduce.Interlace2D('%s.2D.fit... | Python | nomic_cornstack_python_v1 |
for i in primes
begin
if i in primes
begin
set m = integer i
while m < 334
begin
if i * m in primes
begin
remove primes i * m
end
set m = m + 1
end
end
end
print primes | for i in primes:
if i in primes:
m = int(i)
while m < 334:
if i*m in primes:
primes.remove(i*m)
m += 1
print(primes) | Python | zaydzuhri_stack_edu_python |
from deque import Deque
function pal_checker a_string
begin
set char_deque = deque
for ch in a_string
begin
call add_front ch
end
set match = true
while size char_deque > 1 and match
begin
if call remove_front != call remove_rear
begin
set match = false
end
end
return match
end function
print call pal_checker string ma... | from deque import Deque
def pal_checker(a_string):
char_deque = Deque()
for ch in a_string:
char_deque.add_front(ch)
match = True
while char_deque.size() > 1 and match:
if char_deque.remove_front() != char_deque.remove_rear():
match = False
return match
... | Python | zaydzuhri_stack_edu_python |
function admin_required func
begin
decorator wraps func
function decorated_view *args **kwargs
begin
if call get_current_user
begin
if not call is_current_user_admin
begin
comment Unauthorized
call abort 401
end
return call func *args keyword kwargs
end
return call redirect call create_login_url url
end function
return... | def admin_required(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if users.get_current_user():
if not users.is_current_user_admin():
abort(401) # Unauthorized
return func(*args, **kwargs)
return redirect(users.create_login_url(request.url))
... | Python | nomic_cornstack_python_v1 |
function single_source_shortest_path_length G source cutoff=none
begin
comment level (number of hops) when seen in BFS
set seen = dict
comment the current level
set level = 0
comment dict of nodes to check at next level
set nextlevel = dict source 1
while nextlevel
begin
comment advance to next level
set thislevel = n... | def single_source_shortest_path_length(G,source,cutoff=None):
seen={} # level (number of hops) when seen in BFS
level=0 # the current level
nextlevel={source:1} # dict of nodes to check at next level
while nextlevel:
thislevel=nextlevel # advance to next level... | Python | nomic_cornstack_python_v1 |
from urllib2 import urlopen
import csv
import db_connection
from query_helpers import drop_indices , add_indices
set SOURCE_URL = string https://nycopendata.socrata.com/api/views/xx67-kt59/rows.csv?accessType=DOWNLOAD
comment SOURCE_URL = "http://localhost:8000/data.csv"
function transform_row row
begin
string Adjusts ... | from urllib2 import urlopen
import csv
import db_connection
from query_helpers import drop_indices, add_indices
SOURCE_URL = "https://nycopendata.socrata.com/api/views/xx67-kt59/rows.csv?accessType=DOWNLOAD"
# SOURCE_URL = "http://localhost:8000/data.csv"
def transform_row(row):
"""Adjusts column names and value ... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.