code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _parseLine self line
begin
comment print '>>', line
comment print '>>', len(self), self
comment check if we need to remove the previous elements
if length self > 0
begin
del self at slice : :
end
comment end if
comment set self[0] to line
append self line
set NR = NR + 1
set NF = 0
set l = length self at 0
... | def _parseLine(self, line):
#print '>>', line
#print '>>', len(self), self
#check if we need to remove the previous elements
if len(self) > 0:
del self[:]
#end if
# set self[0] to line
self.append(line)
self.NR += 1
self.NF = 0
... | Python | nomic_cornstack_python_v1 |
class Piece
begin
string Piece clips the sprite into pieces to display on the board
function __init__ self pieceinfo chess_coord square_width square_height
begin
comment pieceinfo is a string such as 'Qb'. The Q represents Queen and b
comment shows the fact that it is black:
set piece = pieceinfo at 0
set color = piece... | class Piece:
"""
Piece clips the sprite into pieces to display on the board
"""
def __init__(self,pieceinfo,chess_coord,square_width, square_height):
# pieceinfo is a string such as 'Qb'. The Q represents Queen and b
# shows the fact that it is black:
piece = pieceinfo[0]
... | Python | zaydzuhri_stack_edu_python |
comment ! /bin/env python
import argparse
from ete3 import Tree , NodeStyle , TreeStyle , TextFace , add_face_to_node
function outfile2seqs outfile=string outfile
begin
string Give me a phylip dnapars outfile and I''ll give you a dictionary of sequences, including ancestral, and a dictionary of parent assignments with ... | #! /bin/env python
import argparse
from ete3 import Tree, NodeStyle, TreeStyle, TextFace, add_face_to_node
def outfile2seqs(outfile='outfile'):
"""
Give me a phylip dnapars outfile and I''ll give you a dictionary of sequences,
including ancestral, and a dictionary of parent assignments with branch length... | Python | zaydzuhri_stack_edu_python |
function _parse_date_default_value property_name default_value_string
begin
string Parse and return the default value for a date property.
comment OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually
comment and then turn it into a python datetime object. strptime() will raise an exception
com... | def _parse_date_default_value(property_name, default_value_string):
"""Parse and return the default value for a date property."""
# OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually
# and then turn it into a python datetime object. strptime() will raise an exception
# if the... | Python | jtatman_500k |
function toggle_pacing self
begin
comment Toggles if we are pacing
set not get is_pacing
comment If we are now pacing
if get is_pacing
begin
comment Start pacing command code
call send_data string start-pace
comment Send customisation network update
call send_customisations
comment Switch the toggle button
call config ... | def toggle_pacing(self):
# Toggles if we are pacing
self.is_pacing.set(not self.is_pacing.get())
# If we are now pacing
if self.is_pacing.get():
# Start pacing command code
self.client.send_data("start-pace")
# Send customisation network update
... | Python | nomic_cornstack_python_v1 |
function localization_paths self language_filter
begin
comment general
for basedir in __basedirs
begin
set dir_filter = lambda d -> d in __ignore
for path in call __localization_path basedir language_filter dir_filter
begin
yield path
end
end
comment the locale is the directory name
set lps = list
comment CUPS, Fedora... | def localization_paths(self, language_filter):
#
# general
#
for basedir in self.__basedirs:
dir_filter = lambda d: d in self.__ignore
for path in self.__localization_path(basedir, language_filter, dir_filter):
yield path
#
# the ... | Python | nomic_cornstack_python_v1 |
function find_by_campaign campaign_id _connection=none page_size=100 page_number=0 sort_by=DEFAULT_SORT_BY sort_order=DEFAULT_SORT_ORDER
begin
string List all videos for a given campaign.
return call ItemResultSet string find_videos_by_campaign_id Video _connection page_size page_number sort_by sort_order campaign_id=c... | def find_by_campaign(campaign_id, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos for a given campaign.
"""
return connection.ItemResultSet(
'find_videos_by_campaign_id', ... | Python | jtatman_500k |
string This code finds the jacobi constant from given files.
comment standard modules
import os
import shutil
comment external modules
comment relative Modules
from misc.colours import _RST_ , OKBLUE
from misc.functions import typecheck , list_comp , addspace , strip
from import check_file
comment global attributes
se... | """This code finds the jacobi constant from given files."""
# standard modules
import os
import shutil
# external modules
# relative Modules
from ..misc.colours import _RST_, OKBLUE
from ..misc.functions import typecheck, list_comp, addspace, strip
from . import check_file
# global attributes
__all__ = ('copytree',... | Python | zaydzuhri_stack_edu_python |
for i in range M
begin
set ele = list
set ele = split input
append a list map lambda x -> integer x ele
end
set L_temp = split input
set L = list map lambda x -> integer x L_temp
comment print(M,"",N)
comment print(a)
comment print(L)
set b = list
for i in range M
begin
set ele = list
for j in range N
begin
append e... | for i in range(M):
ele = []
ele = input().split()
a.append(list(map(lambda x: int(x), ele)))
L_temp = input().split()
L = list(map(lambda x: int(x), L_temp))
#print(M,"",N)
#print(a)
#print(L)
b = []
for i in range(M):
ele = []
for j in range(N):
ele.append(0)
b.append(ele)
#... | Python | zaydzuhri_stack_edu_python |
set num = list comprehension i for i in input
set origin = list comprehension j for j in num
reverse num
print num == origin | num=[i for i in input()]
origin=[j for j in num]
num.reverse()
print(num==origin) | Python | zaydzuhri_stack_edu_python |
function render *args **kwargs
begin
with call queries_disabled
begin
set response = call django_render *args keyword kwargs
end
return response
end function | def render(*args, **kwargs):
with queries_disabled():
response = django_render(*args, **kwargs)
return response | Python | nomic_cornstack_python_v1 |
function deleteSchema self schemaId
begin
string Delete a schema. Parameter: schemaId (string). Throws APIException on failure.
set req = oneSchemaUrl % tuple host string /draft schemaId
set resp = delete req auth=credentials verify=verify
if status_code == 204
begin
debug string Schema deleted
end
else
begin
raise cal... | def deleteSchema(self, schemaId):
"""
Delete a schema. Parameter: schemaId (string). Throws APIException on failure.
"""
req = ApiClient.oneSchemaUrl % (self.host, "/draft", schemaId)
resp = requests.delete(req, auth=self.credentials, verify=self.verify)
if resp.status_c... | Python | jtatman_500k |
function loadSettingsFromPriceBarChartSettings self priceBarChartSettings lineSegmentNumberType=1
begin
debug string Entered loadSettingsFromPriceBarChartSettings()
if lineSegmentNumberType == 1
begin
comment Width of the horizontal bar drawn.
set lineSegmentGraphicsItemBarWidth = lineSegment1GraphicsItemBarWidth
comme... | def loadSettingsFromPriceBarChartSettings(self, priceBarChartSettings,
lineSegmentNumberType=1):
self.log.debug("Entered loadSettingsFromPriceBarChartSettings()")
if lineSegmentNumberType == 1:
# Width of the horizontal bar... | Python | nomic_cornstack_python_v1 |
comment !/usr/local/bin/python3
function cable_master n k l
begin
set s = round sum l / k 2
set d = round sum l / k / 2 2
function count v
begin
set c = 0
for e in l
begin
set c = c + e // v
end
return c
end function
while true
begin
set c = count s
if d <= 0.01
begin
break
end
if c < k
begin
set s = round s - d 2
end
... | #!/usr/local/bin/python3
def cable_master(n, k, l):
s = round(sum(l) / k, 2)
d = round(sum(l) / k / 2, 2)
def count(v):
c = 0
for e in l:
c += e // v
return c
while True:
c = count(s)
if d <= 0.01:
break
if c < k:
s ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from bottle import get , post , run , request , template
import serial
decorator get string /
function index
begin
return call template string index
end function
decorator post string /cmd
comment 这个是 客户端请求 服务端就发给一个 index.html 控制界面给客户端
function cmd
begin
comment 打开串口
comment 串口
set serialP... | # -*- coding: utf-8 -*-
from bottle import get,post,run,request,template
import serial
@get("/")
def index():
return template("index")
#### 这个是 客户端请求 服务端就发给一个 index.html 控制界面给客户端
@post("/cmd")
def cmd():
#打开串口
serialPort="/dev/ttyAMA0" #串口
baudRate=9600 #波特率
ser=serial.Serial(serialPort,b... | Python | zaydzuhri_stack_edu_python |
import json
import matplotlib.pyplot as plt
import numpy as np
from scripts.scripts_util import read_experiment_result_df
function draw_line_figure bin_list name_list
begin
set bin_list = list comprehension list sorted items bin key=lambda kv -> kv at 0 for bin in bin_list
set items_list = list comprehension list compr... | import json
import matplotlib.pyplot as plt
import numpy as np
from scripts.scripts_util import read_experiment_result_df
def draw_line_figure(bin_list, name_list):
bin_list = [list(sorted(bin.items(), key=lambda kv: kv[0])) for bin in bin_list]
items_list = [[(transform_bin_length(k), v) for k, v in bin] fo... | Python | zaydzuhri_stack_edu_python |
import utility
import unittest
function count_leaves t
begin
return accumulate lambda x y -> x + y 0 map lambda x -> 1 t
end function
class UnitTestOfAboveFunctions extends TestCase
begin
function test_case1 self
begin
assert equal call count_leaves list 0
assert equal call count_leaves list 1 2 3 4 5 5
end function
en... | import utility
import unittest
def count_leaves(t):
return utility.accumulate(lambda x, y: x + y, 0,
utility.map(lambda x: 1, t))
class UnitTestOfAboveFunctions(unittest.TestCase):
def test_case1(self):
self.assertEqual(count_leaves(utility.list()), 0)
self.asse... | Python | zaydzuhri_stack_edu_python |
function get_source_local
begin
if not is file path CONFIG_FILE
begin
return string
end
set source = load yaml open CONFIG_FILE at string source
if is instance source dict
begin
return source at string local
end
else
begin
return string
end
end function | def get_source_local():
if not os.path.isfile(CONFIG_FILE):
return ""
source = yaml.load(open(CONFIG_FILE))['source']
if isinstance(source, dict):
return source['local']
else:
return "" | Python | nomic_cornstack_python_v1 |
function args **kwargs
begin
string allows us to temporarily override all the special keyword parameters in a with context
set kwargs_str = join string , list comprehension string %s=%r % tuple k v for tuple k v in items kwargs
raise call DeprecationWarning format string sh.args() has been deprecated because it was nev... | def args(**kwargs):
""" allows us to temporarily override all the special keyword parameters in
a with context """
kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()])
raise DeprecationWarning("""
sh.args() has been deprecated because it was never thread safe. use the
following instead... | Python | jtatman_500k |
function test_worktree_prunes_worktree_on_failure repository
begin
set branch = call create string branch
with raises Exception match=string Boom
begin
with call worktree branch as worktree
begin
raise exception string Boom
end
end
set privatedir = path / string .git / string worktrees / name
assert not exists privated... | def test_worktree_prunes_worktree_on_failure(repository: Repository) -> None:
branch = repository.heads.create("branch")
with pytest.raises(Exception, match="Boom"):
with repository.worktree(branch) as worktree:
raise Exception("Boom")
privatedir = repository.path / ".git" / "worktrees... | Python | nomic_cornstack_python_v1 |
for i in range length s1
begin
for j in range 32 128
begin
if character j ? 117 == s1 at i and character j ? 4294967275 == s2 at i
begin
append result character j
end
end
end
print join string result | for i in range(len(s1)):
for j in range(32, 128):
if chr(j & 0x75) == s1[i] and chr(j & 0xffffffeb) == s2[i]:
result.append(chr(j))
print("".join(result))
| Python | zaydzuhri_stack_edu_python |
function testSumMagnitudesCatalog self
begin
set catName = string galaxiesWithHoles.txt
set obs_metadata = call ObservationMetaData mjd=50000.0 boundType=string circle unrefractedRA=0.0 unrefractedDec=0.0 boundLength=10.0
set test_cat = call galaxiesWithHoles galaxy obs_metadata=obs_metadata
call write_catalog catName
... | def testSumMagnitudesCatalog(self):
catName = 'galaxiesWithHoles.txt'
obs_metadata=ObservationMetaData(mjd=50000.0,
boundType='circle',unrefractedRA=0.0,unrefractedDec=0.0,
boundLength=10.0)
test_cat=galaxiesWithHoles(self.galaxy,obs... | Python | nomic_cornstack_python_v1 |
import time
import io
import contextlib
import inspect
import pandas as pd
set methods_list = list
import sys
class decorator_2
begin
function __init__ self meth
begin
comment self.f = open("D:\\err.txt", "a")
comment sys.stderr = self.f
set meth = meth
set counter = 0
end function
function __call__ self *args **kwarg... | import time
import io
import contextlib
import inspect
import pandas as pd
methods_list = []
import sys
class decorator_2:
def __init__(self, meth):
# self.f = open("D:\\err.txt", "a")
# sys.stderr = self.f
self.meth = meth
decorator_2.counter = 0
def __call__(self, *args, **... | Python | zaydzuhri_stack_edu_python |
for line in input_file
begin
print line
end
close input_file | for line in input_file:
print(line)
input_file.close() | Python | zaydzuhri_stack_edu_python |
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql import Row , Column
import pandas as pd
import numpy as np
import time
from pyspark.sql.functions import when , log , exp
from pyspark.ml.feature import StringIndexer , OneHotEncoderEstimator
set spark = call getOrCreate
set sc = sparkContext
call set... | import pyspark
from pyspark.sql import SparkSession
from pyspark.sql import Row,Column
import pandas as pd
import numpy as np
import time
from pyspark.sql.functions import when,log,exp
from pyspark.ml.feature import StringIndexer,OneHotEncoderEstimator
spark = SparkSession.builder \
.master("local[2]") \
.appN... | Python | zaydzuhri_stack_edu_python |
function _reporter_from_storage storage check_exist=true
begin
if is instance storage str
begin
comment Open a reporter to read the data.
set reporter = call MultiStateReporter storage
end
else
begin
set reporter = storage
end
comment Check if netcdf file exists.
if check_exist and not call storage_exists
begin
raise c... | def _reporter_from_storage(storage, check_exist=True):
if isinstance(storage, str):
# Open a reporter to read the data.
reporter = multistate.MultiStateReporter(storage)
else:
reporter = storage
# Check if netcdf file exists.
if check_exist and not re... | Python | nomic_cornstack_python_v1 |
function _config_bay bay baymodel cfg_dir force=false
begin
if coe == string kubernetes
begin
return call _config_bay_kubernetes bay baymodel cfg_dir force
end
else
if coe == string swarm
begin
return call _config_bay_swarm bay baymodel cfg_dir force
end
end function | def _config_bay(bay, baymodel, cfg_dir, force=False):
if baymodel.coe == 'kubernetes':
return _config_bay_kubernetes(bay, baymodel, cfg_dir, force)
elif baymodel.coe == 'swarm':
return _config_bay_swarm(bay, baymodel, cfg_dir, force) | Python | nomic_cornstack_python_v1 |
if not limit
begin
set limit = string 4
end
set limit = integer limit
while true
begin
if counter == limit
begin
break
end
if counter % 2 != 0
begin
print counter end=string
end
set counter = counter + 1
end
print string Fin | if not limit:
limit='4'
limit=int(limit)
while True:
if counter==limit:
break
if counter%2!=0:
print(counter, end=" ")
counter+=1
print('\n''Fin') | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jan 22 14:03:28 2019 @author: cnh17
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hilbert , butter , filtfilt , chirp
from scipy.optimize import curve_fit
import scipy.fftpack as spf
import os
import pylab as pl
set path = string /Users/S... | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 14:03:28 2019
@author: cnh17
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hilbert,butter,filtfilt,chirp
from scipy.optimize import curve_fit
import scipy.fftpack as spf
import os
import pylab as pl
path = "/Users/ShaunGan/Desktop/in... | Python | zaydzuhri_stack_edu_python |
function graph_passages_proches jointure groupe_pl_rappro
begin
set cam_proche_liste = count group by groupe_pl_rappro string liste_passag_faux at string state
set cam_proche_liste_triee = reset index sort values cam_proche_liste ascending=false
set base = encode call Chart jointure x=call X string camera_id:N axis=axi... | def graph_passages_proches(jointure, groupe_pl_rappro):
cam_proche_liste=groupe_pl_rappro.groupby('liste_passag_faux').count()['state']
cam_proche_liste_triee=cam_proche_liste.sort_values(ascending=False).reset_index()
base=alt.Chart(jointure).encode(x=alt.X('camera_id:N', axis=alt.Axis(title='num caméra... | Python | nomic_cornstack_python_v1 |
from Pages.base_page_object import BasePage
from Locators.ProductLocators import ProductLocators
from Objects.product import Product
import logging
class ProductPage extends BasePage
begin
function __init__ self driver
begin
call __init__ driver
end function
function add_product_to_cart self index
begin
comment print("... | from Pages.base_page_object import BasePage
from Locators.ProductLocators import ProductLocators
from Objects.product import Product
import logging
class ProductPage(BasePage):
def __init__(self, driver):
super().__init__(driver)
def add_product_to_cart(self, index):
# print("Productpage:" +... | Python | zaydzuhri_stack_edu_python |
function get_system_boot_once self type=string current
begin
set result = dict
try
begin
if type == none
begin
set type = string current
end
if type not in list string current string allow
begin
return dict string ret false ; string msg string Type '%s' is not correct. % type
end
set system_url = call _find_system_res... | def get_system_boot_once(self, type='current'):
result = {}
try:
if type == None:
type = 'current'
if type not in ['current', 'allow']:
return {'ret': False, 'msg': "Type '%s' is not correct." % type}
system_url = self._find_system_reso... | Python | nomic_cornstack_python_v1 |
function download_image_thumbnail image_url main_directory dir_name return_image_name print_urls socket_timeout print_size no_download
begin
if print_urls or no_download
begin
info string Image URL: %s % image_url
end
if no_download
begin
return tuple string success string Printed url without downloading
end
try
begin
... | def download_image_thumbnail(image_url, main_directory, dir_name, return_image_name, print_urls,
socket_timeout, print_size, no_download):
if print_urls or no_download:
logging.info("Image URL: %s" % image_url)
if no_download:
return "success", "P... | Python | nomic_cornstack_python_v1 |
function check_if_sound_card_exists
begin
try
begin
set snd_cards = call run_shell_cmd string cat /proc/asound/cards
end
except Exception
begin
return false
end
return not string no soundcards in join string snd_cards
end function | def check_if_sound_card_exists():
try:
snd_cards = run_shell_cmd('cat /proc/asound/cards')
except Exception:
return False
return not 'no soundcards' in '\n'.join(snd_cards) | Python | nomic_cornstack_python_v1 |
function test_with_wrong_data self
begin
append buff string
append buff string .. raw:: html
append buff string
append buff string <p>foo<b>bar</p>baz</b>
append buff string
post
assert equal post string There are errors in generated document
end function | def test_with_wrong_data(self):
self.obj.buff.append('')
self.obj.buff.append('.. raw:: html')
self.obj.buff.append('')
self.obj.buff.append(' <p>foo<b>bar</p>baz</b>')
self.obj.buff.append('')
self.obj.post()
self.assertEqual(self.obj.post(),
... | Python | nomic_cornstack_python_v1 |
comment 33
comment ABOUT: CRUD OPERATIONS USING PYTHON CLASS
comment MYSQL Adapatation of article
comment https://www.codeproject.com/Articles/1275121/CRUD-Operations-in-Python-with-SQL-Database
comment written using python 2.+
comment can easily be written in 3+
comment 33
comment database table
comment CREATE TABLE `... | ################################################33
# ABOUT: CRUD OPERATIONS USING PYTHON CLASS
# MYSQL Adapatation of article
# https://www.codeproject.com/Articles/1275121/CRUD-Operations-in-Python-with-SQL-Database
# written using python 2.+
# can easily be written in 3+
##############################################... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import time
import urllib2
set COLLECTION_INTERVAL = 300
set CITIES = list string Beijing string Cambridge string Farnham string Koeln string Sebastopol string Tokyo
set WEATHER_API = string http://citytemp.effectivemonitoring.info/get
function get_temperature city scale=string c
beg... | #!/usr/bin/python
import sys
import time
import urllib2
COLLECTION_INTERVAL = 300
CITIES = ['Beijing', 'Cambridge', 'Farnham', 'Koeln', 'Sebastopol', 'Tokyo']
WEATHER_API = 'http://citytemp.effectivemonitoring.info/get'
def get_temperature(city, scale='c'):
"""Get temperature for a city."""
city_url = WEATHER... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import setuptools
comment To prevent importing about and thereby breaking the coverage info we use this
comment exec hack
set about = dict
with open string python_utils/__about__.py as fp
begin
exec read fp about
end
if is file path string README.rst
begin
set long_description = read open string R... | import os
import sys
import setuptools
# To prevent importing about and thereby breaking the coverage info we use this
# exec hack
about = {}
with open('python_utils/__about__.py') as fp:
exec(fp.read(), about)
if os.path.isfile('README.rst'):
long_description = open('README.rst').read()
else:
long_descr... | Python | jtatman_500k |
string Unittests for Valid_IP_Addresses.py February 2021 Jakub Kazimierski
import unittest
from Valid_IP_Addresses import validIPAddresses
class test_Valid_IP_Addresses extends TestCase
begin
string Class with unittests for Valid_IP_Addresses.py
function setUp self
begin
string Sets up input.
set input = string 1921680... | '''
Unittests for Valid_IP_Addresses.py
February 2021 Jakub Kazimierski
'''
import unittest
from Valid_IP_Addresses import validIPAddresses
class test_Valid_IP_Addresses(unittest.TestCase):
'''
Class with unittests for Valid_IP_Addresses.py
'''
def setUp(self):
'''
Sets up input.
... | Python | zaydzuhri_stack_edu_python |
function worksheets self visibility projection
begin
return call Worksheets self visibility=visibility projection=projection
end function | def worksheets(self, visibility, projection):
return Worksheets(self, visibility=visibility, projection=projection) | Python | nomic_cornstack_python_v1 |
function removeEntryPoint self address
begin
Ellipsis
end function | def removeEntryPoint(self, address: ghidra.program.model.address.Address) -> None:
... | Python | nomic_cornstack_python_v1 |
function test_get_buildable_service_cell mock_parent_object_exists rip_ingestor
begin
set return_value = true
set get_table = call Mock
set record = call _test_serviceinstance_in_cell_message
set body = loads record at string body
set message = loads body at string Message
set buildable_service = call get_buildable_ser... | def test_get_buildable_service_cell(mock_parent_object_exists, rip_ingestor):
mock_parent_object_exists.return_value = True
rip_ingestor.get_table = unittest.mock.Mock()
record = _test_serviceinstance_in_cell_message()
body = json.loads(record["body"])
message = json.loads(body["Message"])
build... | Python | nomic_cornstack_python_v1 |
function convert_abstracts_to_docs conll_path pmids_path vocab_path
begin
set vocab = call from_disk vocab_path
set pmids = list
with open pmids_path as pmids_fp
begin
set line = read line pmids_fp
while line
begin
append pmids right strip line
set line = read line pmids_fp
end
end
set corpus = list
set curr_pmid = n... | def convert_abstracts_to_docs(conll_path: str, pmids_path: str, vocab_path: str) -> List[Tuple[Doc, GoldParse]]:
vocab = Vocab().from_disk(vocab_path)
pmids = []
with open(pmids_path) as pmids_fp:
line = pmids_fp.readline()
while line:
pmids.append(line.rstrip())
line... | Python | nomic_cornstack_python_v1 |
function event_choices events
begin
string Get the possible events from settings
if events is none
begin
set msg = string Please add some events in settings.WEBHOOK_EVENTS.
raise call ImproperlyConfigured msg
end
try
begin
set choices = list comprehension tuple x x for x in events
end
except TypeError
begin
string Not ... | def event_choices(events):
""" Get the possible events from settings """
if events is None:
msg = "Please add some events in settings.WEBHOOK_EVENTS."
raise ImproperlyConfigured(msg)
try:
choices = [(x, x) for x in events]
except TypeError:
""" Not a valid iterator, so we... | Python | jtatman_500k |
function allow_migrate self db app_label model_name=none **hints
begin
if app_label == string RegisteredFroms
begin
return false
end
return true
end function | def allow_migrate(self, db, app_label, model_name=None, **hints):
if model._meta.app_label == 'RegisteredFroms':
return False
return True | Python | nomic_cornstack_python_v1 |
function convolutional_block X f filters stage block s=2
begin
set conv_name_base = string res + string stage + block + string _branch
set bn_name_base = string bn + string stage + block + string _branch
set tuple F1 F2 F3 = filters
set X_shortcut = X
comment MAIN PATH #####
comment First component of main path
set X =... | def convolutional_block(X, f, filters, stage, block, s = 2):
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
F1, F2, F3 = filters
X_shortcut = X
##### MAIN PATH #####
# First component of main path
X = Conv2D(F1, (1, 1), strides =... | Python | nomic_cornstack_python_v1 |
function __init__ self ad bd az bz tax
begin
set tuple ad bd az bz tax = tuple ad bd az bz tax
if ad < az
begin
raise call ValueError string Insufficient demand.
end
end function | def __init__(self, ad, bd, az, bz, tax):
self.ad, self.bd, self.az, self.bz, self.tax = ad, bd, az, bz, tax
if ad < az:
raise ValueError('Insufficient demand.') | Python | nomic_cornstack_python_v1 |
comment Es año PAR
if anio % 2 == 0
begin
comment Ene,Feb ó Mar
if mes >= 1 and mes <= 3
begin
comment Día PAR
if dia % 2 == 0
begin
print string Tu piedra preciosa es: string Rubí
end
else
begin
comment Día IMPAR
print string Tu piedra preciosa es: string Zafiro
end
end
else
if mes >= 4 and mes <= 6
begin
comment Abr,... | if anio % 2 == 0: # Es año PAR
if mes>=1 and mes<=3: # Ene,Feb ó Mar
if dia % 2 ==0: #Día PAR
print("Tu piedra preciosa es: ", "Rubí")
else: #Día IMPAR
print("Tu piedra preciosa es: ", "Zafiro")
elif mes>=4 and mes<=6:
# Abr, May, Jun
if d... | Python | zaydzuhri_stack_edu_python |
function after_get_onc_ctd msg config checklist
begin
set next_workers = dict string crash list ; string failure list ; string success SCVIP list ; string success SEVIP list ; string success LSBBL list ; string success USDDL list
if starts with type string success
begin
set ctd_stn = split type at 1
append next_w... | def after_get_onc_ctd(msg, config, checklist):
next_workers = {
'crash': [],
'failure': [],
'success SCVIP': [],
'success SEVIP': [],
'success LSBBL': [],
'success USDDL': [],
}
if msg.type.startswith('success'):
ctd_stn = msg.type.split()[1]
n... | Python | nomic_cornstack_python_v1 |
function addmsg self _msg
begin
comment Insert to the Text UI
insert consoletxt INSERT _msg + string
end function | def addmsg(self,_msg):
self.consoletxt.insert(INSERT,_msg+"\n") #Insert to the Text UI | Python | nomic_cornstack_python_v1 |
function below_nb_kmers nb_kmers
begin
with open string total_kmers_with_conditions.txt string r as totalKmersFile
begin
for line in totalKmersFile
begin
set splitLine = split line
if integer splitLine at 2 < nb_kmers and splitLine at 3 == string 1
begin
print splitLine at 3
end
end
end
end function | def below_nb_kmers(nb_kmers):
with open("total_kmers_with_conditions.txt", 'r') as totalKmersFile:
for line in totalKmersFile:
splitLine = line.split()
if (int(splitLine[2]) < nb_kmers and splitLine[3] == "1"):
print(splitLine[3]) | Python | nomic_cornstack_python_v1 |
function _compose self title text metadata
begin
raise NotImplementedError
end function | def _compose(self, title, text, metadata):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
string Script to filter CaDiCal results.csv from SAT race 2019
import pandas as pd
function load_dfs file_name
begin
set results_df = read csv file_name
set cadical_df = results_df at solver == string CaDiCaL
set cadical_sat_df = cadical_df at configuration == string sat
set cadical_unsat_df = cadical_df at configurati... | """
Script to filter CaDiCal results.csv from SAT race 2019
"""
import pandas as pd
def load_dfs(file_name):
results_df = pd.read_csv(file_name)
cadical_df = results_df[results_df.solver==' CaDiCaL']
cadical_sat_df = cadical_df[cadical_df.configuration == " sat"]
cadical_unsat_df = cadical_df[ca... | Python | zaydzuhri_stack_edu_python |
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Outliner extends QWidget
begin
set selectionChanged = call Signal
function __init__ self parent=none
begin
call __init__ parent=parent
call setLayout call QVBoxLayout
set list = call QListWidget
call connect emit
call addWidg... | from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Outliner(QWidget):
selectionChanged = Signal()
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setLayout(QVBoxLayout())
self.list = QListWidget()
self.list.itemSe... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
import PyQt4
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import time
import pdb
import sys
from sequence_generator import *
function hamming_distance s1 s2
begin
if length s1 != length s2
begin
raise call ValueError string Undefined for sequences... | #! /usr/bin/env python
import PyQt4
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import time
import pdb
import sys
from sequence_generator import *
def hamming_distance(s1, s2):
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")... | Python | zaydzuhri_stack_edu_python |
import math
import matplotlib.pyplot as plt
function euclidian_distance a b
begin
return square root a at 0 - b at 0 ^ 2 + a at 1 - b at 1 ^ 2
end function
function knn k
begin
set dataset = call getDataSet string C:\Users\Ludvig\Desktop\iris.data.txt
comment split data into training data and test data...
set x = sepal... | import math
import matplotlib.pyplot as plt
def euclidian_distance(a,b):
return math.sqrt((a[0] - b[0])**2 + (a[1]-b[1])**2)
def knn(k):
dataset = getDataSet("C:\\Users\\Ludvig\\Desktop\\iris.data.txt")
#split data into training data and test data...
x = dataset.sepal_length
y = dataset.sepal_widt... | Python | zaydzuhri_stack_edu_python |
class Future
begin
function __init__ self func args=none kwargs=none
begin
set func = func
set args = args
set kwargs = kwargs
set result = none
end function
function eval self
begin
if args is none
begin
set result = func
return func
end
set result = call func *self.args keyword kwargs
set result = result
set memos at... | class Future:
def __init__(self, func, args=None, kwargs=None):
self.func = func
self.args = args
self.kwargs = kwargs
self.result = None
def eval(self):
if self.args is None:
self.result = self.func
return self.func
result = self.func.fun... | Python | zaydzuhri_stack_edu_python |
function ler_matriz_fixa self
begin
return list list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 list 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 li... | def ler_matriz_fixa(self):
return [[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], ... | Python | nomic_cornstack_python_v1 |
function str_geometry_code_body self
begin
return string (%s) % join string ), ( list comprehension call str_geometry_object for o in list_of_geos
end function | def str_geometry_code_body(self) :
return ' (%s)'%('),\n ('.join([o.str_geometry_object() for o in self.list_of_geos])) | Python | nomic_cornstack_python_v1 |
function find_spheroid imCropped wellDiameterUm mutopx marginDistance=110 fraction=3.2 minRegionArea=1000 maxRegionArea=120000
begin
set result1 = call sobel imCropped 1
set result2 = call sobel imCropped 0
set mask = call _make_disk_mask wellDiameterUm wellDiameterUm - marginDistance mutopx
set tuple nx ny = call shap... | def find_spheroid(
imCropped: np.ndarray,
wellDiameterUm: int,
mutopx: float,
marginDistance=110,
fraction=3.2,
minRegionArea=1000,
maxRegionArea=120000):
result1 = ndimage.sobel(imCropped, 1)
result2 = ndimage.sobel(imCropped, 0)
mask = utilities._make_disk_mask(
wellD... | Python | nomic_cornstack_python_v1 |
function _handler_direct_access_enter self *args **kwargs
begin
comment Tell driver superclass to send a state change event.
comment Superclass will query the state.
call _driver_event STATE_CHANGE
set _sent_cmds = list
end function | def _handler_direct_access_enter(self, *args, **kwargs):
# Tell driver superclass to send a state change event.
# Superclass will query the state.
self._driver_event(DriverAsyncEvent.STATE_CHANGE)
self._sent_cmds = [] | Python | nomic_cornstack_python_v1 |
function drawMatrixContour zmatrix nrows ncols level
begin
call conmat zmatrix nrows ncols level
end function | def drawMatrixContour(zmatrix, nrows, ncols, level):
dislin.conmat(zmatrix, nrows, ncols, level) | Python | nomic_cornstack_python_v1 |
function get_ror_cifar classes blocks model_name=none pretrained=false root=join path string ~ string .chainer string models **kwargs
begin
assert classes in list 10 100
assert blocks - 8 % 6 == 0
set layers = list blocks - 8 // 6 * 3
set channels_per_layers = list 16 32 64
set init_block_channels = 16
set channels = l... | def get_ror_cifar(classes,
blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".chainer", "models"),
**kwargs):
assert (classes in [10, 100])
assert ((blocks - 8) % 6 == 0)
layers = [(blocks - 8) // 6] ... | Python | nomic_cornstack_python_v1 |
function GetNextVisible self item
begin
set id = item
while id
begin
set id = call GetNext id
if id and call IsVisible id
begin
return id
end
end
return none
end function | def GetNextVisible(self, item):
id = item
while id:
id = self.GetNext(id)
if id and self.IsVisible(id):
return id
return None | Python | nomic_cornstack_python_v1 |
from duck import Duck
from fly_with_wings import FlyWithWings
from quack import Quack
class RedHeadDuck extends Duck
begin
function __init__ self
begin
call set_fly_behavior FlyWithWings
call set_quack_behavior Quack
end function
function display
begin
print string I'm a real Red Headed duck
end function
end class | from duck import Duck
from fly_with_wings import FlyWithWings
from quack import Quack
class RedHeadDuck(Duck):
def __init__(self):
self.set_fly_behavior(FlyWithWings)
self.set_quack_behavior(Quack)
def display():
print("I'm a real Red Headed duck")
| Python | zaydzuhri_stack_edu_python |
function determine_most_common_prefix self
begin
set prefix_count = dict
for repository in values __repositories
begin
set url_prefix = call to_git_url_prefix origin
set prefix_count at url_prefix = get prefix_count url_prefix 0 + 1
end
set default_prefix = none
set max_count = 0
for tuple prefix count in items prefix... | def determine_most_common_prefix(self):
prefix_count = {}
for repository in self.__repositories.values():
url_prefix = self.to_git_url_prefix(repository.origin)
prefix_count[url_prefix] = prefix_count.get(url_prefix, 0) + 1
default_prefix = None
max_count = 0
... | Python | nomic_cornstack_python_v1 |
function relation_ self table origin_field search_field destination_field=none id_field=string id
begin
string Returns a DataSwim instance with a column filled from a relation foreign key
set df = call _relation table origin_field search_field destination_field id_field
return call _duplicate_ df
end function | def relation_(self, table, origin_field, search_field, destination_field=None,
id_field="id"):
"""
Returns a DataSwim instance with a column filled from a relation foreign key
"""
df = self._relation(table, origin_field,
search_field, destin... | Python | jtatman_500k |
function GoBack self
begin
return call InvokeTypes 100 LCID 1 tuple 24 0 tuple
end function | def GoBack(self):
return self._oleobj_.InvokeTypes(100, LCID, 1, (24, 0), (),) | Python | nomic_cornstack_python_v1 |
function test_netstat_sudo_lnp_ubuntu_18_4 self
begin
assert equal parse netstat ubuntu_18_4_netstat_sudo_lnp quiet=true ubuntu_18_4_netstat_sudo_lnp_json
end function | def test_netstat_sudo_lnp_ubuntu_18_4(self):
self.assertEqual(jc.parsers.netstat.parse(self.ubuntu_18_4_netstat_sudo_lnp, quiet=True), self.ubuntu_18_4_netstat_sudo_lnp_json) | Python | nomic_cornstack_python_v1 |
string @author kamiyong @date 2021-1-19 10:08:18 @description 图片获取工具类
import os
import time
from PIL import ImageGrab
class ImageCaptor extends object
begin
string 图片获取
function __init__ self
begin
set __parent = string /resource/temp/TempImage/
set __path = get current directory
set __timeFormat = string %y-%m-%d_%H-%... | """
@author kamiyong
@date 2021-1-19 10:08:18
@description 图片获取工具类
"""
import os
import time
from PIL import ImageGrab
class ImageCaptor(object):
"""
图片获取
"""
def __init__(self):
self.__parent = "/resource/temp/TempImage/"
self.__path = os.getcwd()
self.__timeFormat = "%y-%m-%d... | Python | zaydzuhri_stack_edu_python |
import sys
from collections import deque
set readline = readline
set readall = read
set ns = lambda -> right strip read line
set ni = lambda -> integer right strip read line
set nm = lambda -> map int split read line
set nl = lambda -> list map int split read line
set prl = lambda x -> print *x sep=string
function ... | import sys
from collections import deque
readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prl = lambda x: print(*x ,sep='\n')
def bfs(start,end):
t... | Python | zaydzuhri_stack_edu_python |
function get_jabbers self uri uri2=none
begin
set templates = list string %(source)s issues %(name)s (%(aaa)s) at %(stamp)s%(headline)s string %(source)s issues %(name)s (%(aaa)s) at %(stamp)s
set aaa = afos at slice : 3 :
set hdl = call get_main_headline
set data = dict string headline if expression hdl != string t... | def get_jabbers(self, uri, uri2=None):
templates = [
"%(source)s issues %(name)s (%(aaa)s) at %(stamp)s%(headline)s ",
"%(source)s issues %(name)s (%(aaa)s) at %(stamp)s "
]
aaa = self.afos[:3]
hdl = self.get_main_headline()
data = {
'headl... | Python | nomic_cornstack_python_v1 |
function test cls pathHolder parentCrawler
begin
if not call test pathHolder parentCrawler ignoreExt=true
begin
return false
end
return call ext == string cc
end function | def test(cls, pathHolder, parentCrawler):
if not super(CcCrawler, cls).test(pathHolder, parentCrawler, ignoreExt=True):
return False
return pathHolder.ext() == 'cc' | Python | nomic_cornstack_python_v1 |
function generate_spi3d_from_colormap colormap cube_size=65 input_exp_range=tuple - 12.473931189 4.026068812 unclipped_exp_range=tuple - 12.473931189 4.026068812 centered=false
begin
set lut = list string SPILUT 1.0 string 3 3 string { cube_size } { cube_size } { cube_size }
for in_red in range 0 cube_size
begin
for in... | def generate_spi3d_from_colormap(colormap,
cube_size=65,
input_exp_range=(-12.473931189, 4.026068812),
unclipped_exp_range=(-12.473931189, 4.026068812),
centered=False):
... | Python | nomic_cornstack_python_v1 |
function web_backup
begin
set conf = utils
if secret_key is none
begin
set upload_path = database_name
set file = none
end
else
begin
set file = named temporary file delete=false
write file call get_encrypted_database
close file
set upload_path = name
end
set factory = if expression tls then FTP_TLS else FTP
comment no... | def web_backup():
conf = config.utils
if conf.tasks.secret_key is None:
upload_path = config.core.database_name
file = None
else:
file = tempfile.NamedTemporaryFile(delete=False)
file.write(get_encrypted_database())
file.close()
upload_path = file.name
fa... | Python | nomic_cornstack_python_v1 |
function request self url method data=none
begin
if is instance data dict and method is not string GET
begin
set data = dumps data
if method == string PUT
begin
set opener = call build_opener HTTPHandler
set request = call Request string %s/api/%s/%s % tuple adress user url data=data
call add_header string Content-Type... | def request(self, url, method, data=None):
if isinstance(data, dict) and method is not 'GET':
data = json.dumps(data)
if method == 'PUT':
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request("%s/api/%s/%s" % (self.adress, self.user,... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding:utf-8 -*-
import pymongo
import datetime
import time
from setting import settings
import random
function print_marker marker
begin
set strTime = string format time now string %Y-%m-%d %H:%M:%S
print marker + strTime
end function
function sleep_random
begin
set x = random inte... | #!/usr/bin/python
# -*- coding:utf-8 -*-
import pymongo
import datetime
import time
from setting import settings
import random
def print_marker(marker):
strTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S');
print (marker + strTime)
def sleep_random():
x = random.randint(3, 7)
tim... | Python | zaydzuhri_stack_edu_python |
comment mainly refer to https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb
from transformers import AutoModelForCausalLM , AutoTokenizer
function get_model_tokenizer weights_dir device=string cuda
begin
print string Loading Model ...
set model = call from_... | # mainly refer to https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb
from transformers import AutoModelForCausalLM, AutoTokenizer
def get_model_tokenizer(weights_dir, device = 'cuda'):
print("Loading Model ...")
model = AutoModelForCausalLM.from_... | Python | zaydzuhri_stack_edu_python |
function orelse self *conds
begin
set _orelse = _orelse + conds
return self
end function | def orelse(self, *conds):
self._orelse += conds
return self | Python | nomic_cornstack_python_v1 |
function get_building self instance
begin
return data
end function | def get_building(self, instance):
return BaseBuildingSerializer(instance.building).data | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import os
import sys
call reload sys
call setdefaultencoding string utf-8
function func1
begin
change directory string C:\Users\admin\WWH\python
end function | # -*- coding: utf-8 -*-
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def func1():
os.chdir(r'C:\Users\admin\WWH\python') | Python | zaydzuhri_stack_edu_python |
function done self group_key
begin
return format string "{}"^^<http://www.w3.org/2001/XMLSchema#integer> _groups at group_key
end function | def done(self, group_key):
return '"{}"^^<http://www.w3.org/2001/XMLSchema#integer>'.format(self._groups[group_key]) | Python | nomic_cornstack_python_v1 |
function generate_anchors dimensions box_sizes
begin
set tuple feat_h feat_w = dimensions
set anchors_list = list
for bs in box_sizes
begin
set x_list = list
for i in range 0 feat_h
begin
set y_list = list
for j in range 0 feat_w
begin
set x = i - bs at 0 // 2
set y = j - bs at 1 // 2
set l = bs at 0
set w = bs at 1... | def generate_anchors(dimensions, box_sizes):
feat_h, feat_w = dimensions
anchors_list = []
for bs in box_sizes:
x_list = []
for i in range(0, feat_h):
y_list = []
for j in range(0, feat_w):
x = (i - (bs[0] // 2))
y = (j - (bs[1] // 2)... | Python | nomic_cornstack_python_v1 |
from datetime import date , datetime , time
from django.shortcuts import render , HttpResponse
from models import Students , Teachers
from django.db.models import Q , Avg , Sum , Min , Max , Count
function home request
begin
string Part 1: returns a new queryset
comment students = Students.objects.all()
comment student... | from datetime import date, datetime, time
from django.shortcuts import render, HttpResponse
from .models import Students, Teachers
from django.db.models import Q, Avg, Sum, Min, Max, Count
def home(request):
"""
Part 1: returns a new queryset
"""
# students = Students.objects.all()
# students = Stu... | Python | zaydzuhri_stack_edu_python |
import json
import copy
import sys
import math
import numpy as np
import matplotlib
from matplotlib.patches import Polygon as mPolygon
from matplotlib.collections import PatchCollection , LineCollection
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from shapely.geometry import Polygon , Multi... | import json
import copy
import sys
import math
import numpy as np
import matplotlib
from matplotlib.patches import Polygon as mPolygon
from matplotlib.collections import PatchCollection, LineCollection
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from shapely.geometry import Polygon, Multi... | Python | zaydzuhri_stack_edu_python |
import os
set environ at string CUDA_VISIBLE_DEVICES = string -1
import numpy as np
import matplotlib.pyplot as plt
from networks.utils.network_updating import load_model_from_disk
from networks.utils.sampling import generate_latent_vectors_gaussian , generate_fake_images_from_latents
from processing.image_processor im... | import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import matplotlib.pyplot as plt
from networks.utils.network_updating import load_model_from_disk
from networks.utils.sampling import generate_latent_vectors_gaussian, generate_fake_images_from_latents
from processing.image_processor import ImageProc... | Python | zaydzuhri_stack_edu_python |
import invoke_methods
function func1 request
begin
call trigger_http_endpoint string func2 string post dict string hello string there
end function
function func2 request
begin
string Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that ca... | import invoke_methods
def func1(request):
invoke_methods.trigger_http_endpoint("func2", "post",{"hello":"there"})
def func2(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned ... | Python | zaydzuhri_stack_edu_python |
function get_splits_ids data_type
begin
set split_data_path = call resolve
comment e.g., 20050908_182943_22_fsp
set split_ids = list
with open split_data_path as split_file
begin
set split_lines = read lines split_file
for split_line in split_lines
begin
set split_line = strip split_line
set split_id = split split_lin... | def get_splits_ids(data_type: str) -> List[str]:
split_data_path = (Path(__file__).parent / f'./splits/split_fisher/train_{data_type}').resolve()
split_ids = [] # e.g., 20050908_182943_22_fsp
with open(split_data_path) as split_file:
split_lines = split_file.readlines()
for split_line in split_lines:
... | Python | nomic_cornstack_python_v1 |
function calculate_error Yhat Y print_errors=false
begin
comment Ensure arrays are 2D
assert call ndim Y <= 3 msg string Y must be one, two, or three dimensional, with the sequence on the first dimension
assert call ndim Yhat <= 3 msg string Yhat must be one, two, or three dimensional, with the sequence on the first di... | def calculate_error(Yhat, Y, print_errors=False):
# Ensure arrays are 2D
assert np.ndim(Y) <= 3, 'Y must be one, two, or three dimensional, with the sequence on the first dimension'
assert np.ndim(Yhat) <= 3, 'Yhat must be one, two, or three dimensional, with the sequence on the first dimension'
assert... | Python | nomic_cornstack_python_v1 |
import numpy as np
from SMILES import SMILES
from BigSMILES_BigSmilesObj import BigSMILES
from BigSmilesPattern import BigSmilesPattern
from BigSMILES_Bond import BigSMILES_Bond
from BigSMILES_StoObj import BigSMILES_StoObj
from utility import errorMsg , flatten_list
from error import BigSMILESError , BigSMILES_BondInc... | import numpy as np
from SMILES import SMILES
from BigSMILES_BigSmilesObj import BigSMILES
from BigSmilesPattern import BigSmilesPattern
from BigSMILES_Bond import BigSMILES_Bond
from BigSMILES_StoObj import BigSMILES_StoObj
from utility import errorMsg, flatten_list
from error import BigSMILESError,BigSMILES_BondIncons... | Python | zaydzuhri_stack_edu_python |
comment importing necessary libraries
import matplotlib.pyplot as plt
comment defining DDA function
function DDA x1 y1 x2 y2
begin
comment Calculating change in both directions
set dx = x2 - x1
set dy = y2 - y1
set x_point = list x1
set y_point = list y1
set steps = 0
comment Deciding the number of steps to move
if abs... | #importing necessary libraries
import matplotlib.pyplot as plt
#defining DDA function
def DDA(x1, y1, x2, y2):
#Calculating change in both directions
dx = x2-x1
dy = y2-y1
x_point = [x1]
y_point = [y1]
steps = 0
#Deciding the number of steps to move
if abs(dx)>abs(dy):
steps = abs(dx)
else:
st... | Python | zaydzuhri_stack_edu_python |
string Euler 206 Find the unique positive integer which takes the form: 1_2_3_4_5_6_7_8_9_0 where each "_" is a single digit. Minimally: sqrt(1020304050607080900) = 1010101010.1010101 Maximally: sqrt(1929394959697989990) = 1389026623.1062636
from math import sqrt
function test_case nsq
begin
comment nsq=n**2
if string ... | """ Euler 206
Find the unique positive integer which takes the form: 1_2_3_4_5_6_7_8_9_0
where each "_" is a single digit.
Minimally: sqrt(1020304050607080900) = 1010101010.1010101
Maximally: sqrt(1929394959697989990) = 1389026623.1062636
"""
from math import sqrt
def test_case(nsq):
# nsq=n**2
if str(nsq)[0]==... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render
comment Create your views here.
comment coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render
comment def index(request):
comment return HttpResponse(u"<h1>PRC</h1><p>The People's Republic of China was born in 1949...</p>")
function index request
begin... | from django.shortcuts import render
# Create your views here.
# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render
# def index(request):
# return HttpResponse(u"<h1>PRC</h1><p>The People's Republic of China was born in 1949...</p>")
def index(request):
return render(request... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
comment Storing the fasta file1 (inputted as argument) in seq1_fasta
set seq1_fasta = argv at 1
comment Storing the fasta file2 (inputted as argument) in seq2_fasta
set seq2_fasta = argv at 2
comment seq1 string is going to contain the sequence 1
set seq1 = string
comment seq2 ... | #!/usr/bin/env python3
import sys
seq1_fasta = sys.argv[1] #Storing the fasta file1 (inputted as argument) in seq1_fasta
seq2_fasta = sys.argv[2] #Storing the fasta file2 (inputted as argument) in seq2_fasta
seq1 = "" #seq1 string is... | Python | zaydzuhri_stack_edu_python |
string @author: tony-tan @time: 2019/6/18 10:30 @file: thread_global.py @site: @describe: 线程间通信的方式
comment 共享变量 存在线程安全问题
import time
import threading
set detail_url_list = list
function get_detail_html url
begin
comment 具体url 内详情数据
global detail_url_list
while true
begin
if detail_url_list != list
begin
set url = pop... | """
@author: tony-tan
@time: 2019/6/18 10:30
@file: thread_global.py
@site:
@describe: 线程间通信的方式
"""
# 共享变量 存在线程安全问题
import time
import threading
detail_url_list = []
def get_detail_html(url):
# 具体url 内详情数据
global detail_url_list
while True:
if detail_url_list != []:
url = detail_url_list... | Python | zaydzuhri_stack_edu_python |
function cigarette request
begin
if method == string POST
begin
set readstring = body
set readstring = decode readstring string ascii
if not is file path datapath
begin
set f = open datapath string w
end
else
begin
set f = open datapath string a
end
write f readstring + string
comment you can omit in most cases as the ... | def cigarette(request):
if request.method == 'POST':
readstring = request.body
readstring = readstring.decode("ascii")
if not os.path.isfile(datapath):
f = open(datapath,'w')
else:
f = open(datapath,'a')
f.write(readstring+"\n")
f.... | Python | nomic_cornstack_python_v1 |
function apply self x
begin
if a is not none and b is not none
begin
set index = a * x + b % p % m
append hashtable at index x
return index
end
end function | def apply(self, x):
if (self.a is not None) and (self.b is not None):
index = ((self.a * x + self.b) % self.p) % self.m
self.hashtable[index].append(x)
return index | Python | nomic_cornstack_python_v1 |
function remove_value self value
begin
if call key value == value
begin
if children == none
begin
set root = none
end
else
begin
call bst_remove root
end
end
else
begin
set node = call get_node value
call bst_remove node
end
end function | def remove_value(self, value: K) -> None:
if self.key(self.root.value) == value:
if self.root.children == None:
self.root = None
else:
self.bst_remove(self.root)
else:
node = self.get_node(value)
self.bst_remove(node) | Python | nomic_cornstack_python_v1 |
function split p
begin
set seps = call _get_bothseps p
set tuple d p = call splitdrive p
comment set i to index beyond p's last slash
set i = length p
while i and p at i - 1 not in seps
begin
set i = i - 1
end
comment now tail has no slashes
set tuple head tail = tuple p at slice : i : p at slice i : :
comment remo... | def split(p):
seps = _get_bothseps(p)
d, p = splitdrive(p)
# set i to index beyond p's last slash
i = len(p)
while i and p[i-1] not in seps:
i -= 1
head, tail = p[:i], p[i:] # now tail has no slashes
# remove trailing slashes from head, unless it's all slashes
head = head.rstri... | Python | nomic_cornstack_python_v1 |
import BaseHTTPServer
import json
import os
import time
import random
import subprocess
import re
string response structure from the xqueue { "xqueue_body":{ "student_response":string ##the code submitted by the student as a string "submission_info":{ "trial":boolean, ##whether the submission is a trial submission( to ... | import BaseHTTPServer
import json
import os
import time
import random
import subprocess
import re
"""
response structure from the xqueue
{
"xqueue_body":{
"student_response":string ##the code submitted by the student as a string
"submission_info":{
"trial":boolean, ##whether... | 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.