code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Class is created here class Socialite begin comment The Constructor function __init__ self begin set __Last_Name = string set __First_Name = string set __Picture = string set __Website = string set __Description = string set __UserID = string end function comment method that returns a string representatio...
#Class is created here class Socialite(): #The Constructor def __init__(self): self.__Last_Name = "" self.__First_Name = "" self.__Picture = "" self.__Website = "" self.__Description = "" self.__UserID = "" #method that returns a string representation of object de...
Python
zaydzuhri_stack_edu_python
import unittest from graph import DirectedGraph from exceptions import NodeNotFound class TestDirectedGraph extends TestCase begin function setUp self begin set _graph = call DirectedGraph end function function test_add_edge self begin call add_edge 1 2 assert in 1 _nodes assert in 2 _nodes assert in 1 keys _edges end ...
import unittest from graph import DirectedGraph from exceptions import NodeNotFound class TestDirectedGraph(unittest.TestCase): def setUp(self): self._graph = DirectedGraph() def test_add_edge(self): self._graph.add_edge(1, 2) self.assertIn(1, self._graph._nodes) self.asser...
Python
zaydzuhri_stack_edu_python
function make_shirt size=string large message=string I love Python begin print string Size: + size + string , Message: + message end function call make_shirt call make_shirt string medium call make_shirt string large string Hello America! call make_shirt message=string Goodnight Detroit! size=string medium
def make_shirt(size='large', message='I love Python'): print('Size: ' + size + ', Message: ' + message) make_shirt() make_shirt('medium') make_shirt('large', 'Hello America!') make_shirt(message='Goodnight Detroit!', size='medium')
Python
zaydzuhri_stack_edu_python
function __init__ self *args begin call TIntStrVH_swiginit self call new_TIntStrVH *args end function
def __init__(self, *args): _snap.TIntStrVH_swiginit(self, _snap.new_TIntStrVH(*args))
Python
nomic_cornstack_python_v1
function validate_voltage file voltage begin comment get the filename from the full path set filename = base name path file comment Check 1: comment Check RMS set voltage_rms = square root mean np call square voltage set voltage_mean = absolute mean np voltage set voltage_crest_factor = call percentile absolute voltage...
def validate_voltage(file: str, voltage: np.ndarray): filename = os.path.basename(file) #get the filename from the full path # Check 1: # Check RMS voltage_rms = np.sqrt(np.mean(np.square(voltage))) voltage_mean = np.abs(np.mean(voltage)) voltage_crest_factor = np.percentile(np.abs(voltage), 99...
Python
nomic_cornstack_python_v1
function es_sustantivo pos begin return pos == string NOUN end function
def es_sustantivo(pos): return pos == "NOUN"
Python
nomic_cornstack_python_v1
function complex_passwords self complex_passwords begin set _complex_passwords = complex_passwords end function
def complex_passwords(self, complex_passwords): self._complex_passwords = complex_passwords
Python
nomic_cornstack_python_v1
from db import db from app.models import restaurants_genres class Genre extends Model begin set __tablename__ = string genres set id = call Column Integer primary_key=true set name = call Column String nullable=false set img_src = call Column String nullable=false set restaurants = call relationship string Restaurant s...
from .db import db from app.models import restaurants_genres class Genre(db.Model): __tablename__ = 'genres' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) img_src = db.Column(db.String, nullable=False) restaurants = db.relationship("Restaurant", secondar...
Python
zaydzuhri_stack_edu_python
function peered_vpc self begin return get pulumi self string peered_vpc end function
def peered_vpc(self) -> Optional[pulumi.Input['PeeredVpcArgs']]: return pulumi.get(self, "peered_vpc")
Python
nomic_cornstack_python_v1
function saque valor begin set lista = list set notas = list 100 50 20 10 for nota in notas begin set quantidade = valor // nota append lista quantidade set valor = valor - quantidade * nota end if valor != 0 begin return none end return lista string quantidade = valor//100 lista.append(quantidade) valor = valor - (qu...
def saque(valor): lista = [] notas = [100, 50, 20, 10] for nota in notas: quantidade = valor//nota lista.append(quantidade) valor = valor - (quantidade * nota) if valor != 0: return None return lista ''' quantidade = valor//100 lista.append(quantidad...
Python
zaydzuhri_stack_edu_python
string data packer class Packer begin function __init__ self data begin set _data = data end function decorator property function data self begin return _data end function function decode self encoding=string utf-8 begin string decode bytes to string :param encoding: :return: set data = decode _data encoding set _data ...
""" data packer """ class Packer: def __init__(self, data): self._data = data @property def data(self): return self._data def decode(self, encoding='utf-8'): """ decode bytes to string :param encoding: :return: """ data = self._...
Python
zaydzuhri_stack_edu_python
function start_program begin while true begin call system string cls print string ~~~~~~~~~~~~~ QUIZ INTERFACE ~~~~~~~~~~~~~~~ print string Press (0) to Log in as Admin print string Press (1) to Play the Game print string Press (2) to exit the program set user_input = input string Please Enter your choice : if user_inp...
def start_program(): while True: system('cls') print("\n~~~~~~~~~~~~~ QUIZ INTERFACE ~~~~~~~~~~~~~~~") print("Press (0) to Log in as Admin") print("Press (1) to Play the Game") print("Press (2) to exit the program") user_input = input("Please Enter your choice : ") ...
Python
nomic_cornstack_python_v1
function set_up_for_eigenmode_search self begin set pos0 = call get_positions call update_center_forces call update_virtual_positions call reset_counter string rotcount set forces1E = none end function
def set_up_for_eigenmode_search(self): self.pos0 = self.atoms.get_positions() self.update_center_forces() self.update_virtual_positions() self.control.reset_counter('rotcount') self.forces1E = None
Python
nomic_cornstack_python_v1
import tensorflow as tf comment 1定义变量及滑动平均类 comment 定义一个32位浮点变量,初始值0.0这个代码就是不断更新w1参数 comment 优化w1参数,滑动平均做了个w1的影子 set w1 = call Variable 0 dtype=float32 comment 定义num_updates(NN迭代轮数),初始值为0,不可被优化(训练) comment 这个参数不训练 set global_step = call Variable 0 trainable=false comment 实例化滑动平均类,给删减率为0.99,当前轮数global_step set MOVING_AV...
import tensorflow as tf #1定义变量及滑动平均类 #定义一个32位浮点变量,初始值0.0这个代码就是不断更新w1参数 #优化w1参数,滑动平均做了个w1的影子 w1=tf.Variable(0,dtype=tf.float32) #定义num_updates(NN迭代轮数),初始值为0,不可被优化(训练) #这个参数不训练 global_step=tf.Variable(0,trainable=False) #实例化滑动平均类,给删减率为0.99,当前轮数global_step MOVING_AVERAGE_DECAY=0.99 ema=tf.train.ExponentialMovingAverage(M...
Python
zaydzuhri_stack_edu_python
function xml_parser xml_file begin set x = get root parse ET xml_file set data = call DataFrame index=range 1 length x + 1 columns=list string pitch string onsetSec string offsetSec set n_notes = 0 for event in find all string event begin for e in event begin set tag = tag set iloc at n_notes at tag = decimal text end ...
def xml_parser(xml_file): x = ET.parse(xml_file).getroot() data = pd.DataFrame( index=range(1, len(x) + 1), columns=['pitch', 'onsetSec', 'offsetSec'] ) n_notes = 0 for event in x.findall('event'): for e in event: tag = e.tag data.iloc[n_notes][tag] = float(e...
Python
nomic_cornstack_python_v1
import sys set stdin = open string 1987.alphabet.txt import collections set dyx = list list 1 0 list - 1 0 list 0 - 1 list 0 1 function bfs y x begin global maxi set q = deque list tuple y x string sheet at 0 at 0 1 while q begin set tuple y x check step = call popleft for i in range 4 begin set ny = dyx at i at 0 + y ...
import sys sys.stdin=open('1987.alphabet.txt') import collections dyx=[[1,0],[-1,0],[0,-1],[0,1]] def bfs(y,x): global maxi q=collections.deque([(y,x,str(sheet[0][0]),1)]) while q: y,x,check,step=q.popleft() for i in range(4): ny=dyx[i][0]+y nx=dyx[i][1]+x ...
Python
zaydzuhri_stack_edu_python
import time try begin import urllib.urequest as urllibreq end except any begin import urllib.request as urllibreq end function GetStartTimes2 hour begin set data = dict set data at string language = string de set data at string commonMacro = string true set data at string name_origin = string 2000124 set data at strin...
import time try: import urllib.urequest as urllibreq except: import urllib.request as urllibreq def GetStartTimes2(hour): data = {} data['language'] = 'de' data['commonMacro'] = 'true' data['name_origin'] = '2000124' data['type_origin'] = 'any' data['nameInput_origin'] = '2000124' ...
Python
zaydzuhri_stack_edu_python
function undeploy_advance_op_handler self begin call __undeploy_function string advance_op end function
def undeploy_advance_op_handler(self): self.__undeploy_function("advance_op")
Python
nomic_cornstack_python_v1
string Author: Sanidhya Mangal, Ravinder Singh github:sanidhyamangal email: sanidhya.mangal@engineerbabu import datetime import uuid from django.db import models comment Create your models here. class BaseModel extends Model begin string A base model to deal with all the asbtracrt level model creations class Meta begin...
""" Author: Sanidhya Mangal, Ravinder Singh github:sanidhyamangal email: sanidhya.mangal@engineerbabu """ import datetime import uuid from django.db import models # Create your models here. class BaseModel(models.Model): """A base model to deal with all the asbtracrt level model creations""" class Meta: ...
Python
zaydzuhri_stack_edu_python
from datetime import datetime , timedelta from time import sleep import requests import tempfile import pytz from polybot import Bot from insight import fetch_images class InsightImages extends Bot begin function init self begin set state at string last_img_time = replace call datetime 2020 9 5 0 0 0 tzinfo=utc set sta...
from datetime import datetime, timedelta from time import sleep import requests import tempfile import pytz from polybot import Bot from insight import fetch_images class InsightImages(Bot): def init(self): self.state["last_img_time"] = datetime(2020, 9, 5, 0, 0, 0).replace(tzinfo=pytz.utc) self....
Python
zaydzuhri_stack_edu_python
comment Roger Guo comment CMSC 210 comment Homework Assignment #1 comment IHRTLUHC comment An alternative way to fit a quadratic polynomial to a set of three data points (using two linear interpolations) comment The initial set of data points set x0 = 1.04 set y0 = 2.71 set x1 = 1.51 set y1 = 2.55 set x2 = 1.83 set y2 ...
# Roger Guo # CMSC 210 # Homework Assignment #1 # IHRTLUHC # An alternative way to fit a quadratic polynomial to a set of three data points (using two linear interpolations) # The initial set of data points x0 = 1.04 y0 = 2.71 x1 = 1.51 y1 = 2.55 x2 = 1.83 y2 = 2.82 # To construct the equation of a line...
Python
zaydzuhri_stack_edu_python
comment Analisis gramatico de las oraciones que se utilizaron para el experimento de Cloze-Task Oraciones online en 2020 ### comment Importo los paquetes necesarios from os import get_terminal_size from numpy import False_ , true_divide import spacy from spacy_syllables import SpacySyllables import pandas as pd import ...
### Analisis gramatico de las oraciones que se utilizaron para el experimento de Cloze-Task Oraciones online en 2020 ### ### Importo los paquetes necesarios from os import get_terminal_size from numpy import False_, true_divide import spacy from spacy_syllables import SpacySyllables import pandas as pd import re impo...
Python
zaydzuhri_stack_edu_python
function test_process_view_middleware self begin get client string /utils/xview/ end function
def test_process_view_middleware(self): self.client.get('/utils/xview/')
Python
nomic_cornstack_python_v1
function __init__ self hidden_size num_layers=1 input_size=none bias=true batch_first=false dropout=0 bidirectional=false name=none begin comment checking the input_size, it is a optional field if input_size is not none and not is instance input_size int and input_size > 0 begin raise call ValueError string Please prov...
def __init__( self, hidden_size, num_layers=1, input_size=None, bias=True, batch_first=False, dropout=0, bidirectional=False, name=None, ): # checking the input_size, it is a optional field if input_size is not None and not ( ...
Python
nomic_cornstack_python_v1
function keep_evens nums begin set new_list = list comprehension num * 2 for num in nums if num % 2 == 0 return new_list end function print call keep_evens list 3 4 6 7 0 1 set things = list 3 4 6 7 0 1 comment chaining together filter and map: comment first, filter to keep only the even numbers comment double each of ...
#################################################### def keep_evens(nums): new_list = [num*2 for num in nums if num % 2 == 0] return new_list print(keep_evens([3, 4, 6, 7, 0, 1])) #################################################### things = [3, 4, 6, 7, 0, 1] # chaining together filter and map: # first, filte...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup from collections import Counter comment request to get the html set response = get requests string http://example.com/ comment parse the html set soup = call BeautifulSoup text string html.parser comment retrieve the text from the page set text = get text soup comment get t...
import requests from bs4 import BeautifulSoup from collections import Counter #request to get the html response = requests.get('http://example.com/') # parse the html soup = BeautifulSoup(response.text, 'html.parser') # retrieve the text from the page text = soup.get_text() # get the word count words = text.split()...
Python
flytech_python_25k
function total_items_discount self total_items_discount begin set _total_items_discount = total_items_discount end function
def total_items_discount(self, total_items_discount): self._total_items_discount = total_items_discount
Python
nomic_cornstack_python_v1
function pc_nproduced self begin return call ldpc_encoder_sptr_pc_nproduced self end function
def pc_nproduced(self): return _ccsds_swig.ldpc_encoder_sptr_pc_nproduced(self)
Python
nomic_cornstack_python_v1
function count_trees right begin set col = 0 set count = 0 with open string input.txt string r as fil begin set line = read line fil set col = col + right set col = col % length line - 1 while line begin set line = read line fil if length line == 0 begin break end if line at col == string # begin set count = count + 1 ...
def count_trees(right): col = 0 count = 0 with open('input.txt', 'r') as fil: line = fil.readline() col += right col = col % (len(line) - 1) while line: line = fil.readline() if len(line) == 0: break if line[col] == '#': ...
Python
zaydzuhri_stack_edu_python
import torch set x1 = tensor print x1 set x2 = tensor list 1 2 3 print x2 print size x2 print dtype set x3 = tensor list 1 2 3 set x4 = call as_tensor list 1 2 3 print x3 print x4 print x3 + x4 comment print (x2+x3) print dtype print device print layout print call eye 2 print zeros 2 2 print ones 2 2 print call rand 2 ...
import torch x1 = torch.Tensor() print (x1) x2 = torch.Tensor([1,2,3]) print (x2) print (x2.size()) print (x2.dtype) x3 = torch.tensor([1,2,3]) x4 = torch.as_tensor([1,2,3]) print (x3) print (x4) print (x3+x4) #print (x2+x3) print (x4.dtype) print (x4.device) print (x4.layout) print (torch.eye(2)) print (torch.zer...
Python
zaydzuhri_stack_edu_python
function grab self monitor begin comment type: (Monitor) -> ScreenShot string See :meth:`MSSMixin.grab <mss.base.MSSMixin.grab>` for full details. comment pylint: disable=too-many-locals comment Convert PIL bbox style if is instance monitor tuple begin set monitor = dict string left monitor at 0 ; string top monitor at...
def grab(self, monitor): # type: (Monitor) -> ScreenShot """ See :meth:`MSSMixin.grab <mss.base.MSSMixin.grab>` for full details. """ # pylint: disable=too-many-locals # Convert PIL bbox style if isinstance(monitor, tuple): monitor = { ...
Python
jtatman_500k
function test_check_min_cppstd_from_outdated_settings cppstd begin set conanfile = call _create_conanfile string gcc string 9 string Linux cppstd string libstdc++ with raises ConanInvalidConfiguration as exc begin call check_min_cppstd conanfile string 17 false end assert format string Current cppstd ({}) is lower than...
def test_check_min_cppstd_from_outdated_settings(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", cppstd, "libstdc++") with pytest.raises(ConanInvalidConfiguration) as exc: check_min_cppstd(conanfile, "17", False) assert "Current cppstd ({}) is lower than the required C++ standard (17)." ...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import pylab as P set df = read csv string psq-tms.csv unique set trial1 = df at string Population type == string Asylum seekers set trial2 = df at string Population type == string Refugees comment sum(trial1|trial2) set df = df at trial1 ? trial2 set columns = list string Destina...
import pandas as pd import numpy as np import pylab as P df = pd.read_csv("psq-tms.csv") df["Population type"].unique() trial1 = (df["Population type"] == "Asylum seekers") trial2 = (df["Population type"] == "Refugees") # sum(trial1|trial2) df = df[trial1|trial2] df.columns = ["Destination", "Origin", "Type", ...
Python
zaydzuhri_stack_edu_python
string Abstracts calculation of delta in the output and gradient delta. import numpy as np from numpy import ndarray as Tensor class LossFunction begin function calcOutputLoss self expectedOutput predictedOutput begin raise NotImplementedError end function function calcOuptutGradient self expectedOutput predictedOutput...
""" Abstracts calculation of delta in the output and gradient delta. """ import numpy as np from numpy import ndarray as Tensor class LossFunction: def calcOutputLoss(self, expectedOutput: Tensor, predictedOutput: Tensor) -> float: raise NotImplementedError def calcOuptutGradient(self, expectedOutput...
Python
zaydzuhri_stack_edu_python
function db_show_all begin set the_list = list set db = open the_phone_book_name flag=string c writeback=true for key in db begin set person = call Person set name = key set phone = db at key append the_list person end call display_list the_list close db end function
def db_show_all(): the_list = [] db = sh.open(the_phone_book_name, flag='c', writeback=True) for key in db: person = Person() person.name = key person.phone = db[key] the_list.append(person) display_list(the_list) db.close()
Python
nomic_cornstack_python_v1
string 给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称。 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入:columnNumber = 1 输出:"A" 示例 2: 输入:columnNumber = 28 输出:"AB" 示例 3: 输入:columnNumber = 701 输出:"ZY" 示例 4: 输入:columnNumber = 2147483647 输出:"FXSHRXW" 提示: 1 <= columnNumber <= 231 - 1 from leetcode.tools.time i...
''' 给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称。 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入:columnNumber = 1 输出:"A" 示例 2: 输入:columnNumber = 28 输出:"AB" 示例 3: 输入:columnNumber = 701 输出:"ZY" 示例 4: 输入:columnNumber = 2147483647 输出:"FXSHRXW" 提示: 1 <= columnNumber <=...
Python
zaydzuhri_stack_edu_python
comment Dictionary basics :D comment 1 - Define a dictionary call story1, it should have the followign keys: comment start, middle and end set story_dict = dict string start string In the beginning there was a hero named bob ; string middle string as he fought on with the evil wizard his bald head kept shining like a c...
# Dictionary basics :D #1 - Define a dictionary call story1, it should have the followign keys: # start, middle and end story_dict = {'start': 'In the beginning there was a hero named bob', 'middle': 'as he fought on with the evil wizard his bald head kept shining like a cue ball', '...
Python
zaydzuhri_stack_edu_python
function enable auto_colors=false reset_atexit=false begin string Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related tags. reset_atexit -- res...
def enable(auto_colors=False, reset_atexit=False): """Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related ...
Python
jtatman_500k
import datacube from datacube.storage.masking import mask_invalid_data import xarray as xr import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure from scripts.combiner import create_composite , get_mask function ploting_rgb_xarray_for_one_day x_array time_index min_possible=0 max_possib...
import datacube from datacube.storage.masking import mask_invalid_data import xarray as xr import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure from scripts.combiner import create_composite, get_mask def ploting_rgb_xarray_for_one_day(x_array,time_index, min_possible=0, max_possib...
Python
zaydzuhri_stack_edu_python
import openpyxl , os change directory string F:// comment print(os.listdir()) set wb = call load_workbook string example.xlsx print type wb print call get_sheet_names set sheet = call get_sheet_by_name string Sheet3 print sheet print type sheet print title set anotherSheet = active comment anotherSheet = wb.get_active_...
import openpyxl, os os.chdir("F://") #print(os.listdir()) wb = openpyxl.load_workbook('example.xlsx') print(type(wb)) print(wb.get_sheet_names()) sheet = wb.get_sheet_by_name('Sheet3') print(sheet) print(type(sheet)) print(sheet.title) anotherSheet = wb.active #anotherSheet = wb.get_active_sheet() changed to...
Python
zaydzuhri_stack_edu_python
from random import randint comment delete from random import seed from collections import Counter comment When submit assignment, delete it function dice_type_recogniser dice begin set counter = dict for num in range 6 begin set counter at num = 0 end for d in dice begin set counter at d = counter at d + 1 end set max...
from random import randint from random import seed # delete from collections import Counter # When submit assignment, delete it def dice_type_recogniser(dice): counter = {} for num in range(6): counter[num] = 0 for d in dice: counter[d] += 1 max_dice_num = max(counter.values()) i...
Python
zaydzuhri_stack_edu_python
import unittest from app.utility.validator import validate_name , validate_id , validate_phone_number class TestUtility extends TestCase begin function test_validate_name_with_valid_input self begin assert equal true call validate_name string ชายยย end function function test_validate_name_with_valid_input_string_of_int...
import unittest from app.utility.validator import validate_name, validate_id, validate_phone_number class TestUtility(unittest.TestCase): def test_validate_name_with_valid_input(self): self.assertEqual(True, validate_name("ชายยย")) def test_validate_name_with_valid_input_string_of_int(self): ...
Python
zaydzuhri_stack_edu_python
function convert celsius begin set fahrenheit = celsius * 1.8 + 32 return fahrenheit end function function table begin print format string {:10} {:10} string F string C for temp in range - 30 50 10 begin print format string {:5} {:7} call convert temp temp end end function call table
def convert(celsius): fahrenheit = celsius * 1.8 + 32 return fahrenheit def table(): print('{:10} {:10}'.format('F', 'C')) for temp in range(-30, 50, 10): print('{:5} {:7}'.format(convert(temp), temp)) table()
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 import json import base64 from urllib import urlencode from urllib2 import urlopen , Request comment Documentation https://tech.yandex.ru/pdd/doc/concepts/api-dns-docpage/ function get_sub_id domain ip token begin set base_params = dict string domain domain set r_id = list set dnsrequest ...
#!/usr/bin/env python2 import json import base64 from urllib import urlencode from urllib2 import urlopen, Request # Documentation https://tech.yandex.ru/pdd/doc/concepts/api-dns-docpage/ def get_sub_id(domain,ip,token): base_params = { 'domain': domain, } r_id = [] dnsrequest = Request("https...
Python
zaydzuhri_stack_edu_python
comment Import internal tools from logging import Logging comment Setup logger set log = call Logging class UpdateTool begin function __init__ self force lang media metadata url begin set date = none set force = force set genre_child = none set genre_parent = none set lang = lang set media = media set metadata = metada...
# Import internal tools from logging import Logging # Setup logger log = Logging() class UpdateTool: def __init__(self, force, lang, media, metadata, url): self.date = None self.force = force self.genre_child = None self.genre_parent = None self.lang = lang self.me...
Python
zaydzuhri_stack_edu_python
function __init__ self abscisse=0 ordonnee=0 begin set abscisse = abscisse set ordonnee = ordonnee end function
def __init__(self, abscisse = 0, ordonnee = 0): self.abscisse = abscisse self.ordonnee = ordonnee
Python
nomic_cornstack_python_v1
function get_output_files self action begin set method_mapping = dict string access _get_output_files_access ; string target _get_output_files_target ; string antitarget _get_output_files_antitarget ; string coverage _get_output_files_coverage ; string reference _get_output_files_reference ; string fix _get_output_file...
def get_output_files(self, action): method_mapping = { "access": self._get_output_files_access, "target": self._get_output_files_target, "antitarget": self._get_output_files_antitarget, "coverage": self._get_output_files_coverage, "reference": self._ge...
Python
nomic_cornstack_python_v1
function GetClassName self begin return string IntProperty2 end function
def GetClassName(self): return "IntProperty2"
Python
nomic_cornstack_python_v1
from PIL import Image import numpy as np function generate_map_with_path map_image output_image path_coordinates path_color begin string Creates an image file with the path drawn over the given path coordinates set im = open map_image set px = load im set tuple w h = size set pixels = list for x in range h begin appen...
from PIL import Image import numpy as np def generate_map_with_path(map_image, output_image, path_coordinates, path_color): '''Creates an image file with the path drawn over the given path coordinates''' im = Image.open(map_image) px = im.load() w, h = im.size pixels = [] for x...
Python
zaydzuhri_stack_edu_python
comment This code uses the random module import random comment Generate random number from 0 to 100 set randomNumber = random integer 0 100 comment Ask user to guess the number comment Keep guessing till user gets it right while true begin set userNumber = integer input string Guess the number: if userNumber == randomN...
# This code uses the random module import random # Generate random number from 0 to 100 randomNumber = random.randint(0, 100) # Ask user to guess the number # Keep guessing till user gets it right while True: userNumber = int(input("Guess the number: ")) if userNumber == randomNumber: print("Yo...
Python
jtatman_500k
function gather reference indices begin assert call ndim reference == 2 set indices = call Cast symbol dtype=dtype return call KerasSymbol call take symbol indices end function
def gather(reference, indices): assert ndim(reference) == 2 indices = mx.sym.Cast(indices.symbol, dtype=reference.dtype) return KerasSymbol(mx.sym.take(reference.symbol, indices))
Python
nomic_cornstack_python_v1
string https://leetcode.com/problems/count-good-numbers/ class Solution begin function countGoodNumbers self n begin set MOD = 10 ^ 9 + 7 set evenCounts = power 5 n - n ? 1 MOD set oddCounts = power 4 n ? 1 MOD return evenCounts * oddCounts % MOD end function end class
""" https://leetcode.com/problems/count-good-numbers/ """ class Solution: def countGoodNumbers(self, n: int) -> int: MOD = 10 ** 9 + 7 evenCounts = pow(5, n - (n >> 1), MOD) oddCounts = pow(4, n >> 1, MOD) return (evenCounts * oddCounts) % MOD
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data set mnist = call read_data_sets string MNIST_data/ one_hot=true set tuple trX trY teX teY = tuple images labels images labels class RBM begin function __init__ self input_size output_size begin set _input_size = input_...
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels class RBM: def __init__(self, input_size, output_s...
Python
zaydzuhri_stack_edu_python
comment ! cat input | python3 main.py import sys set n = integer input set a = list sorted map int split input set M = 10 ^ 9 + 7 set end = lambda x -> print x or exit set result = 1 set n2 = n % 2 if n2 == a at 0 % 2 begin call end 0 end set tmp = none if n2 begin if a at 0 begin call end 0 end end else if not a at 0 ...
#! cat input | python3 main.py import sys n = int(input()) a = list(sorted(map(int, input().split()))) M = 10**9 + 7 end = lambda x: print(x) or sys.exit() result = 1 n2 = n % 2 if n2 == a[0] % 2: end(0) tmp = None if n2: if a[0]: end(0) else: if not a[0] == a[1] == 1: end(0) for a1, a2 in...
Python
zaydzuhri_stack_edu_python
for i in range 2 n + 1 begin for j in range 2 i begin if i % j == 0 begin set k = k + 1 end end if k == 0 begin append prostye_chisla i end else begin set k = 0 end end print prostye_chisla
for i in range(2, n + 1): for j in range(2, i): if i % j == 0: k = k + 1 if k == 0: prostye_chisla.append(i) else: k = 0 print(prostye_chisla)
Python
zaydzuhri_stack_edu_python
function test_nonItem client begin set rv = get client string /items/name/Non existent assert status_code == 404 assert data in b'{"message": "Sorry, right now we are out of stock of the item Non existent comeback later and try again"}\n' end function
def test_nonItem(client): rv = client.get("/items/name/Non existent") assert rv.status_code == 404 assert ( rv.data in b'{"message": "Sorry, right now we are out of stock of the item Non existent comeback later and try again"}\n' )
Python
nomic_cornstack_python_v1
import settings import json import logging set logger = call getLogger string dictionary class Dictionary begin set CONST_SEARCH_EXACT = string EXACT set CONST_SEARCH_STARTS_WITH = string STARTS_WITH set CONST_SEARCH_CONTAINS = string CONTAINS set dictionary = none function __init__ self begin if call is_production beg...
import settings import json import logging logger = logging.getLogger('dictionary') class Dictionary(): CONST_SEARCH_EXACT = "EXACT" CONST_SEARCH_STARTS_WITH = "STARTS_WITH" CONST_SEARCH_CONTAINS = "CONTAINS" dictionary = None def __init__(self): if settings.is_production(): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf8 -*- string Created on 2018年2月1日 @author: root string import socket host,port = '192.168.20.232',18000 s = socket.socket() s.connect((host,port)) while 1: senddata = raw_input("please input data:") s.sendall(senddata) recvdata = s.recv(1024) print recvdata from socket...
#!/usr/bin/env python # -*- coding:utf8 -*- ''' Created on 2018年2月1日 @author: root ''' ''' import socket host,port = '192.168.20.232',18000 s = socket.socket() s.connect((host,port)) while 1: senddata = raw_input("please input data:") s.sendall(senddata) recvdata = s.recv(1024) print recvdata ''' ...
Python
zaydzuhri_stack_edu_python
function subject self begin return _subject end function
def subject(self): return self._subject
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn class RnnLayer extends Module begin function __init__ self input_dim output_dim begin call __init__ set output_dim = output_dim set input_dim = input_dim set inputLinear = linear input_dim output_dim bias=false set hiddenLinear = linear output_dim output_dim bias=true set activation =...
import torch import torch.nn as nn class RnnLayer(nn.Module): def __init__(self, input_dim, output_dim): super().__init__() self.output_dim = output_dim self.input_dim = input_dim self.inputLinear = nn.Linear(input_dim, output_dim, bias=False) self.hiddenLinear = nn.Line...
Python
zaydzuhri_stack_edu_python
function create_rng random_state begin if random_state is none begin return call RandomState 17 end else if is instance random_state int begin return call RandomState random_state end else if is instance random_state RandomState begin return random_state end else begin raise call TypeError string Must pass either a Non...
def create_rng(random_state): if random_state is None: return np.random.RandomState(17) elif isinstance(random_state, int): return np.random.RandomState(random_state) elif isinstance(random_state, np.random.RandomState): return random_state else: raise TypeError("Must pas...
Python
nomic_cornstack_python_v1
function most_eggs_in_pot n_eggs most_eggs most_grams begin set total_grams = 0 set total_eggs = 0 set ls_eggs = map int split call raw_input sort ls_eggs set i = 0 while i < n_eggs begin set cur_gram = pop ls_eggs 0 if total_grams + cur_gram > most_grams or total_eggs >= most_eggs begin break end set total_grams = tot...
def most_eggs_in_pot(n_eggs, most_eggs, most_grams): total_grams = 0 total_eggs = 0 ls_eggs = map(int, raw_input().split()) ls_eggs.sort() i = 0 while i < n_eggs : cur_gram = ls_eggs.pop(0) if total_grams+cur_gram > most_grams or \ total_eggs >= most_eggs: ...
Python
zaydzuhri_stack_edu_python
function override_value self name value special_type begin if value begin if special_type begin set value = call format_type value special_type end call set_by_namespace master_configuration name value end end function
def override_value(self, name, value, special_type): if value: if special_type: value = self.format_type(value, special_type) self.set_by_namespace(self.master_configuration, name, value)
Python
nomic_cornstack_python_v1
for i in range 0 10 begin if integer c at i < b begin append d c at i end end print join string d
for i in range(0,10): if int(c[i]) < b : d.append(c[i]) print(' '.join(d))
Python
zaydzuhri_stack_edu_python
class SimpleStringEncoder begin string To get random letters from the letters letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-_= " letters = list(letters) numpy.random.shuffle(letters) print(''.join(letters)) comment all the required letters in random order set letters = string _2F3x6RzZAByVq...
class SimpleStringEncoder: """To get random letters from the letters letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-_= " letters = list(letters) numpy.random.shuffle(letters) print(''.join(letters)) """ # all the required letters in random order ...
Python
zaydzuhri_stack_edu_python
function get self checklist_type begin comment validate_privilege(self, 'manage') set result = call get_questions checklist_type return tuple result 200 call security_headers end function
def get(self, checklist_type): #validate_privilege(self, 'manage') result = get_questions(checklist_type) return result, 200, security_headers()
Python
nomic_cornstack_python_v1
function __init__ self features labels raw_indices batch_size=50 seed=42 begin assert shape at 0 == shape at 0 msg string features.shape: %s labels.shape: %s % tuple shape shape set _num_examples = shape at 0 set _features = features set _labels = labels set _shuffled_features = copy np features set _shuffled_labels = ...
def __init__(self, features, labels, raw_indices, batch_size=50, seed=42): assert features.shape[0] == labels.shape[0], ( 'features.shape: %s labels.shape: %s' % (features.shape, labels.shape)) self._num_examples = ...
Python
nomic_cornstack_python_v1
function effects self raise_on_error=true begin string Parameters ---------- raise_on_error : bool, optional If exception is raised while determining effect of variant on a transcript, should it be raised? This default is True, meaning errors result in raised exceptions, otherwise they are only logged. return call Effe...
def effects(self, raise_on_error=True): """ Parameters ---------- raise_on_error : bool, optional If exception is raised while determining effect of variant on a transcript, should it be raised? This default is True, meaning errors result in raised exc...
Python
jtatman_500k
function _get_simplified_visible_line self plaza_geometry line tolerance begin set simplified_line = call simplify tolerance preserve_topology=false return if expression call line_visible plaza_geometry simplified_line visibility_delta_m then simplified_line else line end function
def _get_simplified_visible_line(self, plaza_geometry: Polygon, line: LineString, tolerance): simplified_line = line.simplify(tolerance, preserve_topology=False) return simplified_line if utils.line_visible(plaza_geometry, simplified_line, self.visibility_delta_m) else line
Python
nomic_cornstack_python_v1
function _configure_plugin self begin comment The execution setting. if string Execution in configuration begin set config at string execution = configuration at string Execution debug string Workflow %s execution parameters: %s. % tuple name config at string execution end comment The Nipype plug-in parameters. if plug...
def _configure_plugin(self): # The execution setting. if 'Execution' in self.configuration: self.workflow.config['execution'] = self.configuration['Execution'] self.logger.debug( "Workflow %s execution parameters: %s." % (self.workflow.name, self.w...
Python
nomic_cornstack_python_v1
function test_fma_nan_param_okarray_okarray_nanarray_okarray_b_0 self begin comment The expected results. set expected = list comprehension x * y + z for tuple x y z in zip okarrayx okarrayy nanarrayz comment Exceptions are turned off so we can use the results to test for correct values. call fma okarrayx okarrayy nana...
def test_fma_nan_param_okarray_okarray_nanarray_okarray_b_0(self): # The expected results. expected = [(x * y + z) for x,y,z in zip(self.okarrayx, self.okarrayy, self.nanarrayz)] # Exceptions are turned off so we can use the results to test for correct values. arrayfunc.fma(self.okarrayx, self.okarrayy, self.n...
Python
nomic_cornstack_python_v1
function to_dict self begin set result = dict for tuple attr _ in call iteritems swagger_types begin set value = get attribute self attr if is instance value list begin set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value end else if has attribute value ...
def to_dict(self): result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Python
nomic_cornstack_python_v1
function create_table self conn sql_query begin try begin set c = call cursor execute c sql_query end except Error as e begin error string %s e end end function
def create_table(self ,conn, sql_query): try: c = conn.cursor() c.execute(sql_query) except Error as e: self.logger.error("%s",e)
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[11]: set tuple x y = list comprehension integer i for i in split input set k = integer input set N = integer input set price = list for j in range N begin set tuple x_i y_i p_i = list comprehension integer i for i in split input set distance = x - x_i ^ 2 + y - y_i ^ 2 append price dic...
# coding: utf-8 # In[11]: x, y = [int(i) for i in input().split()] k = int(input()) N = int(input()) price = [] for j in range(N): x_i, y_i, p_i = [int(i) for i in input().split()] distance = (x - x_i)**2 + (y - y_i)**2 price.append({"x": x_i, "y": y_i, "p": p_i, "dis": distance}) price = sorted(pri...
Python
zaydzuhri_stack_edu_python
function e_im E begin set result = sum 1 / E * A * E_0 * G * E - E_g ^ 2 / E ^ 2 - E_0 ^ 2 ^ 2 + G ^ 2 * E ^ 2 axis=1 set out = where E at tuple slice : : 0 > E_g result 0 return out end function
def e_im(E): result = np.sum(1 / E * A * E_0 * G * (E - E_g)**2 / ((E**2 - E_0**2)**2 + G**2 * E**2), axis=1) out = np.where(E[:,0] > E_g, result, 0) return out
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 3/5/2018 1:49 PM comment @Author : sunyonghai comment @File : xml_utils.py comment @Software: ZJ_AI comment 此程序用于编辑xml文件 comment ========================================================= import random import xml.etree.ElementTree as ET from xml....
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 3/5/2018 1:49 PM # @Author : sunyonghai # @File : xml_utils.py # @Software: ZJ_AI #此程序用于编辑xml文件 # ========================================================= import random import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element import os im...
Python
jtatman_500k
function generate_frequency_table sequence begin set frequency_table = dict for char in sequence begin if char in frequency_table begin set frequency_table at char = frequency_table at char + 1 end else begin set frequency_table at char = 1 end end return frequency_table end function comment Example usage set sequence...
def generate_frequency_table(sequence): frequency_table = {} for char in sequence: if char in frequency_table: frequency_table[char] += 1 else: frequency_table[char] = 1 return frequency_table # Example usage sequence = "abcbab" frequency_table = generate_frequency_t...
Python
jtatman_500k
function GenomeLen begin global sep set genome = dict set samfile = call Samfile string /Users/ivang/Bioinformatics/Bioinformatics/express/Post-eXpress_Header_%s.sam % g string r set header = header at string SQ comment Iterate through the reference sequences in the header for i in header begin set genome at i at stri...
def GenomeLen(): global sep genome = {} samfile = pys.Samfile('/Users/ivang/Bioinformatics/Bioinformatics/express/Post-eXpress_Header_%s.sam' % args.g,'r') header = samfile.header['SQ'] # Iterate through the reference sequences in the header for i in header: genome[i['SN']] = np.zeros(np.floor(i['LN']/int...
Python
nomic_cornstack_python_v1
class Dice begin function __init__ self begin set number = list comprehension i for i in range 6 set work = list comprehension i for i in range 6 end function function setNumber self n0 n1 n2 n3 n4 n5 begin set number at 0 = n0 set number at 1 = n1 set number at 2 = n2 set number at 3 = n3 set number at 4 = n4 set numb...
class Dice(): def __init__(self): self.number = [i for i in range(6)] self.work = [i for i in range(6)] def setNumber(self, n0, n1, n2, n3, n4, n5): self.number[0] = n0 self.number[1] = n1 self.number[2] = n2 self.number[3] = n3 self.number[4] =...
Python
zaydzuhri_stack_edu_python
function test_plotting_peak_assignments begin comment First, generate a testing dataset. set hdf5_calfilename = string ramandecompy/tests/test_files/peakidentify_calibration_test.hdf5 set hdf5_expfilename = string ramandecompy/tests/test_files/peakidentify_experiment_test.hdf5 set key = string 300C/25s set calhdf5 = ca...
def test_plotting_peak_assignments(): #First, generate a testing dataset. hdf5_calfilename = 'ramandecompy/tests/test_files/peakidentify_calibration_test.hdf5' hdf5_expfilename = 'ramandecompy/tests/test_files/peakidentify_experiment_test.hdf5' key = '300C/25s' calhdf5 = h5py.File(hdf5_calfilename, ...
Python
nomic_cornstack_python_v1
string CSC263 Winter 2019 Problem Set 2, Question 3 Starter Code University of Toronto Mississauga comment Do NOT add any "import" statements class Node begin function __init__ self value begin set value = value set left = none set right = none set height = 1 set balance_factor = 0 set num_leaves = 1 set is_leaf = true...
''' CSC263 Winter 2019 Problem Set 2, Question 3 Starter Code University of Toronto Mississauga ''' # Do NOT add any "import" statements class Node: def __init__(self, value): self.value = value self.left = None self.right = None self.height = 1 self.balance_factor = 0 self.num_leaves = 1 ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt comment 解决中文乱码问题 set rcParams at string font.sans-serif = string SimHei set df_train = read csv string "D:\Software\Ubuntu\ubuntu_share\Experiment4\train_format1.csv" set df_test = read csv string "D:\Software\Ubuntu\ubuntu_share\Experiment4\test_fo...
import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams["font.sans-serif"] = "SimHei" #解决中文乱码问题 df_train = pd.read_csv(r'"D:\Software\Ubuntu\ubuntu_share\Experiment4\train_format1.csv"') df_test = pd.read_csv(r'"D:\Software\Ubuntu\ubuntu_share\Experiment4\test_format1.csv"') user_info = pd....
Python
zaydzuhri_stack_edu_python
comment converts set filesize = 1024 * 2 ^ 10 * 8 set bandwith = 1 * 2 ^ 20
#converts filesize = 1024 * (2** 10 *8) bandwith = 1 *(2 ** 20)
Python
zaydzuhri_stack_edu_python
import math , collections , sys set input = readline comment def check(a, val, finalRange): comment valrange = [0, 10**9] comment r = [0, 10**9] comment for i in range(1, len(a)): comment if a[i]!=-1 and a[i-1]!=-1: comment if abs(a[i]-a[i-1]) > val: comment return False comment if a[i] == -1: comment r = [max(a[i-1] -...
import math, collections, sys input = sys.stdin.readline # def check(a, val, finalRange): # valrange = [0, 10**9] # r = [0, 10**9] # for i in range(1, len(a)): # if a[i]!=-1 and a[i-1]!=-1: # if abs(a[i]-a[i-1]) > val: # return False # if a[i] == -1: # ...
Python
zaydzuhri_stack_edu_python
function has self obsclass begin return call __contains__ obsclass end function
def has(self, obsclass): return dict(self.__obsinfo).__contains__(obsclass)
Python
nomic_cornstack_python_v1
function update_client_url self begin set client = call authenticated_client_from_request _db if is instance client ProblemDetail begin return client end set url = get args string client_url if not url begin return call detailed string No 'client_url' provided end set url = call normalize_url unquote url return call ma...
def update_client_url(self): client = authenticated_client_from_request(self._db) if isinstance(client, ProblemDetail): return client url = request.args.get('client_url') if not url: return INVALID_INPUT.detailed("No 'client_url' provided") client.url = ...
Python
nomic_cornstack_python_v1
function make_workers_cfg trgt begin make directories join path string build string cfgworkers call cp string cfg/base.json join path string build string cfgworkers string base.json set template = read open join path string cfg string workers.json for worker in WORKERS_SRC begin set tuple path name = split path worker ...
def make_workers_cfg(trgt): trgt.makedirs(os.path.join('build', 'cfgworkers')) trgt.cp('cfg/base.json',os.path.join('build','cfgworkers','base.json')) template = open(os.path.join('cfg','workers.json')).read() for worker in WORKERS_SRC: (path, name) = os.path.split(worker) idf = name.re...
Python
nomic_cornstack_python_v1
function post self begin set result = dict string status string error set j = call get_json set seed_text = j at string seed_text set gen_chars = if expression string chars in j then j at string chars else DEFAULT_CHARS set generated_text = predict model_wrapper seed_text gen_chars set full_text = seed_text + generated...
def post(self): result = {'status': 'error'} j = request.get_json() seed_text = j['seed_text'] gen_chars = j['chars'] if 'chars' in j else DEFAULT_CHARS generated_text = self.model_wrapper.predict(seed_text, gen_chars) full_text = seed_text + generated_text model...
Python
nomic_cornstack_python_v1
from django.core.urlresolvers import reverse from django.test import TestCase from ticket.models import Ticket from rest_framework import status from rest_framework.test import APITestCase comment Create your tests here. function createTicket client begin set url = reverse string ticket-list set data = dict string requ...
from django.core.urlresolvers import reverse from django.test import TestCase from ticket.models import Ticket from rest_framework import status from rest_framework.test import APITestCase # Create your tests here. def createTicket(client): url = reverse('ticket-list') data = {'request': 'wat'} return clie...
Python
zaydzuhri_stack_edu_python
function age self begin set tdelta = now - created_timestamp comment enough to round it up to 2 years if days >= 548 begin return string about { days / 365 } years end else comment enough to round it up to 1 year (so it doesn't report '12 months') if days >= 345 begin return string about a year end else comment beyond ...
def age(self) -> str: tdelta = dt.now() - self.created_timestamp if tdelta.days >= 548: # enough to round it up to 2 years return f'about {tdelta.days/365:.0f} years' elif tdelta.days >= 345: # enough to round it up to 1 year (so it doesn't report '12 months') return f'...
Python
nomic_cornstack_python_v1
function unsetName self begin return call Port_unsetName self end function
def unsetName(self): return _libsbml.Port_unsetName(self)
Python
nomic_cornstack_python_v1
comment Menampilkan nilai rata rata dari 2 nilai terbesar pada list set x = list input set n = length x function rata2maks x begin if x at 0 > x at 1 begin set maks1 = x at 0 end else begin set maks1 = x at 1 end for i in range 2 n begin if x at i > maks1 begin set maks2 = maks1 set maks1 = x at i end else if x at i > ...
#Menampilkan nilai rata rata dari 2 nilai terbesar pada list x = list(input()) n = len(x) def rata2maks(x): if x[0] > x[1]: maks1 = x[0] else: maks1 = x[1] for i in range(2, n): if x[i] > maks1: maks2 = maks1 maks1 = x[i] elif x[i] > ma...
Python
zaydzuhri_stack_edu_python
comment USING THE VARIABLE PARAMETER FUNCTIONS, WE ACHIEVE 'OVERLOADING' comment Define a function with default parameters this returns nothing (None) function print_seperator char=string - repeat_count=40 begin print char * repeat_count end function function get_len s begin return length s end function function func_w...
# USING THE VARIABLE PARAMETER FUNCTIONS, WE ACHIEVE 'OVERLOADING' #Define a function with default parameters this returns nothing (None) def print_seperator(char = '-', repeat_count = 40) : print(char*repeat_count) def get_len(s): return len(s) def func_with_one_default_parameter(first, second = "Second") :...
Python
zaydzuhri_stack_edu_python
comment APP LEVEL ############### from django.shortcuts import render , HttpResponse , redirect from models import Roster , User function index request begin set context = dict string rosters all return call render request string roster_user_app/index.html context end function function users_page request begin set cont...
############ APP LEVEL ############### from django.shortcuts import render, HttpResponse, redirect from .models import Roster, User def index(request): context = { "rosters": Roster.objects.all(), } return render(request, "roster_user_app/index.html", context) def users_page(request): context...
Python
zaydzuhri_stack_edu_python
string 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为NULL 的节点将直接作为新二叉树的节点。 示例1: 输入: Tree 1 Tree 2 1 2 / \ / 3 2 1 3 / \ 5 4 7 输出: 合并后的树: 3 / 4 5 / \ 5 4 7 comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None,...
""" 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为NULL 的节点将直接作为新二叉树的节点。 示例1: 输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Apr 16 10:30:38 2020 @author: Rashmi import os import pandas as pd import numpy as np comment import h5py comment TODO: see if this file is needed from sklearn.preprocessing import OneHotEncoder , MinMaxScaler from sklearn.utils import shuffle function get_service_lis...
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 10:30:38 2020 @author: Rashmi """ import os import pandas as pd import numpy as np #import h5py #TODO: see if this file is needed from sklearn.preprocessing import OneHotEncoder, MinMaxScaler from sklearn.utils import shuffle def get_service_list(dirname = 'list', f...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Decrypt a single yaml variable fragment with ansible-vault. from ansible.parsing.dataloader import DataLoader from ansible.parsing.vault import ScriptVaultSecret from ansible.parsing.vault import VaultLib import sys import os import yaml set password_script_path = get current direct...
#!/usr/bin/env python # Decrypt a single yaml variable fragment with ansible-vault. from ansible.parsing.dataloader import DataLoader from ansible.parsing.vault import ScriptVaultSecret from ansible.parsing.vault import VaultLib import sys import os import yaml password_script_path = os.getcwd() + '/scripts/password...
Python
zaydzuhri_stack_edu_python
function main argv begin comment Setup Directory set experiment_dir = join path dir id if not exists path experiment_dir begin make directories join path experiment_dir string logs exist_ok=true end comment Setup Logging set alsologtostderr = true call use_absl_log_file logfile join path experiment_dir string logs comm...
def main(argv): # Setup Directory experiment_dir = os.path.join(FLAGS.dir, FLAGS.id) if not os.path.exists(experiment_dir): os.makedirs(os.path.join(experiment_dir, "logs"), exist_ok=True) # Setup Logging FLAGS.alsologtostderr = True logging.get_absl_handler().use_absl_log_fil...
Python
nomic_cornstack_python_v1
function timer func begin decorator wraps func function wrapper_timer *args **kwargs begin set start_time = performance counter set value = call func *args keyword kwargs set end_time = performance counter set run_time = end_time - start_time print string Finished { __name__ } in { run_time } secs return value end func...
def timer(func): @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() value = func(*args, **kwargs) end_time = time.perf_counter() run_time = end_time - start_time print(f"Finished {func.__name__!r} in {run_time:.4f} secs") ...
Python
nomic_cornstack_python_v1
import threading , os from Getch import Getch from ECAPServer import ECAPServer set ecapServer = call ECAPServer 6060 set connectionsThread = thread target=acceptConnections start connectionsThread print string ECAP Python Server Started. print string Please start typing or hit ESC to exit. set getch = call Getch while...
import threading, os from Getch import Getch from ECAPServer import ECAPServer ecapServer = ECAPServer(6060) connectionsThread = threading.Thread(target = ecapServer.acceptConnections) connectionsThread.start() print('ECAP Python Server Started.\r\n') print('Please start typing or hit ESC to exit.') getch = Getch(...
Python
zaydzuhri_stack_edu_python