code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function gen_indiv_tracks save_path minfrm
begin
exec read open string /home/vivek/Python_Projects/Piezo1_MathToPython_Atom/open_tracks.py
set numTracks = length tracks
comment make list of tracks with >= min number frames
set lst = list
for i in range 0 numTracks
begin
set track = tracks at i
set pts = txy_pts at tup... | def gen_indiv_tracks(save_path, minfrm):
exec(open("/home/vivek/Python_Projects/Piezo1_MathToPython_Atom/open_tracks.py").read())
numTracks = len(tracks)
# make list of tracks with >= min number frames
lst = []
for i in range(0,(numTracks)):
track = tracks[i]
pts = txy_pts[trac... | Python | nomic_cornstack_python_v1 |
function add_polygon self nodes boundary_id=- 1
begin
call add_nodes nodes=nodes subsections=1 is_polygon=true boundary_id=boundary_id
end function
comment Need to be 1, otherwise it won't be a polygon | def add_polygon(
self,
nodes,
boundary_id=-1,
):
self.add_nodes(
nodes=nodes,
subsections=1, # Need to be 1, otherwise it won't be a polygon
is_polygon=True,
boundary_id=boundary_id,
) | Python | nomic_cornstack_python_v1 |
comment drawing a Spinograph
import turtle as T
import random
function random_colour
begin
set r = random integer 0 255
set g = random integer 0 255
set b = random integer 0 255
return tuple r g b
end function
set tmnt = call Turtle
call shape string turtle
call speed string fastest
call colormode 255
comment we want t... | # drawing a Spinograph
import turtle as T
import random
def random_colour():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
tmnt = T.Turtle()
tmnt.shape("turtle")
tmnt.speed("fastest")
T.colormode(255)
# we want turtle to make 360 deg turn then stop -... | Python | zaydzuhri_stack_edu_python |
for i in range t
begin
set n = integer input
set ans = 0
while n >= 0
begin
set ans = ans + n * n
set n = n - 2
end
print ans
end | for i in range(t):
n = int(input())
ans = 0
while(n>=0):
ans+= n*n
n=n-2
print(ans)
| Python | zaydzuhri_stack_edu_python |
from pynput import mouse
from pynput.mouse import Button , Controller
from os import system , name
comment import os
function clear
begin
comment for windows
if name == string nt
begin
set _ = call system string cls
end
else
begin
comment for mac and linux(here, os.name is 'posix')
set _ = call system string clear
end
... | from pynput import mouse
from pynput.mouse import Button, Controller
from os import system, name
#import os
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
mouse = Controller()
n = 1
while n == 1:
... | Python | zaydzuhri_stack_edu_python |
function __getitem__ self s
begin
try
begin
return call coefficients at s
end
except KeyError
begin
return call zero_element
end
end function | def __getitem__(self, s) :
try :
return self.coefficients()[s]
except KeyError :
return self.parent().coefficient_domain().zero_element() | Python | nomic_cornstack_python_v1 |
function timestamp_rfc3339
begin
return call isoformat string T + string Z
end function | def timestamp_rfc3339():
return datetime.utcnow().isoformat("T") + "Z" | Python | nomic_cornstack_python_v1 |
string Author: Tim Henderson Date Started: January 28, 2008 This module does connection pooling for mysql connections. Handles connecting and and closing connections for the user. Must be configured by user before use. Usage: setup: import db db.HOST = HOST db.PORT = PORT db.USER = USER db.PASSWD = PASSWD db.DB = DB ge... | '''
Author: Tim Henderson
Date Started: January 28, 2008
This module does connection pooling for mysql connections. Handles connecting and and closing
connections for the user. Must be configured by user before use.
Usage:
setup:
import db
db.HOST = HOST
db.PORT = PORT
db.USER = U... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Jan 9 15:41:08 2021 @author: nakaharakan
from keras.models import Sequential
from keras.layers.core import Dropout
from keras.layers import Dense , Activation , Reshape , Conv1D , Conv2D , MaxPooling1D , Flatten , BatchNormalization
from ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 9 15:41:08 2021
@author: nakaharakan
"""
from keras.models import Sequential
from keras.layers.core import Dropout
from keras.layers import Dense,Activation,Reshape,Conv1D,Conv2D,MaxPooling1D,Flatten,BatchNormalization
from keras.callbacks import ... | Python | zaydzuhri_stack_edu_python |
if a == b
begin
print string a is equal to b.
end
if a == b
begin
print string a is equal to b.
end
else
if a > b
begin
print string a is greater than b.
end
else
begin
print string a is less than b.
end
comment Here I want to add more about logical operators
comment '==' equals
comment '!=' not equals
comment '>' grea... | if a==b:
print('a is equal to b.')
if a==b:
print('a is equal to b.')
elif a>b:
print('a is greater than b.')
else:
print('a is less than b.')
# Here I want to add more about logical operators
# '==' equals
# '!=' not equals
# '>' greater than
# '<' less than
# '>=' greterthan equal t... | Python | zaydzuhri_stack_edu_python |
function revoke_prefix self prefix
begin
string Revoke all secrets (via a lease ID prefix) or tokens (via the tokens' path property) generated under a given prefix immediately. This requires sudo capability and access to it should be tightly controlled as it can be used to revoke very large numbers of secrets/tokens at... | def revoke_prefix(self, prefix):
"""Revoke all secrets (via a lease ID prefix) or tokens (via the tokens' path property) generated under a given
prefix immediately.
This requires sudo capability and access to it should be tightly controlled as it can be used to revoke very
large numbers... | Python | jtatman_500k |
function load_scenario self scenario_to_load
begin
comment read in the scenario file
set scenario : dict = call read_file_as_json scenario_to_load SCENARIOS_DIRECTORY
comment decode json
set model_file = scenario at string model
set max_slope = scenario at string max_slope
set start_coordinates = scenario at string sta... | def load_scenario(self, scenario_to_load):
# read in the scenario file
scenario: dict = utils.read_file_as_json(scenario_to_load, PathManager.SCENARIOS_DIRECTORY)
# decode json
model_file = scenario['model']
max_slope = scenario['max_slope']
start_coordinates = scenario... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
from numpy.core.function_base import linspace
set x = linear space 0 10 100
plot x x + 0 string pg
plot x x + 2 string -.b
show | import matplotlib.pyplot as plt
import numpy as np
from numpy.core.function_base import linspace
x=np.linspace(0,10,100)
plt.plot(x,x+0,'pg')
plt.plot(x,x+2,'-.b')
plt.show() | Python | zaydzuhri_stack_edu_python |
function on_delVar self items=none
begin
if items is none
begin
set selItems = call selectedItems or list
end
else
begin
set selItems = items
end
for item in selItems
begin
call takeTopLevelItem call indexOfTopLevelItem item
end
call rf_columnSize
end function | def on_delVar(self, items=None):
if items is None:
selItems = self.twVar.selectedItems() or []
else:
selItems = items
for item in selItems:
self.twVar.takeTopLevelItem(self.twVar.indexOfTopLevelItem(item))
self.rf_columnSize() | Python | nomic_cornstack_python_v1 |
function swap_simplex_orientation simplex
begin
set opposite_simplex = copy np simplex
set tuple opposite_simplex at - 1 opposite_simplex at - 2 = tuple opposite_simplex at - 2 opposite_simplex at - 1
return opposite_simplex
end function | def swap_simplex_orientation(simplex):
opposite_simplex = np.copy(simplex)
opposite_simplex[-1], opposite_simplex[-2] = opposite_simplex[-2], opposite_simplex[-1]
return opposite_simplex | Python | nomic_cornstack_python_v1 |
function create_underline self tag
begin
string See if span tag has underline style and wrap with u tag.
set style = get tag string style
if style and string text-decoration:underline in style
begin
call wrap call new_tag string u
end
end function | def create_underline(self, tag):
"""
See if span tag has underline style and wrap with u tag.
"""
style = tag.get('style')
if style and 'text-decoration:underline' in style:
tag.wrap(self.soup.new_tag('u')) | Python | jtatman_500k |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Sep 5 20:24:38 2021 @author: david_zhang
import utils
import pandas as pd
import re
import datetime as dt
function main rel_df_path rel_results_dir
begin
set df_path = call get_rel_dir __file__ rel_df_path
set results_dir = call get_rel_d... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 5 20:24:38 2021
@author: david_zhang
"""
import utils
import pandas as pd
import re
import datetime as dt
def main(rel_df_path, rel_results_dir):
df_path = utils.get_rel_dir(__file__, rel_df_path)
results_dir = utils.get_rel_dir(__fi... | Python | zaydzuhri_stack_edu_python |
function rand_tensor shape mean sigma
begin
return mean * ones shape + sigma * randn shape
end function | def rand_tensor(shape, mean, sigma):
return mean * torch.ones(shape) + sigma * torch.randn(shape) | Python | nomic_cornstack_python_v1 |
function __getBinaryNetworkValue self
begin
function mulBinSum i1 i j
begin
if integer i * integer j
begin
set __networkValueSum = __networkValueSum + __bitLookUp at i1
return string 1
end
else
begin
return string 0
end
end function
set binaryNetworkValue = string
set startVal = integer __focusValue
set binaryFocusVal... | def __getBinaryNetworkValue(self):
def mulBinSum(i1,i,j):
if int(i)*int(j):
self.__networkValueSum += self.__bitLookUp[i1]
return "1"
else:
return "0"
binaryNetworkValue = ""
startVal = int(self.__focusValue)
binaryF... | Python | nomic_cornstack_python_v1 |
function __init__ self dataset=string cifar10
begin
set data = none
set label = none
set data_shape = none
set sample_number = none
set test_data = none
call load_dataset dataset=dataset
end function | def __init__(self, dataset='cifar10'):
self.data = None
self.label = None
self.data_shape = None
self.sample_number = None
self.test_data = None
self.load_dataset(dataset=dataset) | Python | nomic_cornstack_python_v1 |
function test_relative1 self
begin
set xpb = call XPathBuilder is_relative=true
set xp = foo
set exp = string foo
assert equal call tostring exp
end function | def test_relative1(self):
xpb = XPathBuilder(is_relative=True)
xp = xpb.foo
exp = 'foo'
self.assertEqual(xp.tostring(), exp) | Python | nomic_cornstack_python_v1 |
function _read self fp fpname
begin
set elements_added = set
comment None, or a dictionary
set cursect = none
set sectname = none
set optname = none
set lineno = 0
set indent_level = 0
comment None, or an exception
set e = none
for tuple lineno line in enumerate fp start=1
begin
set comment_start = none
comment strip i... | def _read(self, fp, fpname):
elements_added = set()
cursect = None # None, or a dictionary
sectname = None
optname = None
lineno = 0
indent_level = 0
e = None # None, or an exception
for lineno, line in enumerate(fp, start=1):
comment_start =... | Python | nomic_cornstack_python_v1 |
string Provides class to hold members information Provides methods to sort members by first or last name
class Person
begin
string Holds first name, last name, and email of all memeber
function __init__ self first last email
begin
set first = first
set last = last
set email = email
end function
function __str__ self
be... | """
Provides class to hold members information
Provides methods to sort members by first or last name
"""
class Person:
"""
Holds first name, last name, and email of all memeber
"""
def __init__(self, first, last, email):
self.first = first
self.last = last
self.email = email
... | Python | zaydzuhri_stack_edu_python |
function serve_static request path insecure=false **kwargs
begin
set normalized_path = left strip call normpath unquote path string /
set absolute_path = find finders normalized_path
if not absolute_path
begin
if ends with path string / or path == string
begin
raise call Http404 string Directory indexes are not allowe... | def serve_static(request, path, insecure=False, **kwargs):
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
... | Python | nomic_cornstack_python_v1 |
function insert self index string
begin
call _w string insert index string
end function | def insert(self, index, string):
self.tk.call(self._w, 'insert', index, string) | Python | nomic_cornstack_python_v1 |
function ask_for prompt error_msg=none _type=none
begin
while true
begin
set inp = strip input prompt
if not inp
begin
if error_msg
begin
print error_msg
end
continue
end
if _type
begin
try
begin
set inp = call _type inp
end
except ValueError
begin
if error_msg
begin
print error_msg
end
continue
end
end
return inp
end
... | def ask_for(prompt, error_msg=None, _type=None):
while True:
inp = input(prompt).strip()
if not inp:
if error_msg:
print(error_msg)
continue
if _type:
try:
inp = _type(inp)
except ValueError:
if ... | Python | nomic_cornstack_python_v1 |
from person import Person
from robber import Robber
from pornstar import Pornstar
import csv
class Mentor extends Person
begin
function __init__ self nickname *args **kwargs
begin
call __init__ *args keyword kwargs
set nickname = nickname
end function
decorator classmethod
comment creates and returns a list of mentors
... | from person import Person
from robber import Robber
from pornstar import Pornstar
import csv
class Mentor(Person):
def __init__(self, nickname, *args, **kwargs):
super(Mentor, self).__init__(*args, **kwargs)
self.nickname = nickname
@classmethod
def create_by_csv(cls, csv_file): # creat... | Python | zaydzuhri_stack_edu_python |
function _get_manber_myers_suffixes self seq=none
begin
if not seq
begin
set seq = seq
end
return call _sort_manber_myers list comprehension i for i in range length seq
end function | def _get_manber_myers_suffixes(self, seq:str=None) -> List:
if not seq: seq = self.seq
return self._sort_manber_myers([i for i in range(len(seq))]) | Python | nomic_cornstack_python_v1 |
function nonverbose_config config
begin
if verbose <= 0
begin
yield
end
else
begin
set saved = verbose
set verbose = 0
yield
set verbose = saved
end
end function | def nonverbose_config(config) -> Generator[None, None, None]:
if config.option.verbose <= 0:
yield
else:
saved = config.option.verbose
config.option.verbose = 0
yield
config.option.verbose = saved | Python | nomic_cornstack_python_v1 |
comment ------------------------------------------------------------------------------
comment Question:
comment ------------------------------------------------------------------------------
comment tags:
string Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in th... | # ------------------------------------------------------------------------------
# Question:
# ------------------------------------------------------------------------------
# tags:
'''
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes... | Python | zaydzuhri_stack_edu_python |
import random
import numpy as np
set pop_len = 16
class GA extends object
begin
function __init__ self pop_size
begin
set pop_size = pop_size
set pop_list = list
set result = none
for _ in range pop_size
begin
set temp = string
for _ in range pop_len
begin
set temp = temp + string random integer 0 1
end
append pop_li... | import random
import numpy as np
pop_len = 16
class GA(object):
def __init__(self, pop_size):
self.pop_size = pop_size
self.pop_list = []
self.result = None
for _ in range(pop_size):
temp = ''
for _ in range(pop_len):
temp += str(random.randi... | Python | zaydzuhri_stack_edu_python |
function test_bst_empty_post_order bst_empty
begin
set check_list = list
call post_order_trav lambda x -> append check_list val
assert check_list == list
end function | def test_bst_empty_post_order(bst_empty):
check_list = []
bst_empty.post_order_trav(lambda x: check_list.append(x.val))
assert check_list == [] | Python | nomic_cornstack_python_v1 |
function get_pecan_config
begin
set filename = replace __file__ string .pyc string .py
return filename
end function | def get_pecan_config():
filename = api_config.__file__.replace('.pyc', '.py')
return filename | Python | nomic_cornstack_python_v1 |
function _amber_selection_to_atom_indices_ structure selection
begin
set mask = call AmberMask structure string selection
set mask_idx = list comprehension i for i in call Selected
return mask_idx
end function | def _amber_selection_to_atom_indices_(structure, selection):
mask = parmed.amber.AmberMask(structure, str(selection))
mask_idx = [i for i in mask.Selected()]
return mask_idx | Python | nomic_cornstack_python_v1 |
function read self path
begin
raise call NotImplementedError string Reading of subfaults not implemented yet.
end function | def read(self, path):
raise NotImplementedError("Reading of subfaults not implemented yet.") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment @Date : 2018-07-16 17:17:42
comment @Author : Simon (simon.xie@codewalker.meg)
comment @Link : http://www.codewalker.me
comment @Version : 1.0.0
class P extends object
begin
function __init__ self v
begin
comment A0 step 1.1
print string init P
set dat... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-07-16 17:17:42
# @Author : Simon (simon.xie@codewalker.meg)
# @Link : http://www.codewalker.me
# @Version : 1.0.0
class P(object):
def __init__(self, v):
print('init P') # A0 step 1.1
self.data ... | Python | zaydzuhri_stack_edu_python |
from django.db import models
from django.contrib.auth.models import User
class Endereco extends Model
begin
set logradouro = call CharField max_length=128
set complemento = call CharField max_length=256 null=true
set uf = call CharField max_length=2 null=true
set cidade = call CharField max_length=64 null=true
set cep ... | from django.db import models
from django.contrib.auth.models import User
class Endereco (models.Model):
logradouro = models.CharField(max_length=128)
complemento = models.CharField(max_length=256, null=True)
uf = models.CharField(max_length=2,null=True)
cidade = models.CharField(max_length=64, null=T... | Python | zaydzuhri_stack_edu_python |
function with_default_parameters number1 number2=3
begin
return number1 + number2
end function
print call with_default_parameters 1 2
print call with_default_parameters 1
print call with_default_parameters | def with_default_parameters(number1, number2=3):
return number1+number2
print(with_default_parameters(1, 2))
print(with_default_parameters(1))
print(with_default_parameters())
| Python | zaydzuhri_stack_edu_python |
function max_output_buffer self *args **kwargs
begin
return call rate_match_sptr_max_output_buffer self *args keyword kwargs
end function | def max_output_buffer(self, *args, **kwargs):
return _my_lte_swig.rate_match_sptr_max_output_buffer(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
import tkinter as tk
from tkcalendar import Calendar , DateEntry
import sqlite3
function exitserieCat
begin
call destroy
end function
function SerieEntry
begin
set sTitle_entry = get sTitle
set sDate_entry = get sDate
set nSeasons_entry = get nSeasons
set nEpisodes_entry = get nEpisodes
set nGenre_entry = get nGenre
se... | import tkinter as tk
from tkcalendar import Calendar,DateEntry
import sqlite3
def exitserieCat():
windowCat.destroy()
def SerieEntry():
sTitle_entry = sTitle.get()
sDate_entry = sDate.get()
nSeasons_entry = nSeasons.get()
nEpisodes_entry = nEpisodes.get()
nGenre_entry = nGenre.get()
nArti... | Python | zaydzuhri_stack_edu_python |
function make_task_with_deps self function dependencies *args
begin
return call Task partial function *args dependencies
end function | def make_task_with_deps(self, function, dependencies: List[Task], *args):
return Task(partial(function, *args), dependencies) | Python | nomic_cornstack_python_v1 |
function longest_line model
begin
set counts = default dictionary list
for line in call lines
begin
append counts at length stations line
end
set max_count = max keys counts
return tuple max_count counts at max_count
end function | def longest_line(model: Model) -> Tuple[int, List[str]]:
counts = defaultdict(list)
for line in model.lines():
counts[len(model.line(line).stations)].append(line)
max_count = max(counts.keys())
return (max_count, counts[max_count]) | Python | nomic_cornstack_python_v1 |
function get_action self s eval=false
begin
if eval
begin
with no grad
begin
set action = call get_best_action to s at tuple none Ellipsis device
end
end
else
if step_count < 20000
begin
set action = action_space at random integer action_space_len
end
else
begin
with no grad
begin
set tuple action _ _ = call sample_act... | def get_action(self, s, eval=False):
if eval:
with torch.no_grad():
action = self.actor.get_best_action(s[None, ...].to(self.device))
else:
if self.step_count < 20000:
action = self.action_space[np.random.randint(self.action_space_len)]
... | Python | nomic_cornstack_python_v1 |
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
comment Define the LeakyReLU activation function
set leaky_relu = leaky relu
comment Define the deep neural network architecture
class... | import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
# Define the LeakyReLU activation function
leaky_relu = nn.LeakyReLU()
# Define the deep neural network architecture
class DeepNet(n... | Python | jtatman_500k |
function test_xblockcompletion_get_all_data self report
begin
set state_1 = dict string answer_id string answer_id ; string question string question_text ; string answer string answer_text ; string correct_answer string correct_answer_text ; string username username ; string email email ; string user_rut string ; stri... | def test_xblockcompletion_get_all_data(self, report):
state_1 = {
'answer_id': 'answer_id',
'question': 'question_text',
'answer': 'answer_text',
'correct_answer': 'correct_answer_text',
'username': self.student.username,
'email': self.stud... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import logging
import json
import urllib
import urllib2
import time
from common.Database import Database
from weather import weather
class update_weather_data
begin
function __init__ self city=none
begin
set city = city
comment set the logger
set log_level = DE... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import json
import urllib
import urllib2
import time
from common.Database import Database
from weather import weather
class update_weather_data:
def __init__(self, city=None):
self.city = city
# set the logger
self.log_level... | Python | zaydzuhri_stack_edu_python |
function execute self cast
begin
set paddles = cast at string paddle
set bricks = cast at string brick
set ball = cast at string ball at 0
set score = cast at string score at 0
comment breaks the bricks the ball runs into
for brick in bricks
begin
if call equals call get_position
begin
call invert_y
remove bricks brick... | def execute(self, cast):
paddles = cast["paddle"]
bricks = cast["brick"]
ball = cast["ball"][0]
score = cast["score"][0]
# breaks the bricks the ball runs into
for brick in bricks:
if ball.get_position().equals(brick.get_position()):... | Python | nomic_cornstack_python_v1 |
string Parcel graph construction Input: template_file = location of parcel template (.nii) Output: graph_adjacent = binary dxd matrix with 1 for spatially-connected parcels (.mat) graph_bilateral = binary dxd matrix with 1 for bilateral parcel pairs (.mat) graph_right_ipsi = binary dxd matrix with 1 for spatially-conne... | """
Parcel graph construction
Input: template_file = location of parcel template (.nii)
Output: graph_adjacent = binary dxd matrix with 1 for spatially-connected parcels (.mat)
graph_bilateral = binary dxd matrix with 1 for bilateral parcel pairs (.mat)
graph_right_ipsi = binary dxd matrix with 1 for s... | Python | zaydzuhri_stack_edu_python |
function square n start_i start_j num
begin
global ans r c
if n == 0
begin
set ans = num
end
else
begin
set interval = 2 ^ n - 1
if start_i <= r < start_i + interval
begin
comment top-left
if start_j <= c < start_j + interval
begin
call square n - 1 start_i start_j num
end
else
begin
comment top-right
call square n - 1... | def square(n, start_i, start_j, num):
global ans, r ,c
if n == 0:
ans = num
else:
interval = 2**(n-1)
if start_i<=r<start_i+interval:
if start_j<=c<start_j+interval: # top-left
square(n-1, start_i, start_j, num)
else: # top-right
... | Python | zaydzuhri_stack_edu_python |
import re
function binary given_str
begin
return match string ^[0|1]+$ given_str
end function
function binary_even given_str
begin
return match string .+0$ given_str
end function
function hex given_str
begin
return match string ^[A-F0-9]+$ given_str
end function
function word given_str
begin
return match string ^[\w]*[... | import re
def binary(given_str):
return re.match(r"^[0|1]+$", given_str)
def binary_even(given_str):
return re.match(r".+0$", given_str)
def hex(given_str):
return re.match(r"^[A-F0-9]+$", given_str)
def word(given_str):
return re.match(r"^[\w]*[-]*[A-Za-z]+$", given_str)
def words(given_str, ... | Python | zaydzuhri_stack_edu_python |
function __init__ self name problem kwargs
begin
call __init__ self name problem kwargs
call set_default_attr string dim call get_dim
end function | def __init__( self, name, problem, kwargs ):
MiniAppBase.__init__( self, name, problem, kwargs )
self.set_default_attr( 'dim', problem.get_dim() ) | Python | nomic_cornstack_python_v1 |
from models.db_queries import *
import models.user as user
comment from db_queries import *
comment def is_exist(email):
comment query = '''SELECT count(*) FROM item
comment WHERE mail = '{}' '''.format(email)
comment res = select_query(query)
comment if res[0].get('count(*)') > 0:
comment return True
comment return Fa... | from models.db_queries import *
import models.user as user
# from db_queries import *
# def is_exist(email):
# query = '''SELECT count(*) FROM item
# WHERE mail = '{}' '''.format(email)
# res = select_query(query)
# if res[0].get('count(*)') > 0:
# return True
# return False
def insert(n... | Python | zaydzuhri_stack_edu_python |
function get_xs_to_plot values
begin
set xmin = min values
set xmax = max values
set span = xmax - xmin
set xmin = xmin - 0.02 * span
set xmax = xmax + 0.02 * span
return linear space xmin xmax 400
end function | def get_xs_to_plot(values):
xmin = min(values)
xmax = max(values)
span = xmax - xmin
xmin -= 0.02*span
xmax += 0.02*span
return np.linspace(xmin, xmax, 400) | Python | nomic_cornstack_python_v1 |
function _get_sma cls df column windows
begin
string get simple moving average :param df: data :param column: column to calculate :param windows: collection of window of simple moving average :return: None
set window = call get_only_one_positive_int windows
set column_name = format string {}_{}_sma column window
set df... | def _get_sma(cls, df, column, windows):
""" get simple moving average
:param df: data
:param column: column to calculate
:param windows: collection of window of simple moving average
:return: None
"""
window = cls.get_only_one_positive_int(windows)
... | Python | jtatman_500k |
function build_time_series_hidden_layers self
begin
set time_series_hidden_layers = dict
for tuple name time_series in items time_series_features
begin
set time_series_hidden_layers at name = call _build_cnn_layers inputs=time_series hparams=time_series_hidden at name scope=name + string _hidden
end
set time_series_hi... | def build_time_series_hidden_layers(self):
time_series_hidden_layers = {}
for name, time_series in self.time_series_features.items():
time_series_hidden_layers[name] = self._build_cnn_layers(
inputs=time_series,
hparams=self.hparams.time_series_hidden[name],
scope=name + "_hi... | Python | nomic_cornstack_python_v1 |
function writetags self
begin
comment FIXME: need to manually remove those tags not needed
comment the logic is here, just need the first tag to identify
set tagssections = dictionary
for tuple i pid in enumerate pids
begin
set taglist = piddb at pid at string tags
if taglist
begin
set lproc = piddb at pid at string pr... | def writetags(self):
#FIXME: need to manually remove those tags not needed
#the logic is here, just need the first tag to identify
tagssections = dict()
for i, pid in enumerate(self.pids):
taglist = self.piddb[pid]['tags']
if taglist:
lproc ... | Python | nomic_cornstack_python_v1 |
import sys , pygame
call init
set screen = call set_mode tuple 500 500
set ball = load image string intro_ball.gif
set red = call Color 255 0 0
while true
begin
for event in get event
begin
if type == QUIT
begin
call quit
exit
end
end
comment 画线
call line screen red tuple 10 10 tuple 200 200 10
comment 画矩形 pygame.draw.... | import sys, pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
ball = pygame.image.load("intro_ball.gif")
red = pygame.Color(255, 0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#画线
pygame.draw.line(... | Python | zaydzuhri_stack_edu_python |
function write_assemblies_data cls samp_ids
begin
set samp_tab = string view_samples_ena_manifest_assembly
set assemb_samples = call fetch_entries samp_tab sample_ids=samp_ids
with zip file call get_tempfile string a as zipObj
begin
for sample in assemb_samples
begin
set seqbunch = call SeqFilesBunch sample at string s... | def write_assemblies_data(cls, samp_ids: list) -> None:
samp_tab = "view_samples_ena_manifest_assembly"
assemb_samples = Samples.fetch_entries(samp_tab, sample_ids=samp_ids)
with ZipFile(cls.get_tempfile(), "a") as zipObj:
for sample in assemb_samples:
seqbunch = Seq... | Python | nomic_cornstack_python_v1 |
function view_user
begin
return
end function | def view_user():
return | Python | nomic_cornstack_python_v1 |
function toggle_previous_layout self
begin
call toggle_layout string previous
end function | def toggle_previous_layout(self):
self.toggle_layout('previous') | Python | nomic_cornstack_python_v1 |
import datetime
from google.cloud import bigquery
from pytz import timezone
function check_exist_table dataset_id table_id
begin
string Method that check a table in the dataset - will create the table if not exist :param dataset_id: dataset :table_id: table name
set client = call Client
set dataset_ref = call dataset d... | import datetime
from google.cloud import bigquery
from pytz import timezone
def check_exist_table(dataset_id, table_id):
"""
Method that check a table in the dataset - will create the table if not exist
:param dataset_id: dataset
:table_id: table name
"""
client = bigquery.Client()
... | Python | zaydzuhri_stack_edu_python |
function await_done self timeout=none
begin
if call done
begin
return call result
end
if _future is none
begin
raise call ConnectionObserverNotStarted self
end
call wait_for connection_observer=self connection_observer_future=_future timeout=timeout
return call result
end function | def await_done(self, timeout=None):
if self.done():
return self.result()
if self._future is None:
raise ConnectionObserverNotStarted(self)
self.runner.wait_for(connection_observer=self, connection_observer_future=self._future,
timeout=timeout)... | Python | nomic_cornstack_python_v1 |
import base64
function get_base s key
begin
if key == 64
begin
set ans = decode base64 decode encode s string utf-8 string utf-8
end
if key == 32
begin
set ans = decode call b32decode encode s string utf-8 string utf-8
end
if key == 16
begin
set ans = decode call b16decode encode s string utf-8 string utf-8
end
return ... | import base64
def get_base(s,key):
if key == 64:
ans = base64.b64decode(s.encode('utf-8')).decode('utf-8')
if key == 32:
ans = base64.b32decode(s.encode('utf-8')).decode('utf-8')
if key == 16:
ans = base64.b16decode(s.encode('utf-8')).decode('utf-8')
return ans
| Python | zaydzuhri_stack_edu_python |
function AddIncrementalCustomLearnedRoutesArgs parser
begin
set incremental_args = call add_mutually_exclusive_group required=false
call add_argument string --add-custom-learned-route-ranges type=call ArgList metavar=string CIDR_RANGE help=string A list of user-defined custom learned route IP address ranges to be added... | def AddIncrementalCustomLearnedRoutesArgs(parser):
incremental_args = parser.add_mutually_exclusive_group(required=False)
incremental_args.add_argument(
'--add-custom-learned-route-ranges',
type=arg_parsers.ArgList(),
metavar='CIDR_RANGE',
help="""A list of user-defined custom learned rout... | Python | nomic_cornstack_python_v1 |
if word == alpha
begin
print string YES
end
else
begin
print string NO
end | if word == alpha:
print("YES")
else:
print("NO") | Python | zaydzuhri_stack_edu_python |
function list_types self location publisher_name custom_headers=none raw=false **operation_config
begin
comment Construct URL
set url = string /subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types
set path_format_arguments = dict stri... | def list_types(
self, location, publisher_name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types'
path_format_argumen... | Python | nomic_cornstack_python_v1 |
comment import math
function shape vector
begin
return tuple length vector
end function
function compare_shapes *args
begin
if not length set comprehension call shape item for item in args == 1 == 1
begin
raise ShapeError
end
end function
function vector_add a b
begin
call compare_shapes a b
return list comprehension s... | # import math
def shape(vector):
return (len(vector), )
def compare_shapes(*args):
if not len({shape(item) for item in args}) == 1 == 1:
raise ShapeError
def vector_add(a, b):
compare_shapes(a, b)
return [sum(values) for values in zip(a, b)]
def vector_sub(a, b):
compare_shapes(a, b)... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 4 14:48:26 2019 @author: robert
import parameters as p
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
comment actual root enclosed area 0.316
comment actual tip enclosed area 0.045
comment height at root of the wing box
set h_root =... | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 14:48:26 2019
@author: robert
"""
import parameters as p
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
#actual root enclosed area 0.316
#actual tip enclosed area 0.045
#height at root of the wing box
h_root = 0.929*... | Python | zaydzuhri_stack_edu_python |
function _collEntry self entry
begin
set v = dictionary type=string collection name=call getCollName
set specColl = call getSpecColl
if call getCollClass == MOUNTED_COLL
begin
set specCollDict = dictionary type=call getSpecCollTypeStr collClass=call getCollClass objPath=call getObjPath phyPath=call getPhyPath resource=... | def _collEntry(self, entry):
v = dict( type = 'collection',
name = entry.getCollName() )
specColl = entry.getSpecColl()
if specColl.getCollClass() == irods.MOUNTED_COLL :
specCollDict = dict( type = specColl.getSpecCollTypeStr(),
... | Python | nomic_cornstack_python_v1 |
from django.db import models
comment Create your models here.
class Student extends Model
begin
set name = call CharField max_length=128
set reg_number = call IntegerField unique=true
set age = call IntegerField default=25
set address = call TextField max_length=1024
set physics = call IntegerField default=0
set chemis... | from django.db import models
# Create your models here.
class Student(models.Model):
name = models.CharField(max_length=128)
reg_number = models.IntegerField(unique=True)
age = models.IntegerField(default=25)
address = models.TextField(max_length=1024)
physics = models.IntegerField(default=0)
c... | Python | zaydzuhri_stack_edu_python |
comment Simple CNN model for CIFAR-10
import numpy , keras , tensorflow , pandas
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
... | # Simple CNN model for CIFAR-10
import numpy, keras, tensorflow, pandas
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from kera... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment lucky.py - Opens several Google search results.
import requests , sys , webbrowser , bs4
comment display text while downloading the Google page
print string Googling...
set res = get requests string https://google.com/search?q= + join string argv at slice 1 : :
try
begin
call raise_... | #! /usr/bin/python3
#lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4
print('Googling...') # display text while downloading the Google page
res = requests.get('https://google.com/search?q=' + ' '.join(sys.argv[1:]))
try:
res.raise_for_status()
except Exception as exc:
pri... | Python | zaydzuhri_stack_edu_python |
function board_ssm self ssm_uri
begin
if string file:// in ssm_uri
begin
comment opt A: file based import
try
begin
set ssm_path = replace ssm_uri string file:// string
set ssm_image_name = call splitext base name path ssm_path at 0
set r = call import_image ssm_path repository=ssm_image_name
if string error in r
begin... | def board_ssm(self, ssm_uri):
if "file://" in ssm_uri:
# opt A: file based import
try:
ssm_path = ssm_uri.replace("file://", "")
ssm_image_name = os.path.splitext(os.path.basename(ssm_path))[0]
r = self.dc.import_image(ssm_path, repository=... | Python | nomic_cornstack_python_v1 |
function check_missing_values_in_list given_list n
begin
set created_list = list
for x in range 1 n + 1 1
begin
append created_list x
end
set mising_values_list = list comprehension x for x in created_list if not x in given_list
comment print("given list: ", given_list)
comment print("created list: ",created_list)
com... | def check_missing_values_in_list(given_list,n):
created_list = []
for x in range(1,n+1,1):
created_list.append(x)
mising_values_list = [x for x in created_list if not x in given_list]
#print("given list: ", given_list)
#print("created list: ",created_list)
#print("missing values",mising_values_list)
return m... | Python | nomic_cornstack_python_v1 |
function textCount line
begin
set linesCount = 0
set wordsCount = 0
set charCount = 0
comment splitting string and storing tje list in words variable
set words = split line
comment incrementing lines count
set linesCount = linesCount + 1
comment counting number of words
set wordsCount = wordsCount + length words
commen... | def textCount(line):
linesCount = 0
wordsCount = 0
charCount = 0
# splitting string and storing tje list in words variable
words = line.split()
linesCount += 1 # incrementing lines count
wordsCount += len(words) # counting number of words
# counting number of characters excluding space
... | Python | zaydzuhri_stack_edu_python |
comment 饮食话语输入格式:300克汉堡。
import xlrd
import re
import math
import numpy as np
function read_excel path
begin
comment 打开excel表,填写路径
set book = call open_workbook path
comment 找到sheet页
set table = call sheet_by_name string food_categories
comment 获取总行数总列数
set row_Num = nrows
set col_Num = ncols
if row_Num <= 1
begin
prin... | #饮食话语输入格式:300克汉堡。
import xlrd
import re
import math
import numpy as np
def read_excel(path):
# 打开excel表,填写路径
book = xlrd.open_workbook(path)
# 找到sheet页
table = book.sheet_by_name("food_categories")
# 获取总行数总列数
row_Num = table.nrows
col_Num = table.ncols
if row_Num <= 1:
... | Python | zaydzuhri_stack_edu_python |
function is_all_capitalized word
begin
set p = compile string ^[A-Z]+$
return if expression match word then 1 else 0
end function | def is_all_capitalized(word):
p = re.compile('^[A-Z]+$')
return 1 if p.match(word) else 0 | Python | nomic_cornstack_python_v1 |
function _read_nucmfmt self nuc mf mt lines
begin
set opened_here = false
if is instance fh basestring
begin
set fh = open fh string r
set opened_here = true
end
else
begin
set fh = fh
end
set tuple start stop = mat_dict at nuc at string mfs at tuple mf mt
read line fh
seek fh start
if lines == 0
begin
set s = read fh ... | def _read_nucmfmt(self, nuc, mf, mt, lines):
opened_here = False
if isinstance(self.fh, basestring):
fh = open(self.fh, 'r')
opened_here = True
else:
fh = self.fh
start, stop = self.mat_dict[nuc]['mfs'][mf,mt]
fh.readline()
fh.seek(star... | Python | nomic_cornstack_python_v1 |
import glob
from subprocess import check_output
import json
set intersectCMD = string intersectBed -u -a %s -b %s | wc -l
set result_path = string /data/home/hanfei/dc_intersect_result/
set import_bed_path = string /data/home/qqin/Workspace/Achieved/DCjsons/Codes/top1000peak_directory.txt
comment import_bed_path = "/da... | import glob
from subprocess import check_output
import json
intersectCMD = "intersectBed -u -a %s -b %s | wc -l"
result_path = "/data/home/hanfei/dc_intersect_result/"
import_bed_path = "/data/home/qqin/Workspace/Achieved/DCjsons/Codes/top1000peak_directory.txt"
# import_bed_path = "/data/home/hanfei/text.txt"
class B... | Python | zaydzuhri_stack_edu_python |
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status_admin_status input_yang_obj translated_yang_obj=none
begin
if call _changed
begin
set status = status
end
if call _changed
begin
set last_updated = last_updated
end
return translated_yang_obj
end fu... | def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status_admin_status(
input_yang_obj, translated_yang_obj=None):
if input_yang_obj.status._changed():
input_yang_obj.status = input_yang_obj.status
if input_yang_obj.last_updated._chang... | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
from time import sleep
call setwarnings false
call setmode BCM
set Motor1E = 27
set Motor1A = 17
set Motor1B = 18
set Motor2E = 26
comment 19 13
set Motor2A = 13
comment 26
set Motor2B = 19 | import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
Motor1E = 27
Motor1A = 17
Motor1B = 18
Motor2E = 26
Motor2A = 13 ## 19 13
Motor2B = 19#26
| Python | zaydzuhri_stack_edu_python |
function solve C F X
begin
if C >= X
begin
return X / 2
end
set d = 0
set n = 0
set b = X / 2 + n * F
set t = 0
while d == 0
begin
set a = b
set b = X / 2 + n + 1 * F
set tn = C / 2 + n * F
if tn + b < a
begin
set n = n + 1
set t = t + tn
end
else
begin
set d = 1
set t = t + a
end
end
return t
end function
set T = inte... | def solve(C, F, X):
if C >= X:
return X/2
d = 0
n = 0
b = X/(2 + (n * F))
t = 0
while d == 0:
a = b
b = X/(2 + ((n + 1) * F))
tn = C/(2 + (n * F))
if tn + b < a:
n += 1
t += tn
else:
d = 1
t += a
... | Python | zaydzuhri_stack_edu_python |
function getConsumedPublicIPs self cloudspace
begin
set numpublicips = 0
comment Add the public IP directly attached to the cloudspace
if externalnetworkip
begin
set numpublicips = numpublicips + 1
end
comment Add the number of machines in cloudspace that have public IPs attached to them
set numpublicips = numpublicips... | def getConsumedPublicIPs(self, cloudspace):
numpublicips = 0
# Add the public IP directly attached to the cloudspace
if cloudspace.externalnetworkip:
numpublicips += 1
# Add the number of machines in cloudspace that have public IPs attached to them
numpublicips += s... | Python | nomic_cornstack_python_v1 |
from flask_restful import Resource
import sqlite3
from backend import attributes
import json
comment For accessing the file in a folder contained in the current folder
comment Creates or opens a file called uToronto with a SQLite3 DB
set db = call connect string backend/data/ + torCourseDB check_same_thread=false
set c... | from flask_restful import Resource
import sqlite3
from backend import attributes
import json
# For accessing the file in a folder contained in the current folder
# Creates or opens a file called uToronto with a SQLite3 DB
db = sqlite3.connect(
'backend/data/' + attributes.torCourseDB, check_same_thread=False)
cur... | Python | zaydzuhri_stack_edu_python |
function _on_completions_refreshed self new_completer
begin
with _completer_lock
begin
set completer = new_completer
comment When mycli is first launched we call refresh_completions before
comment instantiating the cli object. So it is necessary to check if cli
comment exists before trying the replace the completer obj... | def _on_completions_refreshed(self, new_completer):
with self._completer_lock:
self.completer = new_completer
# When mycli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before tryin... | Python | nomic_cornstack_python_v1 |
import pyautogui
comment 스크린 샷 찍기
comment img = pyautogui.screenshot()
comment img.save("screenshot.png")#파일로저장
comment pyautogui.mouseInfo()
comment 838,131 204,0,0 #CC0000
comment 1221,777 37,37,38 #252526
set pixel = call pixel 1221 777
print pixel
print call pixelMatchesColor 1221 77 tuple 37 37 38 | import pyautogui
#스크린 샷 찍기
#img = pyautogui.screenshot()
#img.save("screenshot.png")#파일로저장
#pyautogui.mouseInfo()
#838,131 204,0,0 #CC0000
#1221,777 37,37,38 #252526
pixel = pyautogui.pixel(1221,777)
print(pixel)
print(pyautogui.pixelMatchesColor(1221,77,(37,37,38)))
| Python | zaydzuhri_stack_edu_python |
function determine_number_of_buildings energy_system
begin
set number_of_buildings = dict string RESIDENTIAL 0 ; string UTILITY 0
set list_of_assets = call get_all_instances_of_type AggregatedBuilding
for asset in list_of_assets
begin
if numberOfBuildings
begin
set number = numberOfBuildings
if buildingTypeDistribution... | def determine_number_of_buildings(energy_system):
number_of_buildings = {
'RESIDENTIAL': 0,
'UTILITY': 0
}
list_of_assets = energy_system.get_all_instances_of_type(energy_system.esdl.AggregatedBuilding)
for asset in list_of_assets:
if asset.numberOfBuildings:
number... | Python | nomic_cornstack_python_v1 |
function build_matrix_from_pts pts1 pts2 T1=call eye 3 T2=call eye 3 zero_eigen=true
begin
assert shape at 0 == shape at 0 == 3
assert shape == shape == tuple 3 3
comment build constraint matrix
set x1 = matrix multiply T1 pts1
set x2 = matrix multiply T2 pts2
set A = T
comment SVD -> take smallest eigenvector
set tupl... | def build_matrix_from_pts(pts1: np.ndarray, pts2: np.ndarray, T1=np.eye(3), T2=np.eye(3), zero_eigen=True):
assert pts1.shape[0] == pts2.shape[0] == 3
assert T1.shape == T2.shape == (3, 3)
# build constraint matrix
x1 = np.matmul(T1, pts1)
x2 = np.matmul(T2, pts2)
A = np.asarray([x2[0, :] * x1... | Python | nomic_cornstack_python_v1 |
from flask import render_template , flash , redirect
from app import app
comment import our LoginForm class from forms.py
from forms import LoginForm
set variableTest = string Wololo
decorator call route string /
decorator call route string /index
comment index page
function index
begin
set user = dict string nickname ... | from flask import render_template, flash, redirect
from app import app
from .forms import LoginForm # import our LoginForm class from forms.py
variableTest = 'Wololo'
# index page
@app.route('/')
@app.route('/index')
def index():
user = {'nickname': 'Juan'}
posts = [
{
'author': {'nickname': 'John', 'age': 14}... | Python | zaydzuhri_stack_edu_python |
class Pet
begin
comment implement __init__( name , type , tricks ):
function __init__ self name type tricks sound
begin
set name = name
set type = type
set tricks = tricks
set energy = 100
set health = 100
set sound = sound
end function
comment implement the following methods:
comment sleep() - increases the pets energ... | class Pet:
# implement __init__( name , type , tricks ):
def __init__(self, name , type , tricks, sound):
self.name = name
self.type = type
self.tricks = tricks
self.energy = 100
self.health = 100
self.sound = sound
# implement the following methods:
# sle... | Python | zaydzuhri_stack_edu_python |
function stopAutoSave
begin
try
begin
set hou2vr_autoSave = false
end
except AttributeError
begin
pass
end
end function | def stopAutoSave():
try:
hou.session.hou2vr_autoSave = False
except AttributeError:
pass | Python | nomic_cornstack_python_v1 |
function test_update_group_contact_entry self
begin
pass
end function | def test_update_group_contact_entry(self):
pass | Python | nomic_cornstack_python_v1 |
import pickle
from sklearn.utils import shuffle
from tensorflow.contrib.layers import flatten
import tensorflow as tf
import numpy as np
set aug_data_train = string ./train_aug.p
set validation_file = string ./valid.p
set testing_file = string ./test.p
with open aug_data_train mode=string rb as f
begin
set train = load... | import pickle
from sklearn.utils import shuffle
from tensorflow.contrib.layers import flatten
import tensorflow as tf
import numpy as np
aug_data_train = './train_aug.p'
validation_file = './valid.p'
testing_file = './test.p'
with open(aug_data_train, mode='rb') as f:
train = pickle.load(f)
X_train_aug, y_train_... | Python | zaydzuhri_stack_edu_python |
import sqlite3
from flask_restful import Resource , reqparse
from flask_jwt import jwt_required
from models.movie import MovieModel
class Movie extends Resource
begin
set parser = call RequestParser
call add_argument string year type=int required=true help=string This field cannot be left blank!
call add_argument strin... | import sqlite3
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.movie import MovieModel
class Movie(Resource):
parser = reqparse.RequestParser()
parser.add_argument('year',
type=int,
required=True,
help="This field cannot be left blank!"
)
... | Python | zaydzuhri_stack_edu_python |
import sys
import os
import time
import codecs
try
begin
import argparse
import urllib.error
from Bio import SeqIO
from Bio import Entrez
from config import config
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from openpyxl import Workbook
from openpyxl import load_workbook
end
except ImportError as err
be... | import sys
import os
import time
import codecs
try:
import argparse
import urllib.error
from Bio import SeqIO
from Bio import Entrez
from config import config
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from openpyxl import Workbook
from openpyxl import load_workbook
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class bond
begin
function __init__ self C=5 M=100 i=0.03
begin
set tuple C M i = tuple C M i
end function
function __str__ self
begin
return string Coupon payment = { C } , Face value = { M } , and Yield to aturity = { i }
end function
function pricing_loop self n
begin
set tuple C M i = tuple C M i
... | import numpy as np
class bond:
def __init__(self, C=5, M=100, i=0.03):
self.C, self.M, self.i = C, M, i
def __str__(self):
return f'Coupon payment = {self.C}, Face value = {self.M}, and Yield to aturity = {i}'
def pricing_loop(self, n):
C, M, i = self.C, self.M... | Python | zaydzuhri_stack_edu_python |
function _multiline_width multiline_s line_width_fn=len
begin
return max map line_width_fn split re string [ ] multiline_s
end function | def _multiline_width(multiline_s, line_width_fn=len):
return max(map(line_width_fn, re.split("[\r\n]", multiline_s))) | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
class Solution
begin
function convert self s numRows
begin
if length s <= 1 or numRows <= 1
begin
return s
end
set n = 2 * numRows - 2
set dict1 = default dictionary list
for i in range length s
begin
set j = i % n
if j < numRows
begin
append dict1 at j s at i
end
else
begin
set j = ... | from collections import defaultdict
class Solution:
def convert(self, s, numRows):
if len(s)<=1 or numRows<=1:
return s
n=2*numRows-2
dict1=defaultdict(list)
for i in range(len(s)):
j=i%n
if j<numRows:
dict1[j].append(s[i]... | Python | zaydzuhri_stack_edu_python |
comment CHERN NUMBER FOR THE HALDANE MODEL (CONVENTION I) #
import numpy as np
import matplotlib.pyplot as plt
import sys
comment lattice vectors (normalized)
set a1 = 1 / 2 * array list square root 3 1
set a2 = 1 / 2 * array list square root 3 - 1
set avec = vertical stack tuple a1 a2
comment reciprocal lattice vector... | #####################################################
# CHERN NUMBER FOR THE HALDANE MODEL (CONVENTION I) #
#####################################################
import numpy as np
import matplotlib.pyplot as plt
import sys
# lattice vectors (normalized)
a1 = (1/2) * np.array([np.sqrt(3), 1])
a2 = (1/2) * np.array([... | Python | zaydzuhri_stack_edu_python |
function wpanctl self cmd
begin
if _verbose
begin
call _log format string $ Node{}.wpanctl('{}') _index cmd new_line=false
end
set result = check output _wpanctl_cmd + cmd shell=true stderr=STDOUT
comment remove the last char if it is '\n',
if length result >= 1 and result at - 1 == string
begin
set result = result at... | def wpanctl(self, cmd):
if self._verbose:
_log('$ Node{}.wpanctl(\'{}\')'.format(self._index, cmd), new_line=False)
result = subprocess.check_output(self._wpanctl_cmd + cmd, shell=True, stderr=subprocess.STDOUT)
if len(result) >= 1 and result[-1] == '\n': # remove the last char i... | 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.