code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
import csv
import copy
import operator
with open string p1.csv string rb as f
begin
set reader = reader f
set f1_0 = map list reader
end
set f1 = deep copy f1_0
with open string p2.csv string rb as f
begin
set reader = reader f
set f2_0 = map list reader
end
set f2 = deep copy f2_0
set p1 ... | # -*- coding: utf-8 -*-
import csv
import copy
import operator
with open('p1.csv', 'rb') as f:
reader = csv.reader(f)
f1_0 = map(list, reader)
f1 = copy.deepcopy(f1_0)
with open('p2.csv', 'rb') as f:
reader = csv.reader(f)
f2_0 = map(list, reader)
f2 = copy.deepcopy(f2_0)
p1 = []
p2 = []
p1p2 = []
f... | Python | zaydzuhri_stack_edu_python |
function create_security_configuration self Name EncryptionConfiguration
begin
pass
end function | def create_security_configuration(self, Name: str, EncryptionConfiguration: Dict) -> Dict:
pass | Python | nomic_cornstack_python_v1 |
function trapezoidal_rule_step self f jac y0 t0 t1 f_params jac_params
begin
comment implicit method requires solving a non-linear equation in y1
set F = lambda y1 -> y1 - y0 + 0.5 * t1 - t0 * f dist t0 y0 *f_params + 0.5 * t1 - t0 * f dist t1 y1 *f_params
comment create jacobian for F using jac
set F_jac = lambda y1 -... | def trapezoidal_rule_step(self, f, jac, y0, t0, t1, f_params, jac_params):
# implicit method requires solving a non-linear equation in y1
F = lambda y1: y1 - (y0 + (0.5 * (t1 - t0) * f(t0, y0, *f_params) +
0.5 * (t1 - t0) * f(t1, y1, *f_params)))
# create jacobian... | Python | nomic_cornstack_python_v1 |
import heapq
comment 시간초과
function solution1 dead_cups
begin
set dead_cups = sorted dead_cups key=lambda x -> tuple x at 0 - x at 1 reverse=true
set tuple now result = pop dead_cups
while dead_cups
begin
set tuple deadline cup = pop dead_cups
if deadline != now
begin
set now = deadline
set result = result + cup
end
end... | import heapq
# 시간초과
def solution1(dead_cups):
dead_cups = sorted(dead_cups, key=lambda x: (x[0], -x[1]), reverse=True)
now, result = dead_cups.pop()
while dead_cups:
deadline, cup = dead_cups.pop()
if deadline != now:
now = deadline
result += cup
print(result... | Python | zaydzuhri_stack_edu_python |
function circle x r a b x_lim
begin
set y = b + square root call maximum r ^ 2 - x - a ^ 2 * x >= x_lim at 0 * x <= x_lim at 1 * x >= x_lim at 0 * x <= x_lim at 1
return y
end function | def circle(x, r, a, b, x_lim):
y = (b + np.sqrt(maximum(
r ** 2 - ((x - a) ** 2) * (x >= x_lim[0]) * (x <= x_lim[1]))
)) * (x >= x_lim[0]) * (x <= x_lim[1])
return y | Python | nomic_cornstack_python_v1 |
function host_table self name table
begin
if _loop_callback is not none
begin
comment always bind the callback to the table's state manager
set queue_process = partial _loop_callback call_process
end
set _tables at name = table
return name
end function | def host_table(self, name, table):
if self._loop_callback is not None:
# always bind the callback to the table's state manager
table._state_manager.queue_process = partial(self._loop_callback, table._state_manager.call_process)
self._tables[name] = table
return name | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot , matplotlib.animation
set pyp = pyplot
set anime = animation
set shape = figure
set shaplot = call add_subplot 1 1 1
function animation x
begin
set data = read lines open string ./cpu.txt
set l = list
for value in data
begin
if length value > 1
begin
append l decimal value
end
end
clear shapl... | import matplotlib.pyplot,matplotlib.animation
pyp = matplotlib.pyplot
anime = matplotlib.animation
shape = pyp.figure()
shaplot = shape.add_subplot(1, 1, 1)
def animation(x):
data = open("./cpu.txt").readlines()
l = []
for value in data:
if len(value) > 1:
l.append(float(value))
... | Python | zaydzuhri_stack_edu_python |
function prepare_parser program
begin
string Create and populate an argument parser.
set parser = call ArgumentParser description=PROG_DESCRIPTION prog=program formatter_class=HelpFormatter add_help=false
call add_argument string -h string --help action=MinimalHelpAction help=SUPPRESS
comment Register sub-commands.
set... | def prepare_parser(program):
"""Create and populate an argument parser."""
parser = ArgumentParser(
description=PROG_DESCRIPTION, prog=program,
formatter_class=HelpFormatter,
add_help=False)
parser.add_argument(
"-h", "--help", action=MinimalHelpAction, help=argparse.SUPPRESS... | Python | jtatman_500k |
function get_nodes_in_radius self previous_node_name delay
begin
if delay in clustering_layers
begin
try
begin
set cluster = clustering_layers at 0 at string nodes at previous_node_name at delay
end
except KeyError
begin
return keys clustering_layers at 0 at string nodes
end
end
else
begin
set tuple layer_delay underly... | def get_nodes_in_radius(self, previous_node_name, delay):
if delay in self.clustering_layers:
try:
cluster = self.clustering_layers[0]['nodes'][previous_node_name][delay]
except KeyError:
return self.clustering_layers[0]['nodes'].keys()
else:
... | Python | nomic_cornstack_python_v1 |
function test_save1d_fits
begin
comment Init
set fitstbl = call dummy_fitstbl spectro_name=string shane_kast_blue directory=call data_path string
set sobj = call mk_specobj
set specObjs = call SpecObjs list sobj
set spectrograph = call load_spectrograph string shane_kast_blue
comment Write to FITS
set basename = string... | def test_save1d_fits():
# Init
fitstbl = dummy_fitstbl(spectro_name='shane_kast_blue', directory=data_path(''))
sobj = mk_specobj()
specObjs = specobjs.SpecObjs([sobj])
spectrograph = util.load_spectrograph('shane_kast_blue')
# Write to FITS
basename = 'test'
outfile = data_path('') + 's... | Python | nomic_cornstack_python_v1 |
comment Promotion constructor :)
function __init__ self router
begin
comment TODO: Use __bases__ to do this instead?
set __dict__ = __dict__
call reset
comment StatsRouters should not be destroyed when Tor forgets about them
comment Give them an extra refcount:
set refcount = refcount + 1
call plog string DEBUG string ... | def __init__(self, router): # Promotion constructor :)
# TODO: Use __bases__ to do this instead?
self.__dict__ = router.__dict__
self.reset()
# StatsRouters should not be destroyed when Tor forgets about them
# Give them an extra refcount:
self.refcount += 1
plog("DEBUG", "Stats refco... | Python | nomic_cornstack_python_v1 |
function append self value
begin
set comparisons = 0
append data value
end function | def append(self, value):
self.comparisons = 0
self.data.append(value) | Python | nomic_cornstack_python_v1 |
function Stop self *_
begin
log string Stopping...
set _stop = true
end function | def Stop(self, *_):
self.Log('Stopping...')
self._stop = True | Python | nomic_cornstack_python_v1 |
function process_folder folder_path report_config=none test_config=none
begin
set report_config = if expression report_config is none then dict else report_config
set results = call _collect_results folder_path test_config
set agg_result = call report_aggregate_results results
call upload_results report_config agg_res... | def process_folder(folder_path, report_config=None, test_config=None):
report_config = {} if report_config is None else report_config
results = _collect_results(folder_path, test_config)
agg_result = util.report_aggregate_results(results)
util.upload_results(
report_config,
agg_result,
framew... | Python | nomic_cornstack_python_v1 |
comment AUTHOR: James Beasley ##
comment DATE: March 18, 2017 ##
comment UDACITY SDC: Project 5 (Vehicle Detection/Tracking) ##
comment IMPORTS ##
import cv2
import glob
import numpy as np
import random
import pickle
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from collections... | #########################################################
## AUTHOR: James Beasley ##
## DATE: March 18, 2017 ##
## UDACITY SDC: Project 5 (Vehicle Detection/Tracking) ##
#########################################################
#############
## IMPORTS ##
#... | Python | zaydzuhri_stack_edu_python |
function create_scan self host_ips
begin
set now = now
set data = dict string uuid call get_template_uuid ; string settings dict string name string jackal- + string format time now string %Y-%m-%d %H:%M ; string text_targets host_ips
set response = post url + string scans data=dumps data verify=false headers=headers
if... | def create_scan(self, host_ips):
now = datetime.datetime.now()
data = {
"uuid": self.get_template_uuid(),
"settings": {
"name": "jackal-" + now.strftime("%Y-%m-%d %H:%M"),
"text_targets": host_ips
}
}
response = requests... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function romanToInt self s
begin
string :type s: str :rtype: int
set dic = dict string M 1000 ; string D 500 ; string C 100 ; string L 50 ; string X 10 ; string V 5 ; string I 1
set result = 0
set num = length s
if num == 0
begin
return 0
end
set pre = dic at s at 0
set result = resu... | class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
result = 0
num = len(s)
if num == 0:
return 0
pre = dic[s[0]]
result += pre
... | Python | zaydzuhri_stack_edu_python |
function hcf a b
begin
if a == 0
begin
return b
end
if b == 0
begin
return a
end
comment Find the largest power of 2 that divides both a and b
set shift = 0
while a ? b ? 1 == 0
begin
set a = a ? 1
set b = b ? 1
set shift = shift + 1
end
comment Remove all the powers of 2 from 'a' by right shifting until 'a' becomes od... | def hcf(a, b):
if a == 0:
return b
if b == 0:
return a
# Find the largest power of 2 that divides both a and b
shift = 0
while ((a | b) & 1) == 0:
a = a >> 1
b = b >> 1
shift += 1
# Remove all the powers of 2 from 'a' by right shifting until 'a' becomes ... | Python | jtatman_500k |
function start_projection self
begin
call paint_project_button true
set canvas = call ProjectionCanvas app
comment 512, 384)
load canvas
start canvas
end function | def start_projection(self):
self.paint_project_button(True)
self.app.canvas = ProjectionCanvas(self.app)
self.app.canvas.load()#512, 384)
self.app.canvas.start() | Python | nomic_cornstack_python_v1 |
function recursive_build_central_diff_matrix level
begin
if level == 1
begin
comment diagonal is [-2,1;1,-2]; right off-diagonal is [0,0;1,0];
comment left off-diagonal is [0,1;0,0];
set minus2ID = call get_valID_from_valString string -2
set oneID = call get_identity_pID 0
set zeroID = call get_zero_pID 0 0
set rodID =... | def recursive_build_central_diff_matrix(level):
if (level==1):
# diagonal is [-2,1;1,-2]; right off-diagonal is [0,0;1,0];
# left off-diagonal is [0,1;0,0];
minus2ID = mypy.get_valID_from_valString("-2")
oneID = mypy.get_identity_pID(0);
zeroID = mypy.get_zero_pID(0,0)
rodID = m... | Python | nomic_cornstack_python_v1 |
function make_sequence_method methodname
begin
function seqmethod self *args **kwargs
begin
comment Proxy these methods to self._inst.entries.
return call get attribute entries methodname *args keyword kwargs
end function
set __name__ = methodname
return seqmethod
end function | def make_sequence_method(methodname):
def seqmethod(self, *args, **kwargs):
# Proxy these methods to self._inst.entries.
return getattr(self._inst.entries, methodname)(*args, **kwargs)
seqmethod.__name__ = methodname
return seqmethod | Python | nomic_cornstack_python_v1 |
function __init__ self scale=1.0 data_format=string channels_last **kwargs
begin
set scale = scale
set data_format = data_format
call __init__ keyword kwargs
end function | def __init__(self, scale=1.0, data_format='channels_last', **kwargs):
self.scale = scale
self.data_format = data_format
super(HeNormalEBRegularizer, self).__init__(**kwargs) | Python | nomic_cornstack_python_v1 |
import googlemaps
from datetime import datetime
import json
comment Will get API key when needed.
set gmaps = call Client key=string
comment Geocoding an address
set geocode_result = call geocode string 476 5th Ave, New York, NY 10018
set location = geocode_result at 0 at string geometry at string location
set place_de... | import googlemaps
from datetime import datetime
import json
#Will get API key when needed.
gmaps = googlemaps.Client(key='')
# Geocoding an address
geocode_result = gmaps.geocode('476 5th Ave, New York, NY 10018')
location = geocode_result[0]['geometry']['location']
place_details = gmaps.places(query = '', location = ... | Python | zaydzuhri_stack_edu_python |
function searchGlossary self keyword
begin
set words = list
end function | def searchGlossary(self,keyword):
words = []
| Python | nomic_cornstack_python_v1 |
function dtype_to_pgtype dtype colname
begin
if colname in tuple string the_geom string the_geom_webmercator
begin
return string geometry
end
else
begin
if dtype == string float64
begin
return string numeric
end
else
if dtype == string int64
begin
return string int
end
else
if dtype == string datetime64[ns]
begin
retur... | def dtype_to_pgtype(dtype, colname):
if colname in ('the_geom', 'the_geom_webmercator'):
return 'geometry'
else:
if dtype == 'float64':
return 'numeric'
elif dtype == 'int64':
return 'int'
elif dtype == 'datetime64[ns]':
return 'date'
e... | Python | nomic_cornstack_python_v1 |
function add_input_data_to_scoped_data self dictionary
begin
string Add a dictionary to the scoped data As the input_data dictionary maps names to values, the functions looks for the proper data_ports keys in the input_data_ports dictionary :param dictionary: The dictionary that is added to the scoped data :param state... | def add_input_data_to_scoped_data(self, dictionary):
"""Add a dictionary to the scoped data
As the input_data dictionary maps names to values, the functions looks for the proper data_ports keys in the
input_data_ports dictionary
:param dictionary: The dictionary that is added to the sc... | Python | jtatman_500k |
function checkAnagram
begin
set word1 = get args string word1
set word2 = get args string word2
if word1 and word2
begin
set tuple word1 word2 = call preprocessInputs word1 word2
set isAnagram = call isAnagramCheck word1 word2
if isAnagram
begin
print string Popular Anagrams Dict: popularAnagramDict
call buildAllAnagra... | def checkAnagram():
word1 = request.args.get('word1')
word2 = request.args.get('word2')
if word1 and word2:
word1, word2 = preprocessInputs(word1, word2)
isAnagram = isAnagramCheck(word1, word2)
if isAnagram:
print("Popular Anagrams Dict:", popularAnagramDict)
... | Python | nomic_cornstack_python_v1 |
async function test_on_fast_cleanup self
begin
set kwargs = call cmd_kwargs 18 0 none target hops_left=3
set topics = list call create_topic ON_FAST ALL_LINK_CLEANUP 6 kwargs 0.1
await call run_test topics 255 1
end function | async def test_on_fast_cleanup(self):
kwargs = cmd_kwargs(0x12, 0x00, None, self.target, hops_left=3)
topics = [
self.create_topic(ON_FAST, MessageFlagType.ALL_LINK_CLEANUP, 6, kwargs, 0.1)
]
await self.run_test(topics, 255, 1) | Python | nomic_cornstack_python_v1 |
import pyaudio
import wave
import numpy as np
import matplotlib.pyplot as plt
import struct
import math
import numpy as np
from scipy.stats import entropy
from math import log , e
import pandas as pd
comment Je Sen Teh , WeiJian Teng , Azman Samsudin “A True Random Number Generator
comment Based on Hyperchaos and Digit... | import pyaudio
import wave
import numpy as np
import matplotlib.pyplot as plt
import struct
import math
import numpy as np
from scipy.stats import entropy
from math import log, e
import pandas as pd
# Je Sen Teh , WeiJian Teng , Azman Samsudin “A True Random Number Generator
# Based on Hyperchaos and Digital Sound”
c... | Python | zaydzuhri_stack_edu_python |
function uniform_ self low=0 high=1
begin
return call uniform_fill self low high
end function | def uniform_(self, low=0, high=1):
return init_funcs.uniform_fill(self, low, high) | Python | nomic_cornstack_python_v1 |
function start_end_datetime data
begin
set index = call _get_index data
return list index at 0 index at - 1
end function | def start_end_datetime(data):
index = _get_index(data)
return [index[0], index[-1]] | Python | nomic_cornstack_python_v1 |
async function about self ctx
begin
set author_repo = string https://github.com/scragly
set bot_repo = author_repo + string /Firetail
set server_url = string https://discord.gg/ZWmzTP3
set owner = string Discord: Scragly#5146 EVE: Kyo Kuronami
set member_count = sum generator expression member_count for g in guilds
set... | async def about(self, ctx):
author_repo = "https://github.com/scragly"
bot_repo = author_repo + "/Firetail"
server_url = "https://discord.gg/ZWmzTP3"
owner = "Discord: Scragly#5146\nEVE: Kyo Kuronami"
member_count = sum(g.member_count for g in self.bot.guilds)
server_cou... | Python | nomic_cornstack_python_v1 |
import json
import numpy as np
import pandas as pd
from scipy.stats import norm
import statsmodels.api as sm
import matplotlib.pyplot as plt
function tweets_to_bins tweetDataPath bin_len start_index=0
begin
comment read file
set f = open tweetDataPath string r
set data = read f
set data = loads data
set tweetTimes = li... | import json
import numpy as np
import pandas as pd
from scipy.stats import norm
import statsmodels.api as sm
import matplotlib.pyplot as plt
def tweets_to_bins(tweetDataPath, bin_len, start_index=0):
# read file
f = open(tweetDataPath, 'r')
data = f.read()
data = json.loads(data)
tweetTimes = []
... | Python | zaydzuhri_stack_edu_python |
function resolve_reference schema_url
begin
try
begin
with open schema_url as f
begin
return load json f
end
end
except Exception as e
begin
return e
end
end function | def resolve_reference(schema_url):
try:
with open(schema_url) as f:
return json.load(f)
except Exception as e:
return e | Python | nomic_cornstack_python_v1 |
function _get self params
begin
comment upon success we can return an image
set video = get objects pk=params at string id
set project = project
set frame_ranges_str = get params string frameRanges none
set frame_ranges_tuple = list comprehension split frame_range string : for frame_range in frame_ranges_str
set frame_... | def _get(self, params):
# upon success we can return an image
video = Media.objects.get(pk=params['id'])
project = video.project
frame_ranges_str = params.get('frameRanges', None)
frame_ranges_tuple=[frame_range.split(':') for frame_range in frame_ranges_str]
frame_ranges... | Python | nomic_cornstack_python_v1 |
function button_state self
begin
if type != TABLET_PAD_BUTTON
begin
raise call AttributeError format _wrong_prop type
end
return call libinput_event_tablet_pad_get_button_state _handle
end function | def button_state(self):
if self.type != EventType.TABLET_PAD_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_pad_get_button_state(
self._handle) | Python | nomic_cornstack_python_v1 |
import numpy as np
import math
import scipy
import pandas as pd
import matplotlib.pyplot as plt
from ParticleClass import Nuclei , RadioNuclei
set c = speed_of_light
function randomNumber min max
begin
string This function gets a random number from a uniform distribution between the inputted minimum and maximum inclusi... | import numpy as np
import math
import scipy
import pandas as pd
import matplotlib.pyplot as plt
from ParticleClass import Nuclei, RadioNuclei
c = scipy.constants.speed_of_light
def randomNumber(min, max):
"""
This function gets a random number from a uniform distribution between
the inputted minimum an... | Python | zaydzuhri_stack_edu_python |
function print_mult_table n
begin
for i in range 1 11
begin
print format string {} x {} = {} n i n * i
end
end function | def print_mult_table(n):
for i in range(1, 11):
print('{} x {} = {}'.format(n, i, n*i))
| Python | flytech_python_25k |
comment !/usr/bin/env python
from __future__ import print_function
from collections import defaultdict
from datetime import datetime , date , time , timedelta
import json
import re
from subprocess import Popen , PIPE
from textwrap import TextWrapper
comment taken from fabric's colors
function _wrap_with code
begin
func... | #!/usr/bin/env python
from __future__ import print_function
from collections import defaultdict
from datetime import datetime, date, time, timedelta
import json
import re
from subprocess import Popen, PIPE
from textwrap import TextWrapper
# taken from fabric's colors
def _wrap_with(code):
def inner(text, bold=Fa... | Python | zaydzuhri_stack_edu_python |
function common_manifest self
begin
return call safe_dict_get_value _json string common_manifest
end function | def common_manifest(self):
return safe_dict_get_value(self._json, "common_manifest") | Python | nomic_cornstack_python_v1 |
function test_create_secret_in_share_that_does_not_exist self
begin
set write = false
save
set url = reverse string secret
set data = dict string link_id string 0f3ff8d2-213a-47f3-bd58-fc88cb0220f9 ; string parent_share_id string 9a4648b6-7832-403b-bcdf-42f825db0311 ; string data string 12345 ; string data_nonce join s... | def test_create_secret_in_share_that_does_not_exist(self):
self.test_user_share_right1_obj.write = False
self.test_user_share_right1_obj.save()
url = reverse('secret')
data = {
'link_id': '0f3ff8d2-213a-47f3-bd58-fc88cb0220f9',
'parent_share_id': "9a4648b6-7832... | Python | nomic_cornstack_python_v1 |
function _child_from_reference self reference
begin
string Returns the child sensor from its reference. Parameters ---------- reference : str Reference to sensor (typically its name). Returns ------- child : :class:`katcp.Sensor` object A child sensor linked to one or more aggregate sensors.
for child in _child_to_pare... | def _child_from_reference(self, reference):
"""Returns the child sensor from its reference.
Parameters
----------
reference : str
Reference to sensor (typically its name).
Returns
-------
child : :class:`katcp.Sensor` object
A child senso... | Python | jtatman_500k |
function find_nearest array value
begin
set idx = argument minimum
return idx
end function | def find_nearest(array, value):
idx = (np.abs(array-value)).argmin()
return idx | Python | nomic_cornstack_python_v1 |
string Based on recho client from class
import select
import socket
import sys
import datetime
set host = string localhost
comment new default port
set port = 50004
set size = 1024
set username = string generic
set nargs = length argv
if nargs > 1
begin
set host = argv at 1
end
if nargs > 2
begin
set port = integer arg... | """
Based on recho client from class
"""
import select
import socket
import sys
import datetime
host = 'localhost'
port = 50004 #new default port
size = 1024
username = 'generic'
nargs = len(sys.argv)
if nargs >1:
host = sys.argv[1]
if nargs >2:
port = int(sys.argv[2])
username=raw_input("Enter Username: ")... | Python | zaydzuhri_stack_edu_python |
comment norvig_solver_test.py
comment author: Josue Mendoza
comment date: 4-12-2015
import unittest
import os
from norvig_solver import NorvigSolver
class NorvigSolverTest extends TestCase
begin
set GAME_1_BOARD_STRING = string 003020600900305001001806400008102900700000008006708200002609500800203009005010300
set GAME_1... | # norvig_solver_test.py
# author: Josue Mendoza
# date: 4-12-2015
import unittest
import os
from norvig_solver import NorvigSolver
class NorvigSolverTest(unittest.TestCase):
GAME_1_BOARD_STRING = '00302060090030500100180640000810290070000000800670820000' \
'2609500800203009005010300'
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import webbrowser
import re
import time
set inputHtml = open string input.html string r
set link = list
for line in inputHtml
begin
if match string (.*)mp4(.*) line
begin
set r = compile string href="(.*?)"
set m = search line
if m
begin
append link call group 1
end
end
end
for items in li... | #!/usr/bin/env python
import webbrowser
import re
import time
inputHtml = open("input.html", "r")
link = []
for line in inputHtml:
if re.match("(.*)mp4(.*)", line):
r = re.compile('href="(.*?)"')
m = r.search(line)
if m:
link.append(m.group(1))
for items in link:
webbrowse... | Python | zaydzuhri_stack_edu_python |
function stop_trigger self Name
begin
pass
end function | def stop_trigger(self, Name: str) -> Dict:
pass | Python | nomic_cornstack_python_v1 |
comment This code uses Python data analysis and visualization libraries to carry out exploratory analysis on the Iris Data Set
comment The code outputs summaries of the four numerical variables to a text file with formatting
comment It generates graphs on the distribution of data and correlation between variables
comme... | # This code uses Python data analysis and visualization libraries to carry out exploratory analysis on the Iris Data Set
# The code outputs summaries of the four numerical variables to a text file with formatting
# It generates graphs on the distribution of data and correlation between variables
# It uses the independe... | Python | zaydzuhri_stack_edu_python |
function _accept_clients self
begin
while true
begin
try
begin
set tuple clienthandler addr = call accept
comment from the addr variable, extract the client id assigned to the client
set client_id = dict string clientid addr at 1
comment send assigned id to the new client. hint: call the send_clientid(..) method
call _... | def _accept_clients(self):
while True:
try:
clienthandler, addr = self.serversocket.accept()
# from the addr variable, extract the client id assigned to the client
client_id = {'clientid': addr[1]}
# send assigned id to the new client. ... | Python | nomic_cornstack_python_v1 |
comment /usr/bin/python
comment -*- coding:utf-8 -*-
string 作者:xguo 文件:fracial_tree.py 功能:利用递归绘制分形树 版本:1.0 日期:2019/2/20 12:28
import turtle
function draw_branch branch_length
begin
if branch_length > 5
begin
comment 绘制右侧树枝
call forward branch_length
print string 向前 branch_length
call right 20
print string 右转 20
call dr... | #/usr/bin/python
#-*- coding:utf-8 -*-
'''
作者:xguo
文件:fracial_tree.py
功能:利用递归绘制分形树
版本:1.0
日期:2019/2/20 12:28
'''
import turtle
def draw_branch(branch_length):
if branch_length > 5 :
#绘制右侧树枝
turtle.forward(branch_length)
print("向前", branch_length)
turtle.right(2... | Python | zaydzuhri_stack_edu_python |
function reduce_for_enumerate method a seed
begin
for tuple _ item in enumerate a
begin
set seed = call method seed item
end
return seed
end function | def reduce_for_enumerate(method, a, seed) -> int:
for _, item in enumerate(a):
seed = method(seed, item)
return seed | Python | nomic_cornstack_python_v1 |
import os
import random
import torch.distributed as td
from torch.multiprocessing import Process
function train Model model_args
begin
comment Run one worker node for each gpu
set gpus = model_args at string gpus
set model_args at string distributed at string world_size = model_args at string distributed at string worl... | import os
import random
import torch.distributed as td
from torch.multiprocessing import Process
def train(Model, model_args):
# Run one worker node for each gpu
gpus = model_args['gpus']
model_args["distributed"]["world_size"] *= len(gpus)
processes = []
for gpu in gpus:
p = Process(targ... | Python | zaydzuhri_stack_edu_python |
function multi_lc_phase_colors stardatas bands periods offsets=none cmap=string jet colorscale=string date figscale=1
begin
set ydim = length stardatas
if offsets is none
begin
set offsets = list 0 * ydim
end
if not length stardatas == length bands == length periods == length offsets
begin
raise call ValueError string ... | def multi_lc_phase_colors(stardatas, bands, periods, offsets=None, cmap='jet', colorscale='date', figscale=1):
ydim = len(stardatas)
if offsets is None:
offsets = [0]*ydim
if not (len(stardatas) == len(bands) == len(periods) == len(offsets)):
raise ValueError("Length of input lists should... | Python | nomic_cornstack_python_v1 |
function test_iter self
begin
set clr = call Colr string This is a test. string red string blue string bright
assert equal join string generator expression c for c in clr data msg=string Colr was not iterable in generator expression.
set chars = list
for c in clr
begin
append chars c
end
assert equal join string cha... | def test_iter(self):
clr = Colr('This is a test.', 'red', 'blue', 'bright')
self.assertEqual(
''.join(c for c in clr),
clr.data,
msg='Colr was not iterable in generator expression.'
)
chars = []
for c in clr:
chars.append(c)
... | Python | nomic_cornstack_python_v1 |
from pyswip import Prolog
import random
import os
set cwd = get current directory
set filename = cwd + string /log
set file = open filename string w
comment Descricao: busca aleatoriamente uma posicao vaga no mundo
comment Uma posicao vaga nao esta ocupada por nada
comment Param: world - Matriz contendo as informacoes ... | from pyswip import Prolog
import random
import os
cwd = os.getcwd()
filename = cwd + "/log"
file = open(filename, 'w')
# Descricao: busca aleatoriamente uma posicao vaga no mundo
# Uma posicao vaga nao esta ocupada por nada
# Param: world - Matriz contendo as informacoes PC = poco, M1,M2,M3,M4=monstros e GD = ouro
#... | Python | zaydzuhri_stack_edu_python |
function generate self num_words=Ellipsis text_seed=Ellipsis random_seed=Ellipsis
begin
Ellipsis
end function | def generate(self, num_words=..., text_seed: Optional[Any] = ..., random_seed: Optional[Any] = ...):
... | Python | nomic_cornstack_python_v1 |
comment EXERCICIO6
set dist = decimal input string Entre com a distância(KM):
set vlMedia = integer input string Entre com a velocidade média(KM/H):
comment v=d/t => t=d/v
set tempoViagem = dist / vlMedia
print string Tempo de viagem é de: + string tempoViagem + string H | #EXERCICIO6
dist = float(input("Entre com a distância(KM): "))
vlMedia = int(input("Entre com a velocidade média(KM/H): "))
#v=d/t => t=d/v
tempoViagem = dist/vlMedia
print("Tempo de viagem é de: " + str(tempoViagem) + "H") | Python | zaydzuhri_stack_edu_python |
function printer lista
begin
for i in range length lista
begin
print lista at i
end
end function
call printer crescente
print string
call printer numeros | def printer(lista):
for i in range(len(lista)):
print(lista[i])
printer(crescente)
print('')
printer(numeros) | Python | zaydzuhri_stack_edu_python |
function get_reverse_complement dna
begin
comment added a unit test to protect against invalid dna strings.
comment Here index is set to negative 1 so that it pulls the last letter in the string first
set index = - 1
comment Initializing an empty list - later the complementary dna strand will be written to this
set rev... | def get_reverse_complement(dna):
#added a unit test to protect against invalid dna strings.
index=-1# Here index is set to negative 1 so that it pulls the last letter in the string first
reverse_complement=[]# Initializing an empty list - later the complementary dna strand will be written to this
whi... | Python | nomic_cornstack_python_v1 |
comment v.in.ogr input=C:\Users\Frank\Desktop\grid\Intersection_id_73.shp output=Intersection_id_73
comment v.dissolve input=Intersection_id_73 output=dissolved_Intersection_id_73 column=dislv
comment v.patch --o input=dissolved_Intersection_id_73,dissolved_Intersection_id_74 output=patched
comment coding: utf-8
import... | # v.in.ogr input=C:\Users\Frank\Desktop\grid\Intersection_id_73.shp output=Intersection_id_73
# v.dissolve input=Intersection_id_73 output=dissolved_Intersection_id_73 column=dislv
# v.patch --o input=dissolved_Intersection_id_73,dissolved_Intersection_id_74 output=patched
# coding: utf-8
import fnmatch
import grass.... | Python | zaydzuhri_stack_edu_python |
comment print(test.sort())
comment dictionaries
print string dict
set testd = dict
set testd at string key = string value
set testd at 5 = 10
print testd
print keys testd
print values testd | #print(test.sort())
#dictionaries
print('dict')
testd = {}
testd['key'] = 'value'
testd[5] = 10
print(testd)
print(testd.keys())
print(testd.values())
| Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import validation_curve , train_test_split
from sklearn.preprocessing import LabelEncoder , StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
set df = read csv ... | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import validation_curve, train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
df = pd.read_csv(".... | Python | zaydzuhri_stack_edu_python |
function process_request self request
begin
if method == string GET
begin
return
end
for pattern in jsonrpc_urlpatterns
begin
set match = search path at slice 1 : :
if match
begin
comment If there are any named groups, use those as kwargs, ignoring
comment non-named groups. Otherwise, pass all non-named arguments as
c... | def process_request(self, request):
if(request.method == "GET"):
return
for pattern in self.jsonrpc_urlpatterns:
match = pattern.regex.search(request.path[1:])
if match:
# If there are any named groups, use those as kwargs, ignoring
# n... | Python | nomic_cornstack_python_v1 |
function begin figsize=tuple 10 5 grid=tuple 1 1
begin
global current_figure current_grid
if current_figure is not none
begin
warn string There is already an open figure. Did you use end()?
end
set current_figure = figure figsize=figsize
set current_grid = grid
end function | def begin(figsize=(10, 5), grid=(1, 1)):
global current_figure, current_grid
if current_figure is not None:
warn("There is already an open figure. Did you use end()?")
current_figure = plt.figure(figsize=figsize)
current_grid = grid | Python | nomic_cornstack_python_v1 |
function body self parent
begin
set img = call Label parent image=_photo text=string Unable to display image
call pack
end function | def body(self, parent):
img = Label(parent, image = self._photo, text="Unable to display image")
img.pack() | Python | nomic_cornstack_python_v1 |
comment This is a simple version of the game, using list and if statements. Have fun!
set rock = string _______ ---' ____) (_____) (_____) (____) ---.__(___)
set paper = string _______ ---' ____)____ ______) _______) _______) ---.__________)
set scissors = string _______ ---' ____)____ ______) __________) (____) ---.__... | # This is a simple version of the game, using list and if statements. Have fun!
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
______... | Python | zaydzuhri_stack_edu_python |
function __new_text_df self
begin
set __new_df = call DataFrame dict uniq_header list string New/ID_TBD ; string Steps list new_text
set data_frame = append __new_df data_frame ignore_index=true
end function | def __new_text_df(self):
__new_df = pd.DataFrame({self.uniq_header: ["New/ID_TBD"], 'Steps': [self.new_text]})
self.data_frame = __new_df.append(self.data_frame, ignore_index=True) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment This tells python that parts of the script are utf-8
string rename-tiers.py This is just a series of regex replacements, renaming all tiers in an ELAN file using a single command. It is designed to replace the default post-Flex tier names, which are awkward. ... Seems to need somet... | # -*- coding: utf-8 -*-
# This tells python that parts of the script are utf-8
"""
rename-tiers.py
This is just a series of regex replacements, renaming all tiers in an ELAN file using a single command. It is designed to replace the default post-Flex tier names, which are awkward.
... Seems to need something more to r... | Python | zaydzuhri_stack_edu_python |
from scipy.stats import spearmanr
comment Let me run it for you!
set list1 = list 1 2 3 4 5
set list2 = list 5 6 7 8 7
set tuple correlation _ = spearman correlation list1 list2
print string Spearman correlation: correlation | from scipy.stats import spearmanr
# Let me run it for you!
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 7]
correlation, _ = spearmanr(list1, list2)
print('Spearman correlation:', correlation)
| Python | flytech_python_25k |
function _add_doc filename doc
begin
comment try:
set id_ = inserted_id
comment except TypeError:
comment id_ = db[filename].insert(doc)
return id_
end function | def _add_doc(filename, doc):
# try:
id_ = db[filename].insert_one(doc).inserted_id
# except TypeError:
# id_ = db[filename].insert(doc)
return id_ | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Spyder Editor Este é um arquivo de script temporário.
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
comment Importando os dados dos pokemons
set dataset = read csv string pokemon.csv.csv encoding=string ISO-8859-1
comment Poder de ataque da inves... | # -*- coding: utf-8 -*-
"""
Spyder Editor
Este é um arquivo de script temporário.
"""
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
#Importando os dados dos pokemons
dataset = pd.read_csv('pokemon.csv.csv', encoding = 'ISO-8859-1')
investida=40; #Poder de ataq... | Python | zaydzuhri_stack_edu_python |
function plot_coordinates radius_function segments=100 alpha=0.4 offset=tuple 0.0 0.0
begin
set tuple xs ys = call get_coordinates radius_function segments=segments offset=offset
call fill xs ys alpha=alpha
plot xs + list xs at 0 ys + list ys at 0
call set_aspect string equal
end function | def plot_coordinates(radius_function, segments=100, alpha=0.4, offset=(0.0, 0.0)):
xs, ys = get_coordinates(radius_function, segments=segments, offset=offset)
plt.fill(xs, ys, alpha=alpha)
plt.plot(xs + [xs[0]], ys + [ys[0]])
plt.gca().set_aspect("equal") | Python | nomic_cornstack_python_v1 |
function restore_irmc_bios_config self task
begin
try
begin
call _restore_bios_config task
end
except IRMCOperationError as e
begin
raise call NodeCleaningFailure node=uuid reason=e
end
end function | def restore_irmc_bios_config(self, task):
try:
_restore_bios_config(task)
except exception.IRMCOperationError as e:
raise exception.NodeCleaningFailure(node=task.node.uuid,
reason=e) | Python | nomic_cornstack_python_v1 |
function _ISBL_DPI self DPI
begin
if lang_factor
begin
set _ISBL_DPI_cached = DPI - sum list comprehension purchase_cost for i in OSBL_units * lang_factor
end
else
begin
set _ISBL_DPI_cached = DPI - sum list comprehension installation_cost for i in OSBL_units
end
return _ISBL_DPI_cached
end function | def _ISBL_DPI(self, DPI):
if self.lang_factor:
self._ISBL_DPI_cached = DPI - sum([i.purchase_cost for i in self.OSBL_units]) * self.lang_factor
else:
self._ISBL_DPI_cached = DPI - sum([i.installation_cost for i in self.OSBL_units])
return self._ISBL_DPI_cached | Python | nomic_cornstack_python_v1 |
function dump_hpo_to_tsv self outFile auth
begin
set session = call get_phenotips_session auth=auth
set patients = call get_patient session=session at string patientSummaries
comment file(sprintf('uclex_hpo_%d-%d-%d.txt'),)
set hpo_file = open outFile string w+
print string eid string hpo string genes string solved sep... | def dump_hpo_to_tsv(self, outFile, auth):
session = self.get_phenotips_session(auth=auth)
patients=self.get_patient(session=session)['patientSummaries']
#file(sprintf('uclex_hpo_%d-%d-%d.txt'),)
hpo_file=open(outFile, 'w+')
print('eid', 'hpo', 'genes', 'solved', sep='\t',file=hpo... | Python | nomic_cornstack_python_v1 |
string LİSTE METOTLARI liste.append(a) a elemanını listenin sonuna ekler liste.clear() Bütün elemanları siler boş listede döndürür. liste.copy() Listenin kopyasını oluşturur. liste.count(a) kaç tane a elemanından olduğunu bulur. liste.insert(i,a) liste.pop() liste.pop(i) liste.remove(a) liste.reverse() liste.sort() | """
LİSTE METOTLARI
liste.append(a) a elemanını listenin sonuna ekler
liste.clear() Bütün elemanları siler boş listede döndürür.
liste.copy() Listenin kopyasını oluşturur.
liste.count(a) kaç tane a elemanından olduğunu bulur.
liste.insert(i,a)
liste.pop()
liste.pop(i)
liste.remove(a)
liste.rever... | Python | zaydzuhri_stack_edu_python |
function add_field self name value
begin
append form_fields tuple name string value
return
end function | def add_field(self, name, value):
self.form_fields.append((name, str(value)))
return | Python | nomic_cornstack_python_v1 |
import os
import psutil
function current_ram
begin
set process = process call getpid
set ram = rss / 1000000
return string integer ram + string MB
end function | import os
import psutil
def current_ram():
process = psutil.Process(os.getpid())
ram = process.memory_info().rss / 1000000
return str(int(ram)) + " MB"
| Python | zaydzuhri_stack_edu_python |
import numpy as np
class MLP
begin
function __init__ self
begin
set W1 = array list list 1 - 2 list 3 4
set W2 = array list list 2 2 list 3 - 3
set b1 = T
set b2 = T
end function
function relu self arr
begin
return call clip arr a_min=0 a_max=none
end function
function forward self x
begin
set a1 = relu matrix multiply... | import numpy as np
class MLP():
def __init__(self):
self.W1=np.array([
[1,-2],
[3,4]
])
self.W2=np.array([
[2,2],
[3,-3]
])
self.b1=np.array([1,0]).T
self.b2=np.array([0,-4]).T
def relu(self, arr):
return n... | Python | zaydzuhri_stack_edu_python |
function remove_comic
begin
set box = call get_or_404 box post_vars at string box owner=id
set comic = call get_or_404 comic post_vars at string comic
if is_unfiled
begin
call flash_and_redirect_back string danger string A comic cannot be removed from the Unfiled box.
end
delete
comment if the comic no longer belongs t... | def remove_comic():
box = get_or_404(db.box, request.post_vars['box'], owner=auth.user.id)
comic = get_or_404(db.comic, request.post_vars['comic'])
if box.is_unfiled:
flash_and_redirect_back('danger', 'A comic cannot be removed from the Unfiled box.')
db(db.comicbox.box == box.id)(db.comicbox... | Python | nomic_cornstack_python_v1 |
function get_covar_inter_weights self
begin
set decoder_weight = network_weights at string beta_ci
set emb = run decoder_weight
return emb
end function | def get_covar_inter_weights(self):
decoder_weight = self.network_weights['beta_ci']
emb = self.sess.run(decoder_weight)
return emb | Python | nomic_cornstack_python_v1 |
function asXML self doctag=none namedItemsOnly=false indent=string formatted=true
begin
set nl = string
set out = list
set namedItems = dictionary list comprehension tuple v at 1 k for tuple k vlist in items __tokdict for v in vlist
set nextLevelIndent = indent + string
comment collapse out indents if formatting is... | def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
nl = "\n"
out = []
namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist ] )
nextLevelIndent = indent + " "
... | Python | nomic_cornstack_python_v1 |
import pickle
import ternary
import matplotlib.pyplot as plt
import numpy as np
from src.constants import MATPLOTLIB_COLORS
from src.constants import BST_SOLUTIONS
from collections import Counter
import matplotlib
update rcParams dict string font.size 22
function euclidean_distance p1 p2
begin
return norm p1 - p2
end f... | import pickle
import ternary
import matplotlib.pyplot as plt
import numpy as np
from src.constants import MATPLOTLIB_COLORS
from src.constants import BST_SOLUTIONS
from collections import Counter
import matplotlib
matplotlib.rcParams.update({'font.size': 22})
def euclidean_distance(p1, p2):
return np.linalg.norm... | Python | zaydzuhri_stack_edu_python |
function has_column_proportion self index
begin
return index in _proportions at 0
end function | def has_column_proportion(self, index):
return index in self._proportions[0] | Python | nomic_cornstack_python_v1 |
function collection_post self
begin
call set_transaction_name string collection_post
set transition = validated at string transition
set message = get validated string message string
set fields = get validated string fields dict
set workflow = workflow
set valid_transitions_list = string list transitions
if transition ... | def collection_post(self) -> dict:
self.set_transaction_name('collection_post')
transition = self.request.validated['transition']
message = self.request.validated.get('message', '')
fields = self.request.validated.get('fields', {})
workflow = self.workflow
valid_transitio... | Python | nomic_cornstack_python_v1 |
function index_view request
begin
comment Create blank form instances.
set form = call TickerForm
set crypto_form = call CryptoTickerForm
comment Check if the request method == POST
if method == string POST
begin
set post_data = POST or none
comment Check that ther is data on the request.
if post_data != none
begin
com... | def index_view(request):
# Create blank form instances.
form = TickerForm()
crypto_form = CryptoTickerForm()
# Check if the request method == POST
if request.method == 'POST':
post_data = request.POST or None
# Check that ther is data on the request.
if post_data != None:
# Check if the user enters dat... | Python | nomic_cornstack_python_v1 |
function add_item self item_label
begin
comment On crée un object itempopup
set item = call PopupItem item_label
comment On connecte le signal émit par l'item lorsque l'on click dessus
call connect item_clicked
comment On ajoute l'item au layout vertical
call addWidget item
comment On supprime les marges interieur et e... | def add_item(self, item_label):
# On crée un object itempopup
item = PopupItem(item_label)
# On connecte le signal émit par l'item lorsque l'on click dessus
item.ITEM_CLICKED.connect(self.item_clicked)
# On ajoute l'item au layout vertical
self.vbox.addWidget(item)
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Nov 8 18:30:10 2017 @author: Administrator
import math
string 图像平滑模板
set box3 = list list 1 / 9 1 / 9 1 / 9 list 1 / 9 1 / 9 1 / 9 list 1 / 9 1 / 9 1 / 9
set box5 = list list 1 / 25 1 / 25 1 / 25 1 / 25 1 / 25 list 1 / 25 1 / 25 1 / 25 1 / 25 1 / 25 list 1 / 25 1 / 25... | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 18:30:10 2017
@author: Administrator
"""
import math
'''
图像平滑模板
'''
box3 = [
[1/9,1/9,1/9],
[1/9,1/9,1/9],
[1/9,1/9,1/9]
]
box5 = [
[1/25,1/25,1/25,1/25,1/25],
[1/25,1/25,1/25,1/25,1/25],
[1/25,1... | Python | zaydzuhri_stack_edu_python |
import dfa
import nfa
set dfa = call DFADesign string x1 set literal string x3 call DFARulebook list call FARule string x1 string a string x2 call FARule string x2 string a string x2 call FARule string x2 string b string x2 call FARule string x2 string c string x3
set start_state = string dummy
set accept_states = _acc... | import dfa
import nfa
dfa = dfa.DFADesign(
'x1', {'x3'},
dfa.DFARulebook([
dfa.FARule('x1', 'a', 'x2'),
dfa.FARule('x2', 'a', 'x2'),
dfa.FARule('x2', 'b', 'x2'),
dfa.FARule('x2', 'c', 'x3'),
]))
start_state = 'dummy'
accept_states = dfa._accept_states | {start_state}
start... | Python | zaydzuhri_stack_edu_python |
function classify_image self scores
begin
comment TODO: rename classify_scores(), does not use image at all!
set vector = call create_vector_from_scores scores
return call svm_proba vector svm at 0 at 1
end function | def classify_image(self, scores):
# TODO: rename classify_scores(), does not use image at all!
vector = self.create_vector_from_scores(scores)
return svm_proba(vector, self.svm)[0][1] | Python | nomic_cornstack_python_v1 |
function insert self id priority
begin
set n = n + 1
set i = n
while i > 1
begin
set pIdx = integer i / 2
set p = elements at pIdx
if priority > p at PRIORITY
begin
break
end
set elements at i = list p
set positions at p at ID = 1
set i = pIdx
end
set elements at i at ID = id
set elements at i at PRIORITY = priority
se... | def insert(self, id, priority):
self.n += 1
i = self.n
while i > 1:
pIdx = int(i/2)
p = self.elements[pIdx]
if priority > p[PRIORITY]:
break
self.elements[i] = list(p)
self.positions[p[ID]] = 1
i = pIdx
... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import datetime
import warnings
filter warnings string ignore
from pandas.core.frame import DataFrame
from math import radians , cos , sin , asin , sqrt
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsC... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import datetime
import warnings
warnings.filterwarnings('ignore')
from pandas.core.frame import DataFrame
from math import radians, cos, sin, asin, sqrt
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighbors... | Python | zaydzuhri_stack_edu_python |
function transform self input format
begin
set out = list split splitter input groups=groups
if validation_size > 0
begin
for tuple i list _ tmp_test in enumerate out
begin
comment Need to convert to list...
set out at i = list out at i
set tuple tmp_test tmp_validation = list split validation_splitter tmp_test at 0
se... | def transform(self, input, format):
out = list(self.splitter.split(input, groups=self.groups))
if self.validation_size > 0:
for i, [_, tmp_test] in enumerate(out):
out[i] = list(out[i]) # Need to convert to list...
tmp_test, tmp_validation = list(self.validat... | Python | nomic_cornstack_python_v1 |
function get_transformed_pose self reference_pose target_frame
begin
for i in range 0 transform_tries
begin
set transformed_pose = call transform_pose reference_pose target_frame
if transformed_pose
begin
return transformed_pose
end
end
set transformed_pose = none
return transformed_pose
end function | def get_transformed_pose(self, reference_pose, target_frame):
for i in range(0, self.transform_tries):
self.transformed_pose = self.transform_pose(reference_pose, target_frame)
if self.transformed_pose:
return self.transformed_pose
self.transformed_pose = None
... | Python | nomic_cornstack_python_v1 |
string Spatially and temporally constrained Split Bregman algorithm. Notes ----- Adapted from [1]_. References ---------- .. [1] https://github.com/HGGM-LIM/ Split-Bregman-ST-Total-Variation-MRI
import numpy as np
from tqdm import trange , tqdm
from skimage.measure import compare_mse
function SpatioTemporalTVSB mask y ... | '''Spatially and temporally constrained Split Bregman algorithm.
Notes
-----
Adapted from [1]_.
References
----------
.. [1] https://github.com/HGGM-LIM/
Split-Bregman-ST-Total-Variation-MRI
'''
import numpy as np
from tqdm import trange, tqdm
from skimage.measure import compare_mse
def SpatioTemporalTVSB(
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set arr = array range 0 12
print arr
print arr at slice 0 : 6 :
set arr at slice 2 : 5 : = 20
print arr
set arr2 = arr at slice 3 : 6 :
set arr2 at slice : : = 29
print arr2
print arr
comment creating new array copy
set arrcopy = copy arr | import numpy as np
arr = np.arange(0,12)
print (arr)
print (arr[0:6])
arr[2:5] = 20
print (arr)
arr2 = arr[3:6]
arr2[:] = 29
print (arr2)
print (arr)
# creating new array copy
arrcopy = arr.copy()
| Python | zaydzuhri_stack_edu_python |
function dayOfYear year month day
begin
set monthnum = 1
set daynum = 0
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0
begin
print string %s年是闰年 % year
set L1 = list 31 29 31 30 31 30 31 31 30 31 30 31
for i in L1
begin
if monthnum < month
begin
set daynum = daynum + i
set monthnum = monthnum + 1
end
end
set d... | def dayOfYear(year,month,day):
monthnum = 1
daynum = 0
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
print("%s年是闰年" % (year))
L1 = [31,29,31,30,31,30,31,31,30,31,30,31]
for i in L1:
if monthnum < month:
daynum += i
... | Python | zaydzuhri_stack_edu_python |
function _get_locked self mountpoint
begin
comment This dance is because we delete locks. We need to be sure that the
comment lock we hold does not belong to an object which has been deleted.
comment We do this by checking that mountpoint still refers to this object
comment when we hold the lock. This is safe because:
... | def _get_locked(self, mountpoint):
# This dance is because we delete locks. We need to be sure that the
# lock we hold does not belong to an object which has been deleted.
# We do this by checking that mountpoint still refers to this object
# when we hold the lock. This is safe because:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Date : 2017-07-22 21:22:39
comment @Author : wangguoan
comment @eMail : 18909311025@189.cn
comment @Link : http://example.org
comment @Version : 1.0
string 传入所有线程共享的mutex对象而非全局对象;和上下文管理器 语句一起使用,实现所得自动获取/释放;添加休眠功能的调用 以避免繁忙的循环并模拟真实工作
import _thread as th... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-07-22 21:22:39
# @Author : wangguoan
# @eMail : 18909311025@189.cn
# @Link : http://example.org
# @Version : 1.0
"""
传入所有线程共享的mutex对象而非全局对象;和上下文管理器
语句一起使用,实现所得自动获取/释放;添加休眠功能的调用
以避免繁忙的循环并模拟真实工作
"""
import _thread as thread,time
numthreads = 10
tim... | Python | zaydzuhri_stack_edu_python |
function vis_umap self legend=true marker_size=tuple 2.0 10.0
begin
assert not dimred_elem_matrix is none
assert not dimred_labels is none
set nplabels = array dimred_labels
figure
set clustered = nplabels >= 0
info format string Pixels : {} shape at 0
info format string Unassigned: {} shape at 0
scatter plt dimred_ele... | def vis_umap(self, legend=True, marker_size=(2.0, 10.0)):
assert(not self.dimred_elem_matrix is None)
assert(not self.dimred_labels is None)
nplabels = np.array(self.dimred_labels)
plt.figure()
clustered = (nplabels >= 0)
self.logger.info("Pixels : {}".format... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.