code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
from sys import stdin set stdin = open string in.txt string r set input = readline set tuple N arr = tuple integer input list for n in range N begin set tuple t p = map int split strip input string append arr tuple t + n n + 1 p end sort arr key=lambda x -> tuple x at 0 - x at - 1 x at 1 set li = list 0 * N + 1 for a ...
from sys import stdin stdin = open('in.txt','r') input = stdin.readline N,arr = int(input()),[] for n in range(N): t,p = map(int,input().strip().split(' ')) arr.append((t+n,n+1,p)) arr.sort(key = lambda x:(x[0],-x[-1],x[1])) li = [0] * (N+1) for a in arr: e,s,p = a if e > N: continue else:...
Python
zaydzuhri_stack_edu_python
comment This is an a beginner level tutorial for those who want to get to know Flask comment Flask modules import .. jsonfiy will be user in later versions from flask import Flask , jsonify , request comment calling the flask constructor set api = call Flask __name__ decorator call route string / comment default entry ...
#This is an a beginner level tutorial for those who want to get to know Flask from flask import Flask, jsonify, request #Flask modules import .. jsonfiy will be user in later versions api = Flask(__name__) #calling the flask constructor @api.route('/') #default entry point to the API def testing_api(): ...
Python
zaydzuhri_stack_edu_python
function tp mc x y z begin set pos = list x y z set cur_pos = tuple call getPos for tuple i p in enumerate pos begin if p at 0 == string ~ begin set pos at i = cur_pos at i + decimal p at slice 1 : : or 0 end else begin set pos at i = decimal p end end call setPos *pos log string Set position to { tuple pos } end fun...
def tp(mc: MCP, x: str, y: str, z: str) -> None: pos = [x, y, z] cur_pos = tuple(mc.player.getPos()) for i, p in enumerate(pos): if p[0] == '~': pos[i] = cur_pos[i] + float(p[1:] or 0) else: pos[i] = float(p) mc.player.setPos(*pos) mc.log(f"Set position to {tuple(pos)}")
Python
nomic_cornstack_python_v1
function _compute_prior self hist_data=none begin function compute_prior_conversion hist_data begin string Summary Args: hist_data (TYPE): Description Returns: TYPE: Description comment Conversion is modelled as ~Bernoulli(lambda) with prior lambda ~Beta(alpha,beta) comment non-informative prior set alpha = 1 set beta ...
def _compute_prior(self,hist_data=None): def compute_prior_conversion(hist_data): """Summary Args: hist_data (TYPE): Description Returns: TYPE: Description """ #Conversion is modelled as ~Bernoulli(lambda) with prior lambda ~Beta(alpha,beta) #non-informativ...
Python
nomic_cornstack_python_v1
set answer = list 1 2 3 4 set s = string set eee = join s list map str answer print eee
answer=[1,2,3,4] s="\n" eee=s.join(list(map(str, answer))) print(eee)
Python
zaydzuhri_stack_edu_python
function __changeTextPosition self coordinate_tuple begin comment coordinate_tuple = (x,y) call fill bgcolor set textpos = call get_rect set x = coordinate_tuple at 0 set y = coordinate_tuple at 1 end function
def __changeTextPosition(self,coordinate_tuple): ## coordinate_tuple = (x,y) self.background.fill(self.bgcolor) self.textpos = self.text.get_rect() self.textpos.x = coordinate_tuple[0] self.textpos.y = coordinate_tuple[1]
Python
nomic_cornstack_python_v1
function conv2d_compute inputs weights bias outputs strides pad_list dilations kernel_name=string conv2d begin set shape_w = list for i in attrs at string ori_shape begin append shape_w value end set format_w = attrs at string ori_format if format_w == string NCHW begin set weight_h = shape_w at 2 set weight_w = shape...
def conv2d_compute(inputs, weights, bias, outputs, strides, pad_list, dilations, kernel_name="conv2d"): shape_w = [] for i in weights.op.attrs['ori_shape']: shape_w.append(i.value) format_w = weights.op.attrs['ori_format'] if format_w == "NCHW": weight_h = shape_w[2] ...
Python
nomic_cornstack_python_v1
import requests import os function test_sources_exists begin assert is file path string ./sources/analytic.tif end function function test_endpoint_vegetation_cover begin set url = string http://localhost:5000/vegetation-cover set resp = get requests url assert status_code == 200 assert json resp at string area == 12670...
import requests import os def test_sources_exists(): assert os.path.isfile("./sources/analytic.tif") def test_endpoint_vegetation_cover(): url = 'http://localhost:5000/vegetation-cover' resp = requests.get(url) assert resp.status_code == 200 assert resp.json()["area"] == 1267031.25 assert re...
Python
zaydzuhri_stack_edu_python
import sys import os
import sys import os
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import sys comment Print some introduction and instruction: print string This script was created using Python 3 + string 3.7.3 (default, Jan 22 2021, 20:04:44) [GCC 8.3.0] print format string Your version is {} version print string print string Here's how this is going...
import numpy as np import matplotlib.pyplot as plt import sys # Print some introduction and instruction: print("This script was created using Python 3 " + '3.7.3 (default, Jan 22 2021, 20:04:44) \n[GCC 8.3.0]') print("Your version is {}".format(sys.version)) print("\n\n") print("Here's how this is going to work. T...
Python
zaydzuhri_stack_edu_python
import turtle set wn = call Screen call bgcolor string lightgreen title wn string Square and Triangle set franklin = call Turtle call shape string turtle call color string blue call pensize 6 for i in list 0 1 2 3 begin call forward 150 call left 90 end call penup backward franklin 200 call pendown for f in list 0 1 2 ...
import turtle wn = turtle.Screen() wn.bgcolor('lightgreen') wn.title('Square and Triangle') franklin = turtle.Turtle() franklin.shape('turtle') franklin.color('blue') franklin.pensize(6) for i in [0,1,2,3]: franklin.forward(150) franklin.left(90) franklin.penup() franklin.backward(200) fran...
Python
zaydzuhri_stack_edu_python
comment To get this to work you will need to download python 3.x to your computer comment you will need to install it if you are on a pc - if win10 enable bash makes it easy comment I use Pycharm as my editor for python - free comment I use arvixe as a easy host for sql db - unlimted for 90 a year comment you can use p...
#To get this to work you will need to download python 3.x to your computer #you will need to install it if you are on a pc - if win10 enable bash makes it easy #I use Pycharm as my editor for python - free #I use arvixe as a easy host for sql db - unlimted for 90 a year #you can use pythonanywhere for this if you pay -...
Python
zaydzuhri_stack_edu_python
function filter_clusters cl_dict cl_residues cl_residues_probs min_clust_size begin comment gather clusters not respecting the minimum size set excl_clusts = list for cl in cl_residues begin if length cl_residues at cl < min_clust_size begin info string Cluster { cl } has less than { min_clust_size } residues. append ...
def filter_clusters(cl_dict, cl_residues, cl_residues_probs, min_clust_size): # gather clusters not respecting the minimum size excl_clusts = [] for cl in cl_residues: if len(cl_residues[cl]) < min_clust_size: log.info(f"Cluster {cl} has less than {min_clust_size} residues.") ...
Python
nomic_cornstack_python_v1
import pandas as pd class Conversion extends object begin decorator staticmethod function create_tuple begin return tuple 1 2 3 4 5 6 7 8 9 end function decorator staticmethod function tuple_to_list tp begin return list tp end function decorator staticmethod function int_to_float ls begin return list comprehension deci...
import pandas as pd class Conversion(object): @staticmethod def create_tuple() -> (): return (1,2,3,4,5,6,7,8,9) @staticmethod def tuple_to_list(tp) -> []: return list(tp) @staticmethod def int_to_float(ls) -> []: return [float(i) for i in ls] @staticmethod ...
Python
zaydzuhri_stack_edu_python
function mergeSorted self l1 l2 begin set tuple l1 l2 = tuple head head set prev = none set cur = none comment Runs only when both lists are not None while l1 and l2 begin comment If l1 is less than or equal to l2, create a new node with l1's data if data == data or data < data begin set newNode = call Node data set l1...
def mergeSorted(self,l1,l2): l1, l2 = l1.head, l2.head prev = cur = None # Runs only when both lists are not None while l1 and l2: # If l1 is less than or equal to l2, create a new node with l1's data if l1.data == l2.data or l1.data < l2.data: n...
Python
nomic_cornstack_python_v1
function get_to_persist persisters begin string Given a specification of what to persist, generates the corresponding set of components. function specs begin for p in persisters begin if is instance p dict begin yield tuple p at string name get p string enabled true end else begin yield tuple p true end end end functio...
def get_to_persist(persisters): """ Given a specification of what to persist, generates the corresponding set of components. """ def specs(): for p in persisters: if isinstance(p, dict): yield p["name"], p.get("enabled", True) else: yie...
Python
jtatman_500k
import json import requests function pueblos nombres begin set filename = string PueblosMagicosRes.txt comment Using the newer with construct to close the file automatically. with open filename as f begin set data = read lines f end for place in data begin append nombres right strip place end end function function api ...
import json import requests def pueblos(nombres): filename = 'PueblosMagicosRes.txt' # Using the newer with construct to close the file automatically. with open(filename) as f: data = f.readlines() for place in data: nombres.append(place.rstrip()) def api(): # Crea arreglo con ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from Bio import pairwise2 from Bio.pairwise2 import format_alignment function recuperer_fasta file begin string recuperer_fasta est une fonction qui permet de récuperer uniquement les séquences protéiques de la séquence cible ou de la séquence support, elle retourne une liste qui contient ...
# -*- coding: utf-8 -*- from Bio import pairwise2 from Bio.pairwise2 import format_alignment def recuperer_fasta(file): """ recuperer_fasta est une fonction qui permet de récuperer uniquement les séquences protéiques de la séquence cible ou de la séquence support, elle retourne une liste qui conti...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from codigo_avulso_test_tutorial.figura_geometrica import FiguraGeometrica class TestFiguraGeometrica extends TestCase begin function setUp self begin setup TestCase self set fig = call FiguraGeometrica end function function test_get_area self begin assert raises NotImplementedError get_ar...
from unittest import TestCase from codigo_avulso_test_tutorial.figura_geometrica import FiguraGeometrica class TestFiguraGeometrica(TestCase): def setUp(self): TestCase.setUp(self) self.fig = FiguraGeometrica() def test_get_area(self): self.assertRaises(NotImplementedError, self.fig.get_area) def t...
Python
zaydzuhri_stack_edu_python
import os import string comment from string import ascii_lowercaseas alphabet class WorkWithFiles begin function __init__ self dirname=string alphabet begin set _dirname = dirname call _create_dir end function function _create_dir self begin make directories _dirname exist_ok=true end function function _create_file sel...
import os import string # from string import ascii_lowercaseas alphabet class WorkWithFiles: def __init__(self, dirname ="alphabet"): self._dirname = dirname self._create_dir() def _create_dir(self): os.makedirs(self._dirname, exist_ok=True) def _create_file(self, symbol): ...
Python
zaydzuhri_stack_edu_python
function Rforce self R z phi=0.0 t=0.0 v=none begin string NAME: Rforce PURPOSE: evaluate cylindrical radial force F_R (R,z) INPUT: R - Cylindrical Galactocentric radius (can be Quantity) z - vertical height (can be Quantity) phi - azimuth (optional; can be Quantity) t - time (optional; can be Quantity) v - 3d velocity...
def Rforce(self,R,z,phi=0.,t=0.,v=None): """ NAME: Rforce PURPOSE: evaluate cylindrical radial force F_R (R,z) INPUT: R - Cylindrical Galactocentric radius (can be Quantity) z - vertical height (can be Quantity) phi - azimuth...
Python
jtatman_500k
function _is_valid_part self begin string Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean set comp_str = lower _encoded_value set part_rxc = compile _PART_PATTERN return match comp_str is not none end...
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re...
Python
jtatman_500k
function fit_standard_scaler_on_partitions partitions dataset_path begin comment Load or accumulate norms set norms = call load_scaler_norms dataset_path if norms is not none begin set tuple mean std = norms end else begin print string Computing Norms set count = 0 set total_sum = none set total_square_sum = none for p...
def fit_standard_scaler_on_partitions(partitions, dataset_path): # Load or accumulate norms norms = load_scaler_norms(dataset_path) if norms is not None: mean, std = norms else: print('Computing Norms') count = 0 total_sum = None total_square_sum = None f...
Python
nomic_cornstack_python_v1
import requests set response = get requests string https://www.google.com print text
import requests response = requests.get('https://www.google.com') print(response.text)
Python
flytech_python_25k
string Created on Nov 20, 2013 @author: excelsior import math from decimal import * comment Round of the decimal output to 16 decimal places set prec = 16 import logging , time call basicConfig level=INFO set logger = call getLogger __name__ string Build a TAN (Tree Augmented Network) bayesian model based on the traini...
''' Created on Nov 20, 2013 @author: excelsior ''' import math from decimal import * # Round of the decimal output to 16 decimal places getcontext().prec = 16 import logging, time logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ''' Build a TAN (Tree Augmented Network) bayesian mode...
Python
zaydzuhri_stack_edu_python
function x self begin return _x end function
def x(self): return self._x
Python
nomic_cornstack_python_v1
import conll import spacy import os import sys import map_spacy_conll as map import pandas as pd from spacy.tokens import Doc insert path 0 absolute path path string ../data/ function test_function begin set nlp = load spacy string en_core_web_sm comment read the corpus of the conll file set test_sents = call read_corp...
import conll import spacy import os import sys import map_spacy_conll as map import pandas as pd from spacy.tokens import Doc sys.path.insert(0, os.path.abspath('../data/')) def test_function(): nlp = spacy.load('en_core_web_sm') # read the corpus of the conll file test_sents = conll.read_corpus_conll('d...
Python
zaydzuhri_stack_edu_python
function weight_variable self shape begin set initial = call truncated_normal shape stddev=0.1 return call Variable initial end function
def weight_variable(self, shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
Python
nomic_cornstack_python_v1
import argparse set parser = call ArgumentParser description=string this is a description call add_argument string --ver string -v action=string store_true help=string hahaha comment 将变量以标签-值的字典形式存入args字典 set args = call parse_args if ver begin print string Ture end else begin print string False end comment python pars...
import argparse parser = argparse.ArgumentParser(description = 'this is a description') parser.add_argument('--ver', '-v', action = 'store_true', help = 'hahaha') # 将变量以标签-值的字典形式存入args字典 args = parser.parse_args() if args.ver: print("Ture") else: print("False") # python parser2.py --ver
Python
zaydzuhri_stack_edu_python
function save_to_file cls list_objs begin set filename = string __name__ + string .json with open filename mode=string w encoding=string utf-8 as a_file begin if list_objs is none begin set text = call to_json_string list end else begin set list_o_dict = list for i in list_objs begin append list_o_dict call to_diction...
def save_to_file(cls, list_objs): filename = str(cls.__name__) + ".json" with open(filename, mode="w", encoding='utf-8') as a_file: if list_objs is None: text = cls.to_json_string([]) else: list_o_dict = [] for i in list_objs: ...
Python
nomic_cornstack_python_v1
function curves self begin return _curves end function
def curves(self): return self._curves
Python
nomic_cornstack_python_v1
function _manage_an_error_or_warning_element self a_text a_dict a_element a_mode=none begin set l_element = none if a_mode begin set l_match_list = find all a_text if length l_match_list > 0 begin set l_element = l_match_list at 0 end end else begin set l_match_list = find all a_text if length l_match_list > 0 begin se...
def _manage_an_error_or_warning_element(self, a_text, a_dict, a_element, a_mode=None): l_element = None if a_mode: l_match_list = self._error_warning_regex[a_mode + "_" + a_element].findall(a_tex...
Python
nomic_cornstack_python_v1
function run_shell_cmd command begin try begin if not is instance command list begin set process = run split command stdout=PIPE return process end else begin set process = run command stdout=PIPE return process end end comment If package manager is missing except FileNotFoundError begin return none end end function
def run_shell_cmd(command): try: if not isinstance(command, list): process = sp.run(command.split(), stdout=sp.PIPE) return process else: process = sp.run(command, stdout=sp.PIPE) return process except FileNotFoundError: # If package manager is missing return None
Python
nomic_cornstack_python_v1
import sys function solve box toy begin if box == list or toy == list begin return 0 end else if box at 0 at 1 == toy at 0 at 1 begin if box at 0 at 0 == toy at 0 at 0 begin return box at 0 at 0 + call solve box at slice 1 : : toy at slice 1 : : end else if box at 0 at 0 > toy at 0 at 0 begin set box at 0 = tuple ...
import sys def solve(box,toy): if (box==[]) or (toy==[]): return 0 elif box[0][1] == toy[0][1]: if box[0][0] == toy[0][0]: return box[0][0] + solve(box[1:],toy[1:]) elif box[0][0] > toy[0][0]: box[0] = (box[0][0]-toy[0][0],toy[0][1]) return toy[0][0] ...
Python
zaydzuhri_stack_edu_python
comment Apriori comment Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd comment Data Preprocessing [§24 Lect162: "Apriori in Python - Step 1"] set dataset = read csv string data/s24_Market_Basket_Optimisation.csv header=none set transactions = list for i in range 0 7501 b...
# Apriori # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Data Preprocessing [§24 Lect162: "Apriori in Python - Step 1"] dataset = pd.read_csv('data/s24_Market_Basket_Optimisation.csv', header = None) transactions = [] for i in range(0, 7501): transactions.append...
Python
zaydzuhri_stack_edu_python
function coordinate_grid centre side_length boxsize n=70 begin set xstart = centre at 0 - 1.0 * side_length / 2.0 set ystart = centre at 1 - 1.0 * side_length / 2.0 set zstart = centre at 2 - 1.0 * side_length / 2.0 set xend = centre at 0 + 1.0 * side_length / 2.0 set yend = centre at 1 + 1.0 * side_length / 2.0 set ze...
def coordinate_grid(centre, side_length, boxsize, n=70): xstart = centre[0]-1.*side_length/2. ystart = centre[1]-1.*side_length/2. zstart = centre[2]-1.*side_length/2. xend = centre[0]+1.*side_length/2. yend = centre[1]+1.*side_length/2. zend = centre[2]+1.*side_length/2. coords = np.mgrid[x...
Python
nomic_cornstack_python_v1
from collections import defaultdict class Trie extends object begin function __init__ self begin set trie = default dictionary int end function function add self string begin for i in range 1 length string + 1 begin set trie at string at slice : i : = trie at string at slice : i : + 1 end end function function find...
from collections import defaultdict class Trie(object): def __init__(self): self.trie = defaultdict(int) def add(self, string): for i in range(1, len(string)+1): self.trie[string[:i]] += 1 def find(self, prefix): return self.trie[prefix] n = int(raw_input()) trie...
Python
zaydzuhri_stack_edu_python
import PyPDF2 comment open the pdf file set pdfFileObj = open string sample.pdf string rb comment create an object for pdf file set pdfReader = call PdfFileReader pdfFileObj comment get number of pages set numPages = numPages comment print no. of pages print string Number of pages: numPages comment define a counter set...
import PyPDF2 #open the pdf file pdfFileObj = open('sample.pdf', 'rb') #create an object for pdf file pdfReader = PyPDF2.PdfFileReader(pdfFileObj) #get number of pages numPages = pdfReader.numPages #print no. of pages print("Number of pages:", numPages) #define a counter count = 0 #while loop to read each page whil...
Python
jtatman_500k
function ws_collection connection begin call sendMessage call get_collection_json end function
def ws_collection(connection): connection.sendMessage(player.get_collection_json())
Python
nomic_cornstack_python_v1
function __call__ self path *args **kwargs begin if not call IsFileAccessible path begin raise call OSError EACCES string path not accessible path end return call _original_func path *args keyword kwargs end function
def __call__(self, path, *args, **kwargs): if not FakeFile.IsFileAccessible(path): raise OSError(errno.EACCES, 'path not accessible', path) return self._original_func(path, *args, **kwargs)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment teste.py comment Copyright 2019 Jack <Jack@DESKTOP-N9D1A4F> comment This program is free software; you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation; e...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # teste.py # # Copyright 2019 Jack <Jack@DESKTOP-N9D1A4F> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of ...
Python
zaydzuhri_stack_edu_python
string Любимый вариант очереди Тимофея — очередь, написанная с использованием связного списка. Помогите ему с реализацией. Очередь должна поддерживать выполнение трёх команд: get — вывести элемент в голове очереди и удалить его. Если очередь пуста, то вывести «error». put x — добавить число x в очередь size — вывести т...
""" Любимый вариант очереди Тимофея — очередь, написанная с использованием связного списка. Помогите ему с реализацией. Очередь должна поддерживать выполнение трёх команд: get — вывести элемент в голове очереди и удалить его. Если очередь пуста, то вывести «error». put x — добавить число x в очередь size — вывести теку...
Python
zaydzuhri_stack_edu_python
comment Author: Charse comment 装饰器 import time function timmer func begin function warpper *args **kwargs begin set start_time = time call func set stop_time = time print string the func run tim is %s % stop_time - start_time end function return warpper end function decorator timmer function test1 begin sleep 3 print s...
# Author: Charse # 装饰器 import time def timmer(func): def warpper(*args, **kwargs): start_time = time.time() func() stop_time = time.time() print('the func run tim is %s ' %(stop_time -start_time)) return warpper @timmer def test1(): time.sleep(3) print('in the test1') ...
Python
zaydzuhri_stack_edu_python
function _update_q_value self state action next_state reward begin set action_ix = action_index_map at action comment Compute Q-value for next state-action pair set next_action = call get_action next_state set next_action_ix = action_index_map at next_action set next_q_value = q at next_state at next_action_ix set td_e...
def _update_q_value(self, state, action, next_state, reward): action_ix = self.user.policy.action_index_map[action] # Compute Q-value for next state-action pair next_action = self.user.policy.get_action(next_state) next_action_ix = self.user.policy.action_index_map[next_action] ...
Python
nomic_cornstack_python_v1
comment https://www.hackerrank.com/challenges/queue-using-two-stacks/problem string A basic queue has the following operations: Enqueue: add a new element to the end of the queue. Dequeue: remove the element from the front of the queue and return it. In this challenge, you must first implement a queue using two stacks....
#https://www.hackerrank.com/challenges/queue-using-two-stacks/problem ''' A basic queue has the following operations: Enqueue: add a new element to the end of the queue. Dequeue: remove the element from the front of the queue and return it. In this challenge, you must first implement a queue using two stacks. Then pro...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Mar 2 23:49:42 2021 @author: SID import pandas as pd import numpy as np set df = read csv string BankNote_Authentication.csv print sum set X = iloc at tuple slice : : slice : - 1 : set Y = iloc at tuple slice : : - 1 from sklearn.model_selection import train_t...
# -*- coding: utf-8 -*- """ Created on Tue Mar 2 23:49:42 2021 @author: SID """ import pandas as pd import numpy as np df=pd.read_csv("BankNote_Authentication.csv") print(df.isnull().sum()) X=df.iloc[:,:-1] Y=df.iloc[:,-1] from sklearn.model_selection import train_test_split X_train,X_test,Y_trai...
Python
zaydzuhri_stack_edu_python
comment Построение модифицированного массива from prefix_border_array import prefix_border_array function prefix_border_arrayM S bp begin set n = length S set bpm = list 0 * n set bpm at n - 1 = bp at n - 1 comment Проверка совпадения следующих символов for i in range 1 n - 1 begin if bp at i != 0 and S at bp at i == S...
# Построение модифицированного массива from prefix_border_array import prefix_border_array def prefix_border_arrayM(S, bp): n = len(S) bpm = [0] * n bpm[n - 1] = bp[n - 1] for i in range(1, n - 1): # Проверка совпадения следующих символов if bp[i] != 0 and S[bp[i]] == S[i + 1]: bp...
Python
zaydzuhri_stack_edu_python
from region import LowBandRegion , MidBandRegion from unittest import TestCase class BandRegion extends TestCase begin function setUp self begin set lowreg = call LowBandRegion regions=list string 3 string 4 set midreg = call MidBandRegion regions=list string 3 string 4 return setup call super end function function tes...
from region import LowBandRegion, MidBandRegion from unittest import TestCase class BandRegion(TestCase): def setUp(self) -> None: self.lowreg = LowBandRegion(regions=['3', '4']) self.midreg = MidBandRegion(regions=['3', '4']) return super().setUp() def test_low_band_field_counts...
Python
zaydzuhri_stack_edu_python
function present self screen background_color foreground_color font frames_per_second begin set clock = call Clock set menu_choice = none while true begin call fill background_color call display_centered_text screen choice_text foreground_color font call flip for event in get event begin if type == KEYDOWN begin set me...
def present( self, screen, background_color, foreground_color, font, frames_per_second, ): clock = pygame.time.Clock() menu_choice = None while True: screen.fill(background_color) display_centere...
Python
nomic_cornstack_python_v1
function content_id self value begin set _content_id = value end function
def content_id(self, value): self._content_id = value
Python
nomic_cornstack_python_v1
function itkGrayscaleMorphologicalOpeningImageFilterID3ID3SE3_cast *args begin return call itkGrayscaleMorphologicalOpeningImageFilterID3ID3SE3_cast *args end function
def itkGrayscaleMorphologicalOpeningImageFilterID3ID3SE3_cast(*args): return _itkGrayscaleMorphologicalOpeningImageFilterPython.itkGrayscaleMorphologicalOpeningImageFilterID3ID3SE3_cast(*args)
Python
nomic_cornstack_python_v1
class Individu begin function __init__ self name firstname phone adress city begin set name = name set firstname = firstname set phone = phone set adress = adress set city = city end function function __str__ self begin return name + firstname + phone + adress + city end function end class
class Individu : def __init__(self,name, firstname,phone, adress, city): self.name = name self.firstname = firstname self.phone = phone self.adress = adress self.city = city def __str__(self): return (self.name + self.firstname + self.phone + self.adress + self.c...
Python
zaydzuhri_stack_edu_python
if v < 5 begin print string Less than 5 end else if v == 5 begin print string Equal to 5 end else begin print string Greater than 5 end
if v < 5: print("Less than 5") elif v==5: print("Equal to 5") else: print("Greater than 5")
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import random import re import copy comment hyper-parameters set exploration_factor = 1 set positions = dict 0 0 ; 1 1 ; 2 2 ; 3 3 ; 10 4 ; 11 5 ; 12 6 ; 13 7 ; 20 8 ; 21 9 ; 22 10 ; 23 11 ; 30 12 ; 31 13 ; 32 14 ; 33 15 class MCTS begin function __init__ self begin comment start dictionar...
import numpy as np from numpy import random import re import copy # hyper-parameters exploration_factor = 1 positions = {0: 0, 1: 1, 2: 2, 3: 3, 10: 4, 11: 5, 12: 6, 13: 7, 20: 8, 21: 9, 22: 10, 23: 11, 30: 12, 31: 13, 32: 14, 33: 15, } class MCTS: ...
Python
zaydzuhri_stack_edu_python
function sigmaHat self begin return call Sigma2ffbar2LEDUnparticlegamma_sigmaHat self end function
def sigmaHat(self): return _pythia8.Sigma2ffbar2LEDUnparticlegamma_sigmaHat(self)
Python
nomic_cornstack_python_v1
import time import wiringpi set HIGH = 1 set LOW = 0 set INPUT = 0 set OUTPUT = 1 set IN1_PIN = 1 set IN2_PIN = 4 set IN3_PIN = 5 set IN4_PIN = 6 set MAX_SPEED = 50 set AVG_SPEED = 30 set MIN_SPEED = 0 set GO_VALUE = tuple AVG_SPEED MIN_SPEED AVG_SPEED MIN_SPEED string GO set STOP_VALUE = tuple MIN_SPEED MIN_SPEED MIN_...
import time import wiringpi HIGH = 1 LOW = 0 INPUT = 0 OUTPUT =1 IN1_PIN = 1 IN2_PIN = 4 IN3_PIN = 5 IN4_PIN = 6 MAX_SPEED = 50 AVG_SPEED = 30 MIN_SPEED = 0 GO_VALUE = (AVG_SPEED, MIN_SPEED, AVG_SPEED, MIN_SPEED, 'GO') STOP_VALUE = (MIN_SPEED, MIN_SPEED, MIN_SPEED, MIN_SPEED, 'STOP') UTURN_VALUE = (AVG_SPEE...
Python
zaydzuhri_stack_edu_python
class LinkedList begin class Node begin function __init__ self data begin set data = data set next = none set prev = none end function function __str__ self begin return string [%s] % data end function end class function __init__ self begin set head = none set tail = none set size = 0 end function function __len__ self...
class LinkedList: class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def __str__(self): return '[%s]' % self.data def __init__(self): self.head = None self.tail = None self.size = 0 ...
Python
zaydzuhri_stack_edu_python
from tkinter import * import tkinter.messagebox set root = call Tk call showinfo string asdas string asdasdasdasdasd set answer = call askquestion string question string XX? print answer call showwarning string x string X call showerror string y string Y set ans = call askokcancel string Y string Y print ans set answ =...
from tkinter import * import tkinter.messagebox root=Tk() messagebox.showinfo('asdas','asdasdasdasdasd') answer = tkinter.messagebox.askquestion('question','XX?') print (answer) tkinter.messagebox.showwarning('x','X') tkinter.messagebox.showerror ('y','Y') ans=tkinter.messagebox.askokcancel('Y','Y') print(ans) an...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- set A = integer call raw_input string Introduce un numero entero= set B = A % 10
#!/usr/bin/env python # -*- coding: utf-8 -*- A=int(raw_input("Introduce un numero entero=")) B=A%10
Python
zaydzuhri_stack_edu_python
function _parse_date date_string date_type begin comment If date_string is None return None if date_string is none begin return none end else comment Parse rfc3339 dates from string if date_type == string rfc3339 begin if date_string at - 3 == string : begin set date_string = date_string at slice : - 3 : + date_strin...
def _parse_date(date_string, date_type): # If date_string is None return None if date_string is None: return None # Parse rfc3339 dates from string elif date_type == "rfc3339": if date_string[-3] == ":": date_string = date_string[:-3] + date_strin...
Python
nomic_cornstack_python_v1
comment func_example_003_uses_a_module.py comment This module contains re-usable functions import func_example_003_main_module print string Area of the rectangle using imported module is call area_of_rectangle 100 20
# func_example_003_uses_a_module.py # This module contains re-usable functions # import func_example_003_main_module print ("Area of the rectangle using imported module is ", func_example_003_main_module.area_of_rectangle (100,20))
Python
zaydzuhri_stack_edu_python
function bar self x y z size=10000.0 color=none bottom=0.0 begin set x = call validate_listlike x key=string x comment for list validation (not allow scalar) set y = call validate_listlike y key=string y comment for length validation set y = call _fill_by y length x key=string y comment z must be a list set z = call va...
def bar(self, x, y, z, size=10e3, color=None, bottom=0.): x = com.validate_listlike(x, key='x') # for list validation (not allow scalar) y = com.validate_listlike(y, key='y') # for length validation y = self._fill_by(y, len(x), key='y') # z must be a list z = co...
Python
nomic_cornstack_python_v1
string 팩토리얼 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 256 MB 9483 5850 5138 62.423% 문제 0보다 크거나 같은 정수 N이 주어진다. 이때, N!을 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 정수 N(0 ≤ N ≤ 12)가 주어진다. 출력 첫째 줄에 N!을 출력한다. 예제 입력 1 10 예제 출력 1 3628800 set n = integer input set ret = 1 for i in range 1 n + 1 begin set ret = ret * i end print ret
""" 팩토리얼 시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 1 초 256 MB 9483 5850 5138 62.423% 문제 0보다 크거나 같은 정수 N이 주어진다. 이때, N!을 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 정수 N(0 ≤ N ≤ 12)가 주어진다. 출력 첫째 줄에 N!을 출력한다. 예제 입력 1 10 예제 출력 1 3628800 """ n = int(input()) ret = 1 for i in range(1, n + 1): ret *= i print(ret)
Python
zaydzuhri_stack_edu_python
function pull_notifications self ev begin set notifications = call get_response_from_configurator _conf if not is instance notifications list begin set message = string Notfications not list, %s % notifications error message end else begin for notification in notifications begin if not notification begin set message = ...
def pull_notifications(self, ev): notifications = transport.get_response_from_configurator(self._conf) if not isinstance(notifications, list): message = "Notfications not list, %s" % (notifications) LOG.error(message) else: for notification in notifications:...
Python
nomic_cornstack_python_v1
async function disable self ctx begin if not settings at id at string disabled begin set settings at id at string disabled = true call save_settings await call say string Logging system has been disabled. end else begin set settings at id at string disabled = false call save_settings await call say string Logging syste...
async def disable(self, ctx): if not self.settings[ctx.message.server.id]['disabled']: self.settings[ctx.message.server.id]['disabled'] = True self.save_settings() await self.bot.say("Logging system has been disabled.") else: self.settings[ctx.messag...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Jul 20 11:26:42 2021 @author: Nilesh function selection_sort a begin set min_index = 0 for i in range length a begin set min_index = i set num = a at i for j in range i length a begin if a at j < a at min_index begin set min_index = j set min_num = a at min_index end ...
# -*- coding: utf-8 -*- """ Created on Tue Jul 20 11:26:42 2021 @author: Nilesh """ def selection_sort(a): min_index = 0 for i in range(len(a)): min_index = i num = a[i] for j in range(i, len(a)): if a[j] < a[min_index]: min_index = j ...
Python
zaydzuhri_stack_edu_python
function __init__ self value decay_steps decay_rate staircase=false begin set _value = value set _decay_steps = decay_steps set _decay_rate = decay_rate set _staircase = staircase end function
def __init__(self, value, decay_steps, decay_rate, staircase=False): self._value = value self._decay_steps = decay_steps self._decay_rate = decay_rate self._staircase = staircase
Python
nomic_cornstack_python_v1
function Lobulation self begin set s = lobulation assert s in range 1 6 msg string Lobulation score out of bounds. if s == 1 begin return string No Lobulation end else if s == 2 begin return string Nearly No Lobulation end else if s == 3 begin return string Medium Lobulation end else if s == 4 begin return string Near ...
def Lobulation(self): s = self.lobulation assert s in range(1,6), "Lobulation score out of bounds." if s == 1: return 'No Lobulation' elif s == 2: return 'Nearly No Lobulation' elif s == 3: return 'Medium Lobulation' elif s == 4: return 'Near Marked Lobulation' ...
Python
nomic_cornstack_python_v1
function handle self *args **options begin print string GLOVAL VARIABLES ARE IN THE FILE __file__ print string REMEMBER TO REPLACE THE GLOBAL VARIABLES ABOVE print string THE FIRST TIME YOU RUN THIS IT SHOULD GO REALLY QUICKLY, AS YOU ARE JUST TESTING comment get rid of this dumb line when you've replaced the variables...
def handle(self, *args, **options): print ("GLOVAL VARIABLES ARE IN THE FILE", __file__) print ("REMEMBER TO REPLACE THE GLOBAL VARIABLES ABOVE") print ("THE FIRST TIME YOU RUN THIS IT SHOULD GO REALLY QUICKLY, AS YOU ARE JUST TESTING") # get rid of this dumb line when you've replace...
Python
nomic_cornstack_python_v1
function minimum_iso_value self minimum_iso_value begin set _minimum_iso_value = minimum_iso_value end function
def minimum_iso_value(self, minimum_iso_value): self._minimum_iso_value = minimum_iso_value
Python
nomic_cornstack_python_v1
from worldsim import WorldSim from worldsim.agents import RandomAgent from worldsim.tasks import SearchTask from worldsim.experiments import reward_plot set EPISODES = 100 function main begin set task = call SearchTask 5.0 5.0 set world = call WorldSim 10.0 10.0 0 0 task set agent = call RandomAgent world task set agen...
from worldsim import WorldSim from worldsim.agents import RandomAgent from worldsim.tasks import SearchTask from worldsim.experiments import reward_plot EPISODES = 100 def main(): task = SearchTask(5.0, 5.0) world = WorldSim(10.0, 10.0, 0, 0, task) agent = RandomAgent(world, task) world.agent = agent...
Python
zaydzuhri_stack_edu_python
function close self begin set in_scope = call defined_names set all_scope = call defined_names tree=true for name in all_scope begin if name not in in_scope begin call define name call lookup name end end end function
def close(self): in_scope = self.defined_names() all_scope = self.defined_names(tree=True) for name in all_scope: if name not in in_scope: self.define(name, self.lookup(name))
Python
nomic_cornstack_python_v1
function add_annotations annot_tuples ref_data annot_type begin for annot in call select_type annot_type begin set tuple annot_begin annot_end = spans at 0 append annot_tuples tuple annot_begin annot_end id end end function
def add_annotations(annot_tuples, ref_data, annot_type): for annot in ref_data.annotations.select_type(annot_type): annot_begin, annot_end = annot.spans[0] annot_tuples.append((annot_begin, annot_end, annot.id))
Python
nomic_cornstack_python_v1
comment Grinberg's unit tests, we can del if need be - Sarvar function test begin import unittest set tests = call discover string tests run tests end function
def test(): # Grinberg's unit tests, we can del if need be - Sarvar import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
Python
nomic_cornstack_python_v1
function open_spider self spider begin set now = call get_now_time comment Create initial batch set batch = call create kickoff_time=now finish_time=now save comment save initial site list set file_content = call ContentFile join string start_urls set filename = replace string batch string string save filename file_c...
def open_spider(self, spider): now = spider.get_now_time() # Create initial batch spider.batch = model.Batch.objects.create( kickoff_time=now, finish_time=now) spider.batch.save() # save initial site list file_content = ContentFile('\n'.join(spider.start_url...
Python
nomic_cornstack_python_v1
import socket from hmac_security import HMAC string This class handles the main information exchange between client and server. Every transaction must attached with it a header, consist of the common hmac_package key, encripted SHA-256 to verify integrity of the data. Any data which fails to comply will be rejected, so...
import socket from hmac_security import HMAC ''' This class handles the main information exchange between client and server. Every transaction must attached with it a header, consist of the common hmac_package key, encripted SHA-256 to verify integrity of the data. Any data which fails to comply will be rejected, sock...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Feb 19 21:58:28 2018 @author: Ben Brock and Shazia Zaman from Deck import Deck from Player import Player from PokerGameTheoryStrategy import PokerGameTheoryStrategy from PokerHandUtility import PokerHandUtility import sys set debug = 0 string Starting Boilerplate for ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 19 21:58:28 2018 @author: Ben Brock and Shazia Zaman """ from Deck import Deck from Player import Player from PokerGameTheoryStrategy import PokerGameTheoryStrategy from PokerHandUtility import PokerHandUtility import sys debug = 0 ''' Starting Boilerplate for the Poke...
Python
zaydzuhri_stack_edu_python
function evaluate_list molecules ensemble_lookup options begin string Evaluate a list of ensembles and return statistics and ROC plots if appropriate comment create stats dictionaries to store results from each ensemble comment {file name : metric_List} set stats = dict comment print progress messages if write_roc beg...
def evaluate_list(molecules, ensemble_lookup, options): """ Evaluate a list of ensembles and return statistics and ROC plots if appropriate """ # create stats dictionaries to store results from each ensemble stats = {} # {file name : metric_List} # print progress messages if options.write...
Python
jtatman_500k
function sr_copy begin set req_data = call get_json debug string req_data = + string req_data set product_name = req_data at string product_name set version_number = req_data at string version_number set version_number_new = req_data at string version_number_new set outcome = dict string name string Fail try begin comm...
def sr_copy(): req_data = request.get_json() logging.debug("req_data = " + str(req_data)) product_name = req_data['product_name'] version_number = req_data['version_number'] version_number_new = req_data['version_number_new'] outcome = {"name": "Fail"} try: # create new associatio...
Python
nomic_cornstack_python_v1
function maximum_cut g begin comment 1. Randomly pick a vertex to split the set into two lists. set vertices = call get_vertices set split_point = random integer 0 length vertices - 1 set left = vertices at slice : split_point : set right = vertices at slice split_point : : comment 2. Start searching for a better s...
def maximum_cut(g): # 1. Randomly pick a vertex to split the set into two lists. vertices = g.get_vertices() split_point = random.randint(0, len(vertices)-1) left = vertices[:split_point] right = vertices[split_point:] # 2. Start searching for a better solution using local search. while Tru...
Python
nomic_cornstack_python_v1
function text_indentation text begin if type text != str or text is none begin raise call TypeError string text must be a string end set sw = 0 for i in text begin if i in list string . string ? string : begin print i end=string set sw = 1 end else if sw == 0 begin print i end=string end else if i == string begin pass...
def text_indentation(text): if type(text) != str or text is None: raise TypeError("text must be a string") sw = 0 for i in text: if i in [".", "?", ":"]: print(i, end="\n\n") sw = 1 else: if sw == 0: print(i, end="") els...
Python
nomic_cornstack_python_v1
function test_failed_suggestion_protocol self begin with call runtime_values verbose=false host=string foo.co begin with call object Session string request as req begin set side_effect = SSLError with call object click string secho as secho begin with assert raises ConnectionError begin get client string /ping/ end cal...
def test_failed_suggestion_protocol(self): with settings.runtime_values(verbose=False, host='foo.co'): with mock.patch.object(Session, 'request') as req: req.side_effect = requests.exceptions.SSLError with mock.patch.object(click, 'secho') as secho: ...
Python
nomic_cornstack_python_v1
function live_active_campaigns self live_active_campaigns begin comment noqa: E501 if client_side_validation and live_active_campaigns is none begin comment noqa: E501 raise call ValueError string Invalid value for `live_active_campaigns`, must not be `None` end set _live_active_campaigns = live_active_campaigns end fu...
def live_active_campaigns(self, live_active_campaigns): if self.local_vars_configuration.client_side_validation and live_active_campaigns is None: # noqa: E501 raise ValueError("Invalid value for `live_active_campaigns`, must not be `None`") # noqa: E501 self._live_active_campaigns = live...
Python
nomic_cornstack_python_v1
string Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Have you met this question in a real interview? Yes Example Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5].
''' Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Have you met this question in a real interview? Yes Example Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. '''
Python
zaydzuhri_stack_edu_python
function get_all_data file_names directory=join path get current directory string data/raw/ begin set logger = call getLogger __name__ set paths_to_data = list comprehension join path directory file_names at key for key in file_names set data = list set ioerror_files = list for tuple file_path name in zip paths_to_da...
def get_all_data(file_names, directory=os.path.join(os.getcwd(), "data/raw/") ): logger = logging.getLogger(__name__) paths_to_data = [os.path.join(directory, file_names[key]) for key in file_names] data = [] ioerror_files = [] for file_path, name in zip(paths_to...
Python
nomic_cornstack_python_v1
function countdown n begin string >>> countdown(3) 3 2 1 if n == 1 begin print 1 end else begin print n call countdown n - 1 end end function function countup n begin string >>> countup(3) 1 2 3 if n == 1 begin print 1 end else begin call countup n - 1 print n end end function function expt base power begin string >>> ...
def countdown(n): """ >>> countdown(3) 3 2 1 """ if n == 1: print(1) else: print(n) countdown(n - 1) def countup(n): """ >>> countup(3) 1 2 3 """ if n == 1: print(1) else: countup(n - 1) print(n) def expt...
Python
zaydzuhri_stack_edu_python
function iter self begin raise NotImplementedError end function
def iter(self) -> Generator[Any, None, None]: raise NotImplementedError
Python
nomic_cornstack_python_v1
function add_command self more_command_list begin print string adding { more_command_list } comment perhaps was here to reinit to zero length ?? for now a do nothing if more_command_list is none begin pass end else begin comment self.command_list = more_command_list # [ r"D:\apps\Notepad++\notepad++.exe", r"gedit", r"x...
def add_command( self, more_command_list ): print( f"adding {more_command_list}") if more_command_list is None: # perhaps was here to reinit to zero length ?? for now a do nothing pass #self.command_list = more_command_list # [ r"D:\apps\Notepad++\notepad++.exe", r...
Python
nomic_cornstack_python_v1
function MergeData self SunsPLDataListLO SunsPLDataListHI index begin set highestSunsLO = effSuns at 4 set dSuns = list for i in range length effSuns begin append dSuns absolute effSuns at i - highestSunsLO end set indSuns = index dSuns min dSuns set time = concatenate tuple raw at string t at slice 0 : indSuns : raw...
def MergeData(self, SunsPLDataListLO, SunsPLDataListHI, index): highestSunsLO = SunsPLDataListLO[0].effSuns[4] dSuns = [] for i in range(len(SunsPLDataListHI[0].effSuns)): dSuns.append(abs(SunsPLDataListHI[0].effSuns[i] - highestSunsLO)) indSuns = dSuns.index(min(dSuns...
Python
nomic_cornstack_python_v1
function running self begin return _running end function
def running(self): return self._running
Python
nomic_cornstack_python_v1
function end self begin return _end end function
def end(self) -> datetime: return self._end
Python
nomic_cornstack_python_v1
function meshgridn E begin comment Check inputs if not is instance E tuple list ndarray begin raise call TypeError string E must be a list of grid edges in each dim end comment Base case: 1D if length E == 1 begin return reshape E at 0 - 1 1 end else begin comment Multidim set gridn1 = call tile call meshgridn E at sli...
def meshgridn(E): # Check inputs if not isinstance(E, (list, np.ndarray)): raise TypeError('E must be a list of grid edges in each dim') # Base case: 1D if len(E) == 1: return E[0].reshape(-1, 1) # Multidim else: gridn1 = np.tile(meshgridn(E[1:]), (len(E[0]), 1)) ...
Python
nomic_cornstack_python_v1
import os , glob import numpy as np import matplotlib.pyplot as plt import cv2 as cv from skimage import io from skimage.measure import compare_ssim get current directory set img_list = list for img in glob glob string /........./*.JPG begin set test_image = call imread img print img append img_list test_image end set...
import os,glob import numpy as np import matplotlib.pyplot as plt import cv2 as cv from skimage import io from skimage.measure import compare_ssim os.getcwd() img_list = [] for img in glob.glob('/........./*.JPG'): test_image = cv.imread(img) print(img) img_list.append(test_image) template_data=[] for my...
Python
zaydzuhri_stack_edu_python
function draw self surf camera begin comment dead men tell no tales if call is_dead begin return end comment create temporary list to protect the current position set temp_rect = apply camera current_pos comment converts from world coord to screen coords set temp_cube = call Cuboid call Vector3 0 0 0 copy mPos call Vec...
def draw(self, surf, camera): if self.is_dead(): # dead men tell no tales return temp_rect = camera.apply(self.current_pos) # create temporary list to protect the current position # converts from world coord to screen coords temp_cube = Cuboid(vector.Vector3(0, 0, 0), se...
Python
nomic_cornstack_python_v1
function __setattr__ self *args **kwargs begin Ellipsis end function
def __setattr__(self, *args, **kwargs): ...
Python
nomic_cornstack_python_v1
function dgTimerOff self begin pass end function
def dgTimerOff(self): pass
Python
nomic_cornstack_python_v1
function addIptablesBlockRule set_list_name begin set result = read stdout for line in split strip result string begin if line == set_list_name begin return end end set result = read stdout if strip result != string begin error string Could not block ipset %s. Error: %s. % tuple set_list_name result end end function
def addIptablesBlockRule(set_list_name): result = subprocess.Popen("/sbin/iptables -L | grep 'match-set' | awk '{print $7}' 2>&1", shell=True, stdout=subprocess.PIPE).stdout.read() for line in result.strip().split('\n'): if line == set_list_name: return result = subprocess.Popen("/sbin/i...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import smtplib , json from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage function uploadPicture path id_name begin comment 指定图片为当前目录 set fp = open path string rb set msgImage = call MIMEImag...
#!/usr/bin/python3 import smtplib,json from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage def uploadPicture(path,id_name): # 指定图片为当前目录 fp = open(path, 'rb') msgImage = MIMEImage(fp.read()) fp.close()...
Python
zaydzuhri_stack_edu_python
comment Use the pandas module to answer the following questions about the EPA-HTTP data set. comment Print the result of each part to the console. Use pandas as much as you can; comment this includes the data structure and the analysis. comment Use any other tools or techniques you need to create an efficient program. ...
#Use the pandas module to answer the following questions about the EPA-HTTP data set. #Print the result of each part to the console. Use pandas as much as you can; #this includes the data structure and the analysis. #Use any other tools or techniques you need to create an efficient program. #These include scipy, numpy...
Python
zaydzuhri_stack_edu_python
string based on riplpox import logging from copy import copy from Dijkstras import dijkstraHelperFunction from Hashed import HashHelperFunction class Routing extends object begin string Base class for data center network routing. Routing engines must implement the get_route() method. function __init__ self topo begin s...
''' based on riplpox ''' import logging from copy import copy from Dijkstras import dijkstraHelperFunction from Hashed import HashHelperFunction class Routing(object): '''Base class for data center network routing. Routing engines must implement the get_route() method. ''' def __init__(self, topo...
Python
zaydzuhri_stack_edu_python