code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function nested_parts num_atoms num_threads upper_triangle=false
begin
comment partition of atoms with an inner loop
set parts = list
set num_threads_ = min num_threads num_atoms
for num in range num_threads_
begin
set part = 1 + 4 * parts at - 1 ^ 2 + parts at - 1 + num_atoms * num_atoms + 1.0 / num_threads_
set part... | def nested_parts(num_atoms, num_threads, upper_triangle=False):
# partition of atoms with an inner loop
parts = []
num_threads_ = min(num_threads, num_atoms)
for num in range(num_threads_):
part = 1 + 4 * (parts[-1] ** 2 + parts[-1] + num_atoms * (num_atoms + 1.) / num_threa... | Python | nomic_cornstack_python_v1 |
import cv2
import time
import traceback
import numpy as np
function get_delay start_time fps=30
begin
if time - start_time > 1 / decimal fps
begin
return 1
end
else
begin
return max integer 1 / decimal fps * 1000 - time - start * 1000 1
end
end function
comment Instantiate cascade classifiers for finding faces
set face... | import cv2
import time
import traceback
import numpy as np
def get_delay(start_time, fps=30):
if (time.time() - start_time) > (1 / float(fps)):
return 1
else:
return max(int((1 / float(fps)) * 1000 - (time.time() - start) * 1000), 1)
# Instantiate cascade classifiers for finding faces
face_cas... | Python | zaydzuhri_stack_edu_python |
function Json trame
begin
set sub = split trame character 10
set dict = dict
for i in range 1 length sub
begin
set item = split sub at i string
set dict at item at 0 = item at 1
end
with open string /var/www/stream/realTime.json string w as file
begin
dump dict file indent=4
end
close file
end function | def Json (trame):
sub=trame.split(chr(0x0a))
dict={}
for i in range(1,len(sub)):
item=sub[i].split(' ')
dict[item[0]]=item[1]
with open("/var/www/stream/realTime.json","w") as file:
json.dump(dict,file,indent=4)
file.close() | Python | nomic_cornstack_python_v1 |
function print_results self results
begin
for result in results
begin
call print_result result
end
end function | def print_results(self, results):
for result in results:
self.print_result(result) | Python | nomic_cornstack_python_v1 |
function _pairwise_distances embeddings squared=false
begin
comment Get the dot product between all embeddings
comment shape (batch_size, batch_size)
set dot_product = matrix multiply embeddings transpose tf embeddings
comment Get squared L2 norm for each embedding. We can just take the diagonal of `dot_product`.
comme... | def _pairwise_distances(embeddings, squared=False):
# Get the dot product between all embeddings
# shape (batch_size, batch_size)
dot_product = tf.matmul(embeddings, tf.transpose(embeddings))
# Get squared L2 norm for each embedding. We can just take the diagonal of `dot_product`.
# This also provi... | Python | nomic_cornstack_python_v1 |
comment Korzystając z modułu socket i wiedzy o zapytaniach HTTP,
comment uzyskaj informację jaki serwer i w jakiej wersji jest uruchumiony pod adresem kretes.xyz
comment Na wyjściu programu powinieneś uzyskać tylko informację o serwerze
comment Podpowiedź 1:
comment http używa \r\n. Przy podziale na nowe linie zostaje ... | # Korzystając z modułu socket i wiedzy o zapytaniach HTTP,
# uzyskaj informację jaki serwer i w jakiej wersji jest uruchumiony pod adresem kretes.xyz
# Na wyjściu programu powinieneś uzyskać tylko informację o serwerze
#
# Podpowiedź 1:
# http używa \r\n. Przy podziale na nowe linie zostaje \r. Aby temu zapobiec, uży... | Python | zaydzuhri_stack_edu_python |
function factor_twos x
begin
set tuple d s = tuple x 0
while call even d
begin
set d = d ? 1
set s = s + 1
end
return tuple d s
end function | def factor_twos(x):
d, s = x, 0
while even(d):
d >>= 1
s += 1
return d, s | Python | nomic_cornstack_python_v1 |
function runJMeter self jMeterPrefix=string /usr/local/apache-jmeter-2.9/bin
begin
set jMeterOutcome = 0
set jobDesc = string SG-MonCheck-JM_%s % string format time now string %Y%m%d-%H%M%S
set mytmp = temporary file mode=string w+b dir=string /tmp suffix=string jmeterDEBUG
comment shutup=os.open('/tmp/jmeterdebug.txt'... | def runJMeter(self, jMeterPrefix="/usr/local/apache-jmeter-2.9/bin"):
jMeterOutcome = 0
jobDesc = ("SG-MonCheck-JM_%s"
% (datetime.now().strftime("%Y%m%d-%H%M%S")))
mytmp = tempfile.TemporaryFile(mode='w+b', dir='/tmp',
suffix='jmeterDEB... | Python | nomic_cornstack_python_v1 |
comment importa a biblioteca Glu e Glut
string A biblioteca GLUT responsvel pela criao janelas e o tratamento de seus eventos de forma independente do sistema operacional utilizado.
string A biblioteca GLU responsvel pelo mapeamento entre coordenadas de tela e coordenadas do mundo, gerao de mipmaps de texturas,
string ... | #importa a biblioteca Glu e Glut
"A biblioteca GLUT responsvel pela criao janelas e o tratamento de seus eventos de forma independente do sistema operacional utilizado."
"A biblioteca GLU responsvel pelo mapeamento entre coordenadas de tela e coordenadas do mundo, gerao de mipmaps de texturas,"
'desenho de superfcie... | Python | zaydzuhri_stack_edu_python |
function test_searchMessageSetUIDWithStar self
begin
return call _messageSetSearchTest string UID 10000:* list 2 3 4 5
end function | def test_searchMessageSetUIDWithStar(self):
return self._messageSetSearchTest('UID 10000:*', [2, 3, 4, 5]) | Python | nomic_cornstack_python_v1 |
function pricing_reset request simulation
begin
comment Get all tolls.
set policies = call get_query string policy simulation
set tolls = filter type=string PRICING
comment Delete the Policy objects (the LinkSelection objects are not deleted).
delete
return call HttpResponseRedirect reverse string metro:pricing_main ar... | def pricing_reset(request, simulation):
# Get all tolls.
policies = get_query('policy', simulation)
tolls = policies.filter(type='PRICING')
# Delete the Policy objects (the LinkSelection objects are not deleted).
tolls.delete()
return HttpResponseRedirect(reverse(
'metro:pricing_main', a... | Python | nomic_cornstack_python_v1 |
comment - Testing the abstract factory
from BostonConcreteSoupFactory import BostonConcreteSoupFactory
from HonoluluConcreteSoupFactory import HonoluluConcreteSoupFactory
import unittest
class TestAbstractFactory extends TestCase
begin
function makeSoupOfTheDay self concreteSoupFactory
begin
return call makeFishChowder... | # - Testing the abstract factory
from BostonConcreteSoupFactory import BostonConcreteSoupFactory
from HonoluluConcreteSoupFactory import HonoluluConcreteSoupFactory
import unittest
class TestAbstractFactory( unittest.TestCase ):
def makeSoupOfTheDay(self,concreteSoupFactory) :
return concreteSoupFactory.makeFish... | Python | zaydzuhri_stack_edu_python |
comment I got this wrong on my first attempt:
set s = string CATTCTCATAGCCAAAAAAGTACCATCAAGGT
set d = dict string A string T ; string C string G ; string G string C ; string T string A
print call translate d
comment Note that you could use s[::-1] instead of reversed(s).
comment My code should have been:
set s = string... | # I got this wrong on my first attempt:
s = 'CATTCTCATAGCCAAAAAAGTACCATCAAGGT'
d = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
print(reversed(s).translate(d))
# Note that you could use s[::-1] instead of reversed(s).
# My code should have been:
s = 'CATTCTCATAGCCAAAAAAGTACCATCAAGGT'
d = {ord('A'): 'T', ord('C'): 'G',... | Python | zaydzuhri_stack_edu_python |
function bin_dates date_series method=string year num_bins=3 date_format=string %d/%m/%Y
begin
set parsed_date_series = call to_datetime date_series format=date_format
if method == string bins
begin
return call cut parsed_date_series bins=num_bins labels=false
end
else
if method == string year
begin
return year
end
end... | def bin_dates(date_series:pd.Series, method="year", num_bins = 3, date_format="%d/%m/%Y"):
parsed_date_series = pd.to_datetime(date_series, format=date_format)
if method == "bins":
return pd.cut(parsed_date_series,bins=num_bins,labels=False)
elif method == "year":
return parsed_date_series.d... | Python | nomic_cornstack_python_v1 |
function get_getter self
begin
set c = call Curl
set resp = call HTTPResponse _encoding
call setopt HTTPGET 1
if _query
begin
update query _query
set _query = none
end
call setopt URL string _url
call setopt WRITEFUNCTION _body_callback
call setopt HEADERFUNCTION _header_callback
call setopt HTTPHEADER map str _headers... | def get_getter(self):
c = pycurl.Curl()
resp = HTTPResponse(self._encoding)
c.setopt(pycurl.HTTPGET, 1)
if self._query:
self._url.query.update(self._query)
self._query = None
c.setopt(c.URL, str(self._url))
c.setopt(c.WRITEFUNCTION, resp._body_call... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string sensor fusion algorithm for ardrone
import rospy
from ardrone_autonomy.msg import Navdata
from ardrone_msgs.msg import QuadrotorState
import math
import ardrone_lib.quadrotor as quadrotor
class SensorFusion extends object
begin
string Sensor Fusion Class: Reads navdata Publishes odom... | #!/usr/bin/env python
"""
sensor fusion algorithm for ardrone
"""
import rospy
from ardrone_autonomy.msg import Navdata
from ardrone_msgs.msg import QuadrotorState
import math
import ardrone_lib.quadrotor as quadrotor
class SensorFusion(object):
"""
Sensor Fusion Class:
Reads navdata
Publishes odomet... | Python | zaydzuhri_stack_edu_python |
import tie
from datatime import timedelta
set start_time = monotonic
function recur_fabo n
begin
if n <= 1
begin
return n
end
else
begin
return call recur_fabo n - 1 + call recur_fabo n - 2
end
end function
set n = integer input string how many terms
if n <= 0
begin
print string please enter positive number
end
else
be... | import tie
from datatime import timedelta
start_time = time.monotonic()
def recur_fabo(n):
if n<=1:
return n
else:
return recur_fabo(n-1) + recur_fabo(n-2)
n=int(input("how many terms"))
if n<=0:
print("please enter positive number")
else:
print("Fibonacci sequence") | Python | zaydzuhri_stack_edu_python |
string Escreva um programa em Python que solicite ao usuário 3 (três) números inteiros e retorne se os números foram ou não foram digitados em ordem crescente.
set numero = integer input string Digite o primeiro número:
set numero_1 = integer input string Digite o segundo número:
set numero_2 = integer input string Dig... | '''
Escreva um programa em Python que solicite ao usuário 3 (três) números inteiros e retorne se os números foram ou não foram digitados em ordem crescente.
'''
numero = int(input('Digite o primeiro número: '))
numero_1 = int(input('Digite o segundo número: '))
numero_2 = int(input('Digite o terceiro número: '))
if n... | Python | zaydzuhri_stack_edu_python |
from pprint import pprint
import requests
import urllib3
from bs4 import BeautifulSoup
import pandas
from openpyxl.workbook import Workbook
call disable_warnings
class GithubRepo
begin
function __init__ self username
begin
set username = username
set repo_url = string https://github.com/ { username } ?tab=repositories
... | from pprint import pprint
import requests
import urllib3
from bs4 import BeautifulSoup
import pandas
from openpyxl.workbook import Workbook
urllib3.disable_warnings()
class GithubRepo:
def __init__(self, username):
self.username = username
self.repo_url = f'https://github.com/{username}?tab=rep... | Python | zaydzuhri_stack_edu_python |
function setScaling self scaling
begin
set scaling = scaling
end function | def setScaling(self, scaling):
self.scaling = scaling | Python | nomic_cornstack_python_v1 |
for i in range a b + 1
begin
if i % k == 0
begin
set c = c + 1
end
else
begin
pass
end
end
if c == 0
begin
print string NG
end
else
begin
print string OK
end | for i in range(a, b+1):
if i%k == 0:
c += 1
else:
pass
if c == 0:
print("NG")
else:
print("OK") | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import requests , json
from flask import Flask , jsonify , request , render_template , send_from_directory
import cPickle as pickle
from keras.models import load_model
from keras.models import Sequential
from keras.layers.core import Dense , Dropout , Activation , Flatten
from ker... | import pandas as pd
import numpy as np
import requests, json
from flask import Flask, jsonify, request, render_template, send_from_directory
import cPickle as pickle
from keras.models import load_model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optim... | Python | zaydzuhri_stack_edu_python |
function scale array amin amax
begin
global g_scale_between_zero_and_one
if g_scale_between_zero_and_one
begin
set x = array - amin
set scale = amax - amin
return x / scale
end
else
begin
return array
end
end function | def scale(array:np.ndarray, amin:np.ndarray, amax:np.ndarray)->np.ndarray:
global g_scale_between_zero_and_one
if g_scale_between_zero_and_one:
x = array - amin
scale = amax - amin
return x / scale
else:
return array | Python | nomic_cornstack_python_v1 |
function squaredDistanceTo self other
begin
if not is instance other Point
begin
return
end
return longitude - call getLongitude ^ 2 + latitude - call getLatitude ^ 2
end function | def squaredDistanceTo(self,other):
if not isinstance(other,Point):
return
return (self.longitude - other.getLongitude())**2 +(self.latitude - other.getLatitude())**2 | Python | nomic_cornstack_python_v1 |
function patch_click monkeypatch
begin
set echo_mock = call Mock
set confirm_mock = call Mock
set attribute click string echo echo_mock
set attribute click string confirm confirm_mock
return none
end function | def patch_click(monkeypatch):
echo_mock = mock.Mock()
confirm_mock = mock.Mock()
monkeypatch.setattr(click, "echo", echo_mock)
monkeypatch.setattr(click, "confirm", confirm_mock)
return None | Python | nomic_cornstack_python_v1 |
function _set_qos self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_qos_openconfig_qos_interfaces__qos is_container=string container yang_name=string qos parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true e... | def _set_qos(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_qos_openconfig_qos_interfaces__qos, is_container='container', yang_name="qos", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, na... | Python | nomic_cornstack_python_v1 |
function data_sample complexe_list taille
begin
set indices = random sample range length complexe_list taille
set complex_file_names = list comprehension complexe_list at i for i in indices
return complex_file_names
end function | def data_sample(complexe_list, taille):
indices = random.sample(range(len(complexe_list)), taille)
complex_file_names = [complexe_list[i] for i in indices]
return(complex_file_names) | Python | nomic_cornstack_python_v1 |
function print_result self result
begin
print string - * 100
print call rjust 7 + length votes + tab string + call rjust tab * 5 + length user string + call rjust tab * 10 + length date - length user string
print
for text in text
begin
if text at string type == string text
begin
set n_rows = call round_up length text a... | def print_result(self, result):
print('-' * 100)
print(f'Votes: {result.votes}'.rjust(7 + len(result.votes) + self.tab, ' ') +
f'User: {result.user}'.rjust(self.tab * 5 + len(result.user), ' ') +
f"Date: {result.date}".rjust(self.tab * 10 + len(result.date) - len(r... | Python | nomic_cornstack_python_v1 |
function table self
begin
return get pulumi self string table
end function | def table(self) -> Optional[str]:
return pulumi.get(self, "table") | Python | nomic_cornstack_python_v1 |
function task_died handle
begin
set exception = exception
if exception is none
begin
debug string Task finished: %s string handle
return
end
call stop
call print_stack
end function | def task_died(handle):
exception = handle.exception()
if exception is None:
logger.debug('Task finished: %s', str(handle))
return
asyncio.get_event_loop().stop()
handle.print_stack() | Python | nomic_cornstack_python_v1 |
comment Abhinav Pachauri #########################################################################
comment In order to run on the content extractor on command line just type: python content_extractor.py -i <inputfile_name> #####
comment A folder named "output" will be created at the path where this file "content_extrac... | ############################################## Abhinav Pachauri #########################################################################
############## In order to run on the content extractor on command line just type: python content_extractor.py -i <inputfile_name> #####
############# A folder named "output" will b... | Python | zaydzuhri_stack_edu_python |
function median_subtract flux window
begin
set size = length flux
set nPoints = window
set filtered = zeros size
for i in range size
begin
comment This two step ensures that lwr and upr lie in the range [0,size)
set lwr = max i - nPoints 0
set upr = min lwr + 2 * nPoints size
set lwr = upr - 2 * nPoints
set sub = flux ... | def median_subtract(flux, window):
size = len(flux)
nPoints = window
filtered = np.zeros(size)
for i in range(size):
#This two step ensures that lwr and upr lie in the range [0,size)
lwr = max(i-nPoints, 0)
upr = min(lwr + 2*nPoints, size)
lwr = upr- 2*nPoints
... | Python | nomic_cornstack_python_v1 |
comment Created by Aashish Adhikari at 10:00 AM 1/15/2021
string Time Complexity: O(n) since we traverse to each node once. Space Complexity: O(height of the tree) as we are maintaining a recursive stack under the hood.
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self... | # Created by Aashish Adhikari at 10:00 AM 1/15/2021
'''
Time Complexity:
O(n) since we traverse to each node once.
Space Complexity:
O(height of the tree) as we are maintaining a recursive stack under the hood.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=No... | Python | zaydzuhri_stack_edu_python |
function miasta_panstwa city country population=string
begin
string Funkcja z miastami i państwami.
if population
begin
return title city + string , + title country + string - populacja + population
end
else
begin
return title city + string , + title country
end
end function | def miasta_panstwa(city, country, population=''):
"""Funkcja z miastami i państwami."""
if population:
return city.title() + ", " + country.title() + ' - populacja ' + \
population
else:
return city.title() + ", " + country.title()
| Python | zaydzuhri_stack_edu_python |
function is_member_suggestions_change_policy self
begin
return _tag == string member_suggestions_change_policy
end function | def is_member_suggestions_change_policy(self):
return self._tag == 'member_suggestions_change_policy' | Python | nomic_cornstack_python_v1 |
function summarise_data trip_in station_data trip_out
begin
comment generate dictionary of station - city mapping
set station_map = call create_station_mapping station_data
string Below implementation is using csv read write module. But this can be very easily implemented using Pandas Dataframe
with open trip_out strin... | def summarise_data(trip_in, station_data, trip_out):
# generate dictionary of station - city mapping
station_map = create_station_mapping(station_data)
"""Below implementation is using csv read write module. But this can be very easily implemented
using Pandas Dataframe"""
with open(trip_out, 'w'... | Python | nomic_cornstack_python_v1 |
from nepali_unicode_converter.convert import Converter
set test_cases = list tuple string gaahro string गाह्रो tuple string phone number 98432 string फोन नम्बर ९८४३२ tuple string aaNNkhaa string आँखा tuple string samRIddha string समृद्ध tuple string samaRIddha string समृद्ध tuple string garyo string गर्यो tuple string ... | from nepali_unicode_converter.convert import Converter
test_cases = [
('gaahro', 'गाह्रो'),
('phone number 98432', 'फोन नम्बर ९८४३२'),
('aaNNkhaa', 'आँखा'),
('samRIddha', 'समृद्ध'),
('samaRIddha', 'समृद्ध'),
('garyo', 'गर्यो'),
('hudai', 'हुँदै'),
('mero instagram', 'मेरो इन्स्टाग्राम'... | Python | zaydzuhri_stack_edu_python |
import multiprocessing
class FloatChannel extends object
begin
function __init__ self maxsize
begin
set buffer = call RawArray string d maxsize
comment 共享内存中创建int类型数据
set buffer_len = call Value string i
set empty = semaphore 1
set full = semaphore 0
end function
function send self value
begin
acquire empty
set nitems ... | import multiprocessing
class FloatChannel(object):
def __init__(self, maxsize):
self.buffer = multiprocessing.RawArray('d', maxsize)
self.buffer_len = multiprocessing.Value('i') #共享内存中创建int类型数据
self.empty = multiprocessing.Semaphore(1)
self.full = multiprocessing.Semaphore(0)
d... | Python | zaydzuhri_stack_edu_python |
function main
begin
set parser = call ArgumentParser description=string Renumber atoms and residues from a 3D structure. formatter_class=lambda prog -> call RawTextHelpFormatter prog width=99999
call add_argument string -c string --config required=false help=string This file can be a YAML file, JSON file or JSON string... | def main():
parser = argparse.ArgumentParser(description="Renumber atoms and residues from a 3D structure.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
parser.add_argument('-c', '--config', required=False, help="This file can be a YAML file, JSON file or JSON string")
# ... | Python | nomic_cornstack_python_v1 |
function offset_relative_base self value
begin
set _relative_base = _relative_base + value
end function | def offset_relative_base(self, value: int) -> None:
self._relative_base += value | Python | nomic_cornstack_python_v1 |
from stack import Stack
function check_parantheses_balance s
begin
set opn = list string { string [ string (
set clse = list string } string ] string )
set st = stack
for i in range 0 length s
begin
if s at i in opn
begin
call push s at i
end
else
if call isEmpty
begin
return string Not balanced
end
else
begin
set elem... | from stack import Stack
def check_parantheses_balance(s):
opn = ['{','[','(']
clse = ['}',']',')']
st = Stack()
for i in range(0, len(s)):
if s[i] in opn:
st.push(s[i])
else:
if st.isEmpty():
return "Not balanced"
else:
... | Python | zaydzuhri_stack_edu_python |
import json
set json_string = string { "location": "Berlin", "weather": { "temperature": 17.6 } }
set data = loads json_string
set temperature = data at string weather at string temperature | import json
json_string = '''
{
"location": "Berlin",
"weather": {
"temperature": 17.6
}
}
'''
data = json.loads(json_string)
temperature = data["weather"]["temperature"] | Python | iamtarun_python_18k_alpaca |
from binascii import hexlify , unhexlify
import requests
import json
from dht.common_utils import generate_node_id
from dht.crawler.krpc import DHTProtocol
function __try_load_routing_table web_server_api_url local_node_host local_node_port local_node_id=none
begin
set response = json get requests format string {0}/loa... | from binascii import hexlify, unhexlify
import requests
import json
from dht.common_utils import generate_node_id
from dht.crawler.krpc import DHTProtocol
def __try_load_routing_table(web_server_api_url, local_node_host, local_node_port, local_node_id=None):
response = requests.get(
"{0}/load_routing_tabl... | Python | zaydzuhri_stack_edu_python |
function save_metric_plots_at self path
begin
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
call use string ggplot
if length _metrics <= 0 or length epochs <= 0
begin
return
end
set dev = list
list comprehension call mean_metrics for epoch in epochs
for epoch in epochs
begin
if dev_log is not n... | def save_metric_plots_at(self, path):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
if len(self._metrics) <= 0 or len(self.epochs) <= 0:
return
dev = []
[epoch.dev_log.mean_metrics() for epoch in... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from astropy.io import fits
comment Load the ids of the available galaxies
set non_AGN_list = call loadtxt string ../Text_Files/nonAGN.txt
set seyfert_before = call loadtxt string ../Text_Files/seyfert_before.txt
set sf_before = call loadtxt string ../Text_Files/sf_before.txt
set ... | import pandas as pd
import numpy as np
from astropy.io import fits
# Load the ids of the available galaxies
non_AGN_list = np.loadtxt('../Text_Files/nonAGN.txt')
seyfert_before = np.loadtxt('../Text_Files/seyfert_before.txt')
sf_before = np.loadtxt('../Text_Files/sf_before.txt')
liner_before = np.loadtxt('../Text_Fil... | Python | zaydzuhri_stack_edu_python |
try
begin
print string The sum of these no is :- integer num1 + integer num2
end
except Exception as e
begin
print e
end
print string important | try:
print("The sum of these no is :- ", int(num1)+int(num2))
except Exception as e:
print(e)
print("important") | Python | zaydzuhri_stack_edu_python |
comment config: utf8
import boto3
import pandas as pd
function create_s3_bucket bucket_name
begin
string Funcion que crea el bucket en AWS. El busket no tiene acceso publico y esta encriptado. Input: bucket_name: Nombre del bucket
set s3_client = call resource string s3
comment Bandera para ver si se creo exitosamente
... | # config: utf8
import boto3
import pandas as pd
def create_s3_bucket(bucket_name):
"""
Funcion que crea el bucket en AWS.
El busket no tiene acceso publico y esta encriptado.
Input:
bucket_name: Nombre del bucket
"""
s3_client = boto3.resource("s3")
exito = 0 # Bandera para v... | Python | zaydzuhri_stack_edu_python |
function solve_b self sess x_b_np y_b_np fdict=none
begin
set tconfig = transfer_config
set steps = max_train_steps
set batch_size = batch_size
set rnd = call RandomState 0
comment Re-initialize the fast weights.
comment self.reset_b(sess)
if fdict is none
begin
set fdict = dict
end
if batch_size == - 1
begin
set fdic... | def solve_b(self, sess, x_b_np, y_b_np, fdict=None):
tconfig = self.config.transfer_config
steps = tconfig.ft_optimizer_config.max_train_steps
batch_size = tconfig.ft_optimizer_config.batch_size
rnd = np.random.RandomState(0)
# Re-initialize the fast weights.
# self.reset_b(sess)
if f... | Python | nomic_cornstack_python_v1 |
import socket
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import os
print string -----------------------------------------------------
print string WELCOME TO SECURE SERVER
print string Please enter...
set username = input string Username :
set password = input string Password... | import socket
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import os
print("-----------------------------------------------------")
print("WELCOME TO SECURE SERVER")
print("Please enter...")
username = input("Username : ")
password = input("Password : ")
s=socket.so... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Module :
comment Author : fengfeng
comment Date : 2018-10-02
comment Version : 1.0
comment Desc : 日期处理
import time , datetime , calendar
function getToday_s fmt=string %Y%m%d
begin
string 获取今天 str :param fmt: :return: yyyyMMdd
return string format time time fmt call localtime decim... | # -*- coding: utf-8 -*-
# Module :
# Author : fengfeng
# Date : 2018-10-02
# Version : 1.0
# Desc : 日期处理
import time, datetime, calendar
#
def getToday_s(fmt='%Y%m%d'):
'''
获取今天 str
:param fmt:
:return: yyyyMMdd
'''
return time.strftime(fmt, time.localtime(float(time.time())))
... | Python | zaydzuhri_stack_edu_python |
import pygame
comment img = pygame.image.load('monalisa.jpg')
comment white = (255, 255, 255)
comment w = 300
comment h = 300
comment screen = pygame.display.set_mode((w, h))
comment screen.fill((white))
comment running = 1
comment screen.blit(img,(0,0))
comment pygame.display.flip()
function main
begin
set image = cal... | import pygame
#img = pygame.image.load('monalisa.jpg')
#white = (255, 255, 255)
#w = 300
#h = 300
#screen = pygame.display.set_mode((w, h))
#screen.fill((white))
#running = 1
#screen.blit(img,(0,0))
#pygame.display.flip()
def main():
image=setUpImage()
readImageFromFile(image,"monalisa.jpg")
raw_input("Was ist ... | Python | zaydzuhri_stack_edu_python |
function json_dumps obj
begin
try
begin
return dumps obj indent=2
end
except TypeError
begin
comment Not json encodable
return string obj
end
end function | def json_dumps(obj: dict):
try:
return json.dumps(obj, indent=2)
except TypeError:
# Not json encodable
return str(obj) | Python | nomic_cornstack_python_v1 |
class stack
begin
function __init__ self
begin
set lst_stack = list
end function
function push self val
begin
append lst_stack val
end function
function peek self
begin
return lst_stack at - 1
end function
function size self
begin
return length lst_stack
end function
function pop self
begin
if size self
begin
pop lst_... | class stack:
def __init__(self):
self.lst_stack = []
def push(self, val):
self.lst_stack.append(val)
def peek(self):
return self.lst_stack[-1]
def size(self):
return len(self.lst_stack)
def pop(self):
if self.size():
self.lst_st... | Python | zaydzuhri_stack_edu_python |
from pygame import *
import math
import random
call init
comment 화면설정
string 1. 화면생성
set screen = call set_mode tuple 1200 800
string 2. Title
call set_caption string 고군분투 따라잡기
string 3. 배경담기
set bg1 = load image string e:/dev/python_workspace/img/bg1.jpg
set bg2 = load image string e:/dev/python_workspace/img/bg2.jpg
... | from pygame import *
import math
import random
init()
# 화면설정
'''1. 화면생성'''
screen = display.set_mode((1200,800))
'''2. Title'''
display.set_caption("고군분투 따라잡기")
'''3. 배경담기'''
bg1 = image.load('e:/dev/python_workspace/img/bg1.jpg')
bg2 = image.load('e:/dev/python_workspace/img/bg2.jpg')
bg1 = transform.scale(bg1,(1... | Python | zaydzuhri_stack_edu_python |
function bilinear_interpolation self image fx fy
begin
comment Write your code for bilinear interpolation here
set tuple width height = shape at slice : 2 :
set nw = integer width * fx
set nh = integer height * fy
set new_img = zeros tuple nw nh uint8
set inter = call interpolation
for i in range nw
begin
for j in ra... | def bilinear_interpolation(self, image, fx, fy):
# Write your code for bilinear interpolation here
width, height = image.shape[:2]
nw = int(width * fx)
nh = int(height * fy)
new_img = np.zeros((nw, nh), np.uint8)
inter = interpolation.interpolation()
for ... | Python | nomic_cornstack_python_v1 |
function append_talk_show_snippets input_dir temp_storage_dir politician
begin
with open temp_storage_dir string w+ encoding=string utf-8 as output
begin
for filename in list directory input_dir
begin
set content = call get_clean_content filename input_dir politician
write output content
end
end
end function | def append_talk_show_snippets(input_dir, temp_storage_dir, politician):
with open(temp_storage_dir, "w+", encoding="utf-8") as output:
for filename in os.listdir(input_dir):
content = get_clean_content(filename, input_dir, politician)
output.write(content) | Python | nomic_cornstack_python_v1 |
from python.Lexer import *
from python.Tokenizer import *
from python.LED_GameParser import *
from python.LED_GameCompiler_js import *
import os
import shutil
comment This function is used for debugging purposes and will print the results of intermediate functions
function compile_LED_to_JS LED_code_string
begin
set LE... | from python.Lexer import *
from python.Tokenizer import *
from python.LED_GameParser import *
from python.LED_GameCompiler_js import *
import os
import shutil
# This function is used for debugging purposes and will print the results of intermediate functions
def compile_LED_to_JS(LED_code_string):
LED_code = pr... | Python | zaydzuhri_stack_edu_python |
comment 输入年份 如果是闰年输出True 否则输出False
set year = integer input string 请输入年份:
set is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0
if is_leap
begin
print string %s是闰年 % string year
end
else
begin
print string %2s是平年 % string year
end | # 输入年份 如果是闰年输出True 否则输出False
year = int(input("请输入年份:"))
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
if is_leap:
print("%s是闰年" % str(year))
else:
print("%2s是平年" % str(year))
| Python | zaydzuhri_stack_edu_python |
function _suppress_logger loggerName level=CRITICAL
begin
set logger = call getLogger loggerName
set original_level = call getEffectiveLevel
call setLevel level
try
begin
yield
end
finally
begin
call setLevel original_level
end
end function | def _suppress_logger(loggerName: str, level=logging.CRITICAL):
logger = logging.getLogger(loggerName)
original_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield
finally:
logger.setLevel(original_level) | Python | nomic_cornstack_python_v1 |
function distance self ts1 ts2
begin
set sax = transform self list ts1 ts2
return call distance_sax sax at 0 sax at 1
end function | def distance(self, ts1, ts2):
sax = self.transform([ts1, ts2])
return self.distance_sax(sax[0], sax[1]) | Python | nomic_cornstack_python_v1 |
comment 사용자 정의 모듈
set a = 10
print a
function aa
begin
print string aa 만세
end function
comment 외부 모듈의 멤버 사용하기
comment 경로 지정
import pack2.test12my
print string tot : tot
set li1 = list 1 2
set li2 = list 3 4
call ListHap li1 li2
function abc
begin
if __name__ == string __main__
begin
print string 응용 프로그램이 시작되는 모듈
end
en... | # 사용자 정의 모듈
a = 10
print(a)
def aa():
print('aa 만세')
# 외부 모듈의 멤버 사용하기
import pack2.test12my # 경로 지정
print('tot :', pack2.test12my.tot)
li1 = [1, 2]
li2 = [3, 4]
pack2.test12my.ListHap(li1, li2)
def abc():
if __name__ == '__main__':
print('응용 프로그램이 시작되는 모듈')
abc()
p... | Python | zaydzuhri_stack_edu_python |
from itertools import combinations
from math import factorial , floor
function euler121
begin
set j = decimal call factorial 16 / call winning 15
end function | from itertools import combinations
from math import factorial, floor
def euler121():
j = float(factorial(16))/winning(15) | Python | zaydzuhri_stack_edu_python |
function download resources_data dir_path get_response get_content save need_dir=true
begin
comment noqa: F811
if resources_data is none
begin
debug string Downloading skipped.
return none
end
if need_dir
begin
call ensure_dir dir_path
end
set bar = call IncrementalBar string Downloading: max=BAR_WIDTH
set suffix = str... | def download(resources_data, dir_path, get_response,
get_content, save, need_dir=True): # noqa: F811
if resources_data is None:
logger.debug('Downloading skipped.')
return None
if need_dir:
ensure_dir(dir_path)
bar = IncrementalBar('Downloading:', max=BAR_W... | Python | nomic_cornstack_python_v1 |
comment 2020-08-30, Sun
set n = integer input
set lis = sorted list map int split input reverse=true
set a = 0
set b = 0
for i in lis at slice : : 2
begin
set a = a + i
end
for i in lis at slice 1 : : 2
begin
set b = b + i
end
print a - b | # 2020-08-30, Sun
n = int(input())
lis = sorted(list(map(int, input().split())), reverse=True)
a = 0
b = 0
for i in lis[::2]:
a += i
for i in lis[1::2]:
b += i
print(a - b) | Python | zaydzuhri_stack_edu_python |
function euler diStr row
begin
set jVals = call diStrToJVals diStr row
set tensor = row at string tensor
set c2 = row at string chern2
set euler = 0
for a in jVals
begin
for b in c2
begin
set euler = euler + a at 0 + b at 0 * tensor at a at 1 - 1 at b at 1 - 1 at b at 2 - 1
end
end
return euler
end function | def euler(diStr, row):
jVals = diStrToJVals(diStr, row)
tensor = row['tensor']
c2 = row['chern2']
euler = 0
for a in jVals:
for b in c2:
euler += a[0] + b[0] * tensor[a[1]-1][b[1]-1][b[2]-1]
return euler | Python | nomic_cornstack_python_v1 |
function getBoxPosition self sort boxIdx *sets **kw
begin
set evtsPerBox = pop kw string evtsPerBox none
set remainder = pop kw string remainder none
set maxEvts = pop kw string maxEvts none
set takeFrom = none
from math import floor
comment Check parameters
if maxEvts is not none
begin
if maxEvts < 0
begin
call _fatal... | def getBoxPosition(self, sort, boxIdx, *sets, **kw):
evtsPerBox = kw.pop( 'evtsPerBox', None )
remainder = kw.pop( 'remainder', None )
maxEvts = kw.pop( 'maxEvts', None )
takeFrom = None
from math import floor
# Check parameters
if maxEvts is not None:
if maxEvts < 0:
self._fat... | Python | nomic_cornstack_python_v1 |
function waitForDevicePm self wait_time=120
begin
log string Waiting for device package manager...
call sendCommand string wait-for-device
comment Now the device is there, but may not be running.
comment Query the package manager with a basic command
try
begin
call _waitForShellCommandContents string pm path android st... | def waitForDevicePm(self, wait_time=120):
logger.Log("Waiting for device package manager...")
self.sendCommand("wait-for-device")
# Now the device is there, but may not be running.
# Query the package manager with a basic command
try:
self._waitForShellCommandContents... | Python | nomic_cornstack_python_v1 |
function esfericaCoordenada x y z
begin
from math import atan , sqrt , pi
set r = square root x ^ 2 + y ^ 2 + z ^ 2
if z > 0
begin
set phi = call atan square root x ^ 2 + y ^ 2 / z
end
end function | def esfericaCoordenada(x, y, z):
from math import atan, sqrt, pi
r=sqrt(x**2+y**2+z**2)
if z>0:
phi=atan(sqrt(x**2+y**2)/z) | Python | zaydzuhri_stack_edu_python |
function OnColumnResize self event
begin
set iColumn = call GetColumn
set column = call getParam string columns at iColumn
set call updateParam string colWidths at column = call GetColumnWidth iColumn
end function | def OnColumnResize(self,event):
iColumn = event.GetColumn()
column = self.data.getParam('columns')[iColumn]
self.data.updateParam('colWidths')[column] = self.gList.GetColumnWidth(iColumn) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys
from sys import stderr
function Solve combs opos invoke
begin
tuple print ? stderr combs opos invoke
set dcombs = dict
for c in combs
begin
set dcombs at c at 0 + c at 1 = c at 2
set dcombs at c at 1 + c at 0 = c at 2
end
tuple print ? stderr dcombs
set dopos = dict
for o in opos
b... | #!/usr/bin/python
import sys
from sys import stderr
def Solve(combs, opos, invoke):
print >>stderr, combs, opos, invoke
dcombs = {}
for c in combs:
dcombs[c[0]+c[1]] = c[2]
dcombs[c[1]+c[0]] = c[2]
print >>stderr, dcombs
dopos = {}
for o in opos:
dopos[o[0]] = dopos.ge... | Python | zaydzuhri_stack_edu_python |
comment slicing:extracting one or more values from list
comment index 0 1 2 3 4
set students = list string Ali string Faisal string Saleem string faraz string Hamza
comment index -5 -4 -3 -2 -1
comment to ascess single value
print students at 0
print students at - 5
comment list have double index
comment listname[start... | #slicing:extracting one or more values from list
#index 0 1 2 3 4
students=["Ali","Faisal","Saleem","faraz","Hamza"]
#index -5 -4 -3 -2 -1
#to ascess single value
print(students[0])
print(students[-5])
#list have double index
#listname[start;end+1]
a=stude... | Python | zaydzuhri_stack_edu_python |
import hashlib as hl
import json
comment __all__ = ['hash_string256','hash_block']
function hash_string256 string
begin
return hex digest sha256 string
end function
function hash_block block
begin
string Hashes a block and returns a string representation of it
set hashable_block = copy __dict__
set hashable_block at st... | import hashlib as hl
import json
##__all__ = ['hash_string256','hash_block']
def hash_string256(string):
return hl.sha256(string).hexdigest()
def hash_block(block):
""" Hashes a block and returns a string representation of it"""
hashable_block = block.__dict__.copy()
hashable_block['trans... | Python | zaydzuhri_stack_edu_python |
function undrained_bulk_modulus self locs
begin
set tuple npts dim = shape
set undrained_bulk_modulus = K_u * ones tuple 1 npts 1 dtype=float64
return undrained_bulk_modulus
end function | def undrained_bulk_modulus(self, locs):
(npts, dim) = locs.shape
undrained_bulk_modulus = K_u * numpy.ones((1, npts, 1), dtype=numpy.float64)
return undrained_bulk_modulus | Python | nomic_cornstack_python_v1 |
function delete request username date time room
begin
comment see where the delete call was made from (can be from homepage or manage)
set referer = get META string HTTP_REFERER
try
begin
set user = get objects username=username
if loggedIn
begin
set fullname = fullname
set username = username
end
else
begin
return cal... | def delete(request,username,date,time,room):
# see where the delete call was made from (can be from homepage or manage)
referer = request.META.get('HTTP_REFERER')
try:
user = UserInfo.objects.get(username = username)
if(user.loggedIn):
fullname = user.fullname
usernam... | Python | nomic_cornstack_python_v1 |
function to_str self
begin
import simplejson as json
if PY2
begin
import sys
call reload sys
call setdefaultencoding string utf-8
end
return dumps call sanitize_for_serialization self ensure_ascii=false
end function | def to_str(self):
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) | Python | nomic_cornstack_python_v1 |
function template_path name
begin
set template_dir = join path directory name path __file__ string templates
return join path template_dir name + string .html
end function | def template_path(name):
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
return os.path.join(template_dir, (name + ".html")) | Python | nomic_cornstack_python_v1 |
function write_optimized_graph g2o_graph_optimization num_vertices file_name
begin
set f = open file_name string w
for i in range num_vertices + 1
begin
write f call format_vertex call get_pose i i + string
end
close f
end function | def write_optimized_graph(g2o_graph_optimization, num_vertices, file_name):
f = open(file_name, "w")
for i in range(num_vertices + 1):
f.write(format_vertex(g2o_graph_optimization.get_pose(i), i) + "\n")
f.close() | Python | nomic_cornstack_python_v1 |
function resubmit self
begin
return _resubmit
end function | def resubmit(self):
return self._resubmit | Python | nomic_cornstack_python_v1 |
function validate_price self key p
begin
if p is not none and p < 0
begin
raise call DBException dict string message string Default price cannot be less than zero. ; string code string price
end
return p
end function | def validate_price(self, key, p):
if p is not None and p < 0:
raise DBException({'message': 'Default price cannot be less than zero.', 'code': 'price'})
return p | Python | nomic_cornstack_python_v1 |
import sys
function printCycle x tortoise
begin
set result = list
set hare = tortoise
set i = 0
while 2 * i < length x
begin
set t = x at i
set h = x at hare
end
end function | import sys
def printCycle(x, tortoise):
result = []
hare = tortoise
i = 0
while 2*i < len(x):
t = x[i]
h = x[hare] | Python | zaydzuhri_stack_edu_python |
function nonzero self
begin
call check_zero_fill_value self
return tuple coords
end function | def nonzero(self):
check_zero_fill_value(self)
return tuple(self.coords) | Python | nomic_cornstack_python_v1 |
function test_list_tokens_transfers_by_address self
begin
pass
end function | def test_list_tokens_transfers_by_address(self):
pass | Python | nomic_cornstack_python_v1 |
string HW3-Problem3
string authora@monicayan
from scipy.io import loadmat
import numpy as np
import pandas as pd
set data = call loadmat string hw3data.mat
set x_train = data at string data
set y_train = data at string labels
set x_train = insert np x_train 0 1 axis=1
comment global x_train
function log_odd beta1
begin... | '''HW3-Problem3'''
'''authora@monicayan'''
from scipy.io import loadmat
import numpy as np
import pandas as pd
data=loadmat('hw3data.mat')
x_train=data['data']
y_train=data['labels']
x_train=np.insert(x_train,0,1,axis=1)
#global x_train
def log_odd(beta1):
log_odd=np.exp(x_train.dot(beta1))/(1+np.exp(x_train.do... | Python | zaydzuhri_stack_edu_python |
function feature self feature
begin
set _feature = feature
end function | def feature(self, feature):
self._feature = feature | Python | nomic_cornstack_python_v1 |
function GetValidLabelValues self
begin
return call itkLabelStatisticsImageFilterISS3ISS3_GetValidLabelValues self
end function | def GetValidLabelValues(self) -> "std::vector< short,std::allocator< short > > const &":
return _itkLabelStatisticsImageFilterPython.itkLabelStatisticsImageFilterISS3ISS3_GetValidLabelValues(self) | Python | nomic_cornstack_python_v1 |
comment ! Python3
import sys
set A = integer argv at 1
set B = integer argv at 3
set Opr = argv at 2
print string A + string and + string B
if Opr == string +
begin
print string A + string + Opr + string + string B + string = + string A + B
end
else
if Opr == string -
begin
print string A + string + Opr + string + ... | #! Python3
import sys
A = int(sys.argv[1])
B = int(sys.argv[3])
Opr = sys.argv[2]
print(str(A) + ' and '+ str(B))
if Opr == '+':
print (str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A+B))
elif Opr == '-':
print(str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A-B))
elif (Opr == 'x') or (Opr == '*'):
print... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment Copyright 2019 Colin. All Rights Reserved.
comment THESE MATERIALS ARE PROVIDED ON AN "AS IS" BASIS. AMAZON SPECIFICALLY DISCLAIMS, WITH
comment RESPECT TO THESE MATERIALS, ALL WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
comment THE IMPLIED WARRANTIES OF MERCHANTABILITY, ... | #!/usr/bin/env python3
# Copyright 2019 Colin. All Rights Reserved.
#
# THESE MATERIALS ARE PROVIDED ON AN "AS IS" BASIS. AMAZON SPECIFICALLY DISCLAIMS, WITH
# RESPECT TO THESE MATERIALS, ALL WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
# THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR P... | Python | zaydzuhri_stack_edu_python |
function add_notify_date values username
begin
set cursor = call cursor
execute cursor string INSERT INTO notification_tracker(id,notify_date,username) VALUES (%s, %s,%s) tuple values at 0 values at 5 username
comment text = cursor.fetchone()[0]
commit conn
print string Notifier date added to notification_tracker table... | def add_notify_date(values,username):
cursor = conn.cursor()
cursor.execute("INSERT INTO notification_tracker(id,notify_date,username) VALUES (%s, %s,%s)",
(values[0], values[5],username))
# text = cursor.fetchone()[0]
conn.commit()
print("Notifier date added to notification_trac... | Python | nomic_cornstack_python_v1 |
function disabled_player_pits self player disable
begin
set wonted_player = call get_player player
yield call disable_pit jackpot
for pit in pits
begin
if disable or stones == 0
begin
yield call disable_pit pit
end
else
begin
yield call enable_pit pit
end
end
end function | def disabled_player_pits(self, player: bool, disable: bool) -> Iterator[ImpactData]:
wonted_player = self.get_player(player)
yield ImpactData.disable_pit(wonted_player.jackpot)
for pit in wonted_player.pits:
if disable or pit.stones == 0:
yield ImpactData.disable_pit... | Python | nomic_cornstack_python_v1 |
from itertools import *
from os import *
from pylab import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
import time
string README: https://github.com/wiggoen/FYS3150/blob/master/Project_3/README.md
comment System setup
set numTimesteps = 1000
set dt = 0.001
set outfilemode = string Python
s... | from itertools import *
from os import *
from pylab import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
import time
"""
README: https://github.com/wiggoen/FYS3150/blob/master/Project_3/README.md
"""
# System setup
numTimesteps = 1000
dt = 0.001
outfilemode = "Python"
outfilename = "positi... | Python | zaydzuhri_stack_edu_python |
function fs_mkdir self dirname
begin
call exec_ string import uos uos.mkdir('%s') % dirname
end function | def fs_mkdir(self, dirname: str) -> None:
self.exec_("import uos\nuos.mkdir('%s')" % dirname) | Python | nomic_cornstack_python_v1 |
from math import gcd
import random , time
function gcdcount n m
begin
set tuple x y = tuple min n m max n m
if x == 0
begin
return 0
end
else
begin
return 1 + call gcdcount x y % x
end
end function
set fibo = list 0 1 2
for i in range 100
begin
append fibo fibo at - 1 + fibo at - 2
end
set gcdfibo = list list list tup... | from math import gcd
import random,time
def gcdcount(n,m):
x,y=min(n,m),max(n,m)
if x==0:
return 0
else:
return 1+gcdcount(x,y%x)
fibo=[0,1,2]
for i in range(100):
fibo.append(fibo[-1]+fibo[-2])
gcdfibo=[[],[(1,2),(1,3)]]
for i in range(2,101):
temp=[]
for a,b in gcdfibo[-1]:... | Python | jtatman_500k |
function item self
begin
set query = query collection service_id=service_id
call add_term field=id_field value=item_id
return call InstanceProxy Item query client=_client
end function | def item(self) -> InstanceProxy[Item]:
query = Query(Item.collection, service_id=self._client.service_id)
query.add_term(field=Item.id_field, value=self.data.item_id)
return InstanceProxy(Item, query, client=self._client) | Python | nomic_cornstack_python_v1 |
function DeAccum self time_steps indent=string
begin
comment modules:
import logging
import netCDF4
import numpy
import datetime
comment testing ...
comment import shutil
comment create backup:
comment shutil.copy( self.filename, self.filename+'.bak' )
comment info ...
debug indent + string convert from accumulated val... | def DeAccum( self, time_steps, indent='' ) :
# modules:
import logging
import netCDF4
import numpy
import datetime
## testing ...
#import shutil
## create backup:
#shutil.copy( self.filename, self.filename+'.bak' )
# info ...
... | Python | nomic_cornstack_python_v1 |
function as_callback_hook hook_name hook_type hook_status force_deploy
begin
return dict string name hook_name ; string type hook_type ; string status hook_status ; string force-deploy force_deploy
end function | def as_callback_hook(hook_name, hook_type, hook_status, force_deploy):
return {
'name': hook_name,
'type': hook_type,
'status': hook_status,
'force-deploy': force_deploy
} | Python | nomic_cornstack_python_v1 |
comment CloudFormation Outputs Collector. An alternative to static release notes.
comment Retrieves outputs for a set of environment stacks and writes them to a csv file.
comment Usage example get-stackouts.py -environment "dev01" -outputpath c:/
comment Author: Jonathan Rudge
import boto3
import re
import csv
import t... | #CloudFormation Outputs Collector. An alternative to static release notes.
#Retrieves outputs for a set of environment stacks and writes them to a csv file.
#Usage example get-stackouts.py -environment "dev01" -outputpath c:/
#Author: Jonathan Rudge
import boto3
import re
import csv
import time
import argparse
parser... | Python | zaydzuhri_stack_edu_python |
function _update_config_lines self config_line
begin
set entry = call ConfigLine config_line _current_parents
append config_lines entry
end function | def _update_config_lines(self, config_line):
entry = ConfigLine(config_line, self._current_parents)
self.config_lines.append(entry) | Python | nomic_cornstack_python_v1 |
comment 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
comment Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
set number_find = integer input string Введите, какую цифру мы ищем:
set n = integer input string Введите количест... | # 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
# Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
number_find = int(input('Введите, какую цифру мы ищем: '))
n = int(input('Введите количество чисел для поиска: '))
result = 0
... | Python | zaydzuhri_stack_edu_python |
function are_lists_equal list1 list2
begin
if sorted list1 == sorted list2
begin
return true
end
else
begin
return false
end
end function | def are_lists_equal(list1, list2):
if sorted(list1) == sorted(list2):
return True
else:
return False | Python | nomic_cornstack_python_v1 |
import requests , json
from flask import jsonify
class Http
begin
decorator staticmethod
function get url return_json=true
begin
set response = get requests url=url
comment print(response.content.decode("utf-8"))
if status_code != 200
begin
return if expression return_json then string else dict
end
return if expressi... | import requests,json
from flask import jsonify
class Http:
@staticmethod
def get(url,return_json=True):
response=requests.get(url=url)
# print(response.content.decode("utf-8"))
if response.status_code!=200:
return "" if return_json else {}
return json.loads(response... | 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.