code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class String begin function __init__ self string begin set string = string end function function replace_odd_occurrences self substring replace_with begin set count = count string substring if count % 2 == 0 or count == 0 begin return string end set result = string set stack = list for i in range length string begin ...
class String: def __init__(self, string): self.string = string def replace_odd_occurrences(self, substring, replace_with): count = self.string.count(substring) if count % 2 == 0 or count == 0: return self.string result = "" stack = [] for i in range...
Python
greatdarklord_python_dataset
comment !/usr/bin/python3 import sys import os import re import colorsys set HEX_COLOR_REGEX = string #([A-Fa-f0-9]{6}) set RGB_COLOR_REGEX = string rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\) comment Greens are between these hue values: set MIN_HUE = 57 set MAX_HUE = 180 set hex_colors = dict set rgb_col...
#!/usr/bin/python3 import sys import os import re import colorsys HEX_COLOR_REGEX = r'#([A-Fa-f0-9]{6})' RGB_COLOR_REGEX = r'rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)' # Greens are between these hue values: MIN_HUE = 57 MAX_HUE = 180 hex_colors = {} rgb_colors = {} IGNORED_COLORS = [] IGNORED_COLORS.a...
Python
zaydzuhri_stack_edu_python
import pygame , wx from pygame.locals import * from wx import * call init function main begin set white = tuple 255 255 255 set black = tuple 0 0 0 set savenumber = 1 set red = tuple 255 0 0 set green = tuple 0 255 0 set blue = tuple 0 0 255 set userColor = tuple 0 0 0 set go = true set draw = false set erase = false s...
import pygame, wx from pygame.locals import * from wx import * pygame.init() def main(): white = (255,255,255) black = (0,0,0) savenumber = 1 red = (255,0,0) green = (0,255,0) blue = (0,0,255) userColor = (0,0,0) go = True draw = False erase = False radius = 25 color = black (rx,ry) = (0,25) (gx,gy) = (0...
Python
zaydzuhri_stack_edu_python
function setMaxOutputLength self value begin return call _set maxOutputLength=value end function
def setMaxOutputLength(self, value): return self._set(maxOutputLength=value)
Python
nomic_cornstack_python_v1
comment Here's a generator that produces a range of floating-point numbers: function frange start stop increment begin set x = start while x < stop begin yield x set x = x + increment end end function comment To use such a function, you iterate over it using a for loop or use it with some other function that consumes a...
# Here's a generator that produces a range of floating-point numbers: def frange(start, stop, increment): x = start while x < stop: yield x x += increment # To use such a function, you iterate over it using a for loop or use it with some other function that consumes an # iterable (e.g., sum(),...
Python
zaydzuhri_stack_edu_python
function excluded_folder folder=none begin if not folder begin return true end if ends with folder string __pycache__ begin return true end if ends with folder string \.git begin return true end if string \.git\ in folder begin return true end if string \$RECYCLE.BIN\ in folder begin return true end if starts with lowe...
def excluded_folder(folder=None): if not folder: return True if folder.endswith("__pycache__"): return True if folder.endswith("\\.git"): return True if "\\.git\\" in folder: return True if "\\$RECYCLE.BIN\\" in folder: return True if folder.lower().start...
Python
nomic_cornstack_python_v1
import numpy as np import string set data_path = string ../word_data/ set out_path = string ../word_data/ function input1 f begin set train = load np data_path + f set keys = list keys train set values = list comprehension train at key for key in keys save out_path + string input1.npy values end function function input...
import numpy as np import string data_path = "../word_data/" out_path = "../word_data/" def input1(f): train = np.load(data_path + f) keys = list(train.keys()) values = [train[key] for key in keys] np.save(out_path + "input1.npy", values) def input2(f): train = np.load(data_p...
Python
zaydzuhri_stack_edu_python
class DicomConfiguration extends object begin function __init__ self name=string Kamil Plucisnki id=string 132307 destination=string none file_name=string test begin string :param name: :param id: :param destination: :param file_name: call __init__ set name = name set id = id set destination = destination set file_name...
class DicomConfiguration(object): def __init__(self, name: str = 'Kamil Plucisnki', id: str = '132307', destination: str = 'none', file_name: str = 'test'): """ :param name: :param id: :param destination: :param file_name: """ super(DicomConfi...
Python
zaydzuhri_stack_edu_python
import numpy as np set S = integer input set memo = ones S + 1 * - 1 function dp i begin comment print("i = {}".format(i)) if memo at i != - 1 begin set res = memo at i end else if i == 0 or i == 1 or i == 2 begin set res = 0 end else if i == 3 begin set res = 1 end else begin set sum = 1 for j in range i - 1 2 - 1 beg...
import numpy as np S = int(input()) memo = np.ones(S + 1) * -1 def dp(i): # print("i = {}".format(i)) if memo[i] != -1: res = memo[i] elif i == 0 or i == 1 or i == 2: res = 0 elif i == 3: res = 1 else: sum = 1 for j in range(i - 1, 2, -1): # if i...
Python
zaydzuhri_stack_edu_python
import sys , os , os.path , re , itertools set config = dict exec read open string quicktikz.conf config set codes = list class Node begin function __init__ self text begin set text = strip split text string : at - 1 set code = call makeCode text set type = get config at string types split text string : at 0 string b...
import sys, os, os.path, re, itertools config = {} exec(open("quicktikz.conf").read(), config) codes = [] class Node(): def __init__(self, text): self.text = text.split(':')[-1].strip() self.code = self.makeCode(self.text) self.type = config['types'].get(text.split(':')[0], 'block') def makeCode(...
Python
zaydzuhri_stack_edu_python
function _load_images begin set image_descriptions = call _load_file _SOURCE_CODE_ROOT / string test_suites / string images.yml if string images not in image_descriptions begin raise exception string images.yml is missing the 'images' item end set images = dict comment first load the images as 1-item lists for tuple n...
def _load_images() -> Dict[str, List[VmImageInfo]]: image_descriptions = AgentTestLoader._load_file(AgentTestLoader._SOURCE_CODE_ROOT/"test_suites"/"images.yml") if "images" not in image_descriptions: raise Exception("images.yml is missing the 'images' item") images = {} # ...
Python
nomic_cornstack_python_v1
function plot self column_for_xticks=none overlay=false **vargs begin set tuple xticks labels = call _split column_for_xticks function draw axis label color begin plot self at label color=color keyword vargs end function function annotate axis ticks begin call set_xticklabels ticks rotation=string vertical end function...
def plot(self, column_for_xticks=None, overlay=False, **vargs): xticks, labels = self._split(column_for_xticks) def draw(axis, label, color): axis.plot(self[label], color=color, **vargs) def annotate(axis, ticks): axis.set_xticklabels(ticks, rotation='vertical') s...
Python
nomic_cornstack_python_v1
function verifyInputs self mode begin string Goes through and checks all stimuli and input settings are valid and consistent. Prompts user with a message if there is a condition that would prevent acquisition. :param mode: The mode of acquisition trying to be run. Options are 'chart', or anthing else ('explore', 'proto...
def verifyInputs(self, mode): """Goes through and checks all stimuli and input settings are valid and consistent. Prompts user with a message if there is a condition that would prevent acquisition. :param mode: The mode of acquisition trying to be run. Options are 'chart', o...
Python
jtatman_500k
function shuffle self begin set train_nodes = call permutation train_nodes set batch_num = 0 end function
def shuffle(self): self.train_nodes = np.random.permutation(self.train_nodes) self.batch_num = 0
Python
nomic_cornstack_python_v1
function save_file self file_path content begin with open file_path string w+ as file begin write file content return true end return false end function
def save_file(self, file_path: str, content: list) -> bool: with open(file_path, 'w+') as file: file.write(content) return True return False
Python
nomic_cornstack_python_v1
for i in range n m + 1 begin set a = string i if find a string o == - 1 begin pass end else begin set c = c + 1 end end print c
for i in range(n,m+1): a=str(i) if a.find(str(o))==-1: pass else: c=c+1 print(c)
Python
zaydzuhri_stack_edu_python
function build self learning_rate_name gradients_name params_name begin set input_names = list learning_rate_name gradients_name params_name return call _build_optimizer_node input_names call generate_graph_name string update_completed string SGDOptimizerV2 dict end function
def build( self, learning_rate_name: str, gradients_name: str, params_name: str, ) -> str: input_names = [learning_rate_name, gradients_name, params_name] return self._build_optimizer_node( input_names, _graph_utils.generate_graph_name("updat...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns comment %matplotlib inline from urllib.request import urlopen from bs4 import BeautifulSoup from contextlib import closing from selenium.webdriver import Firefox from selenium.webdriver.support.ui import WebDriverWait from sele...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline from urllib.request import urlopen from bs4 import BeautifulSoup from contextlib import closing from selenium.webdriver import Firefox from selenium.webdriver.support.ui import WebDriverWait from selen...
Python
zaydzuhri_stack_edu_python
function to_matrix_form model begin comment Assign each variable a deterministic symbol (an index comment in a list) so that we can guarantee the same matrix comment ordering for a given Pyomo model. We can not assign a comment column index until after collecting the list of comment variables that are actually used. se...
def to_matrix_form(model): # Assign each variable a deterministic symbol (an index # in a list) so that we can guarantee the same matrix # ordering for a given Pyomo model. We can not assign a # column index until after collecting the list of # variables that are actually used. sortOrder = (Sor...
Python
nomic_cornstack_python_v1
function __apply_caesar self delta begin set keylist = list key for index in range length keylist begin set keylist at index = character ordinal keylist at index + delta % CIPHER_KEY_ASCII_LIM end set key = join string keylist end function
def __apply_caesar(self, delta): keylist = list(self.key) for index in range(len(keylist)): keylist[index] = chr((ord(keylist[index]) + delta) % CIPHER_KEY_ASCII_LIM) self.key = ''.join(keylist)
Python
nomic_cornstack_python_v1
function get_playlist_items self begin set results = call playlist playlist_uri return results at string tracks at string items end function
def get_playlist_items(self): results = self.API.playlist(self.playlist_uri) return results["tracks"]["items"]
Python
nomic_cornstack_python_v1
function all_of_2 upto begin set upto = upto - 1 comment last ten digits set limit = 10 ^ 10 comment 509 and 24 are divisors of upto-1 set part = upto / 509 * 24 - 1 set number = 2 ^ 509 * 24 % limit set n = number for i in call xrange part begin set number = number * n % limit end return number * 2 * 28433 + 1 % limit...
def all_of_2(upto): upto-=1 limit=10**10 #last ten digits # 509 and 24 are divisors of upto-1 part=upto/(509*24)-1 number=(2**(509*24))%(limit) n=number for i in xrange(part): number=(number*n)%limit return (number*2*28433+1)%limit
Python
zaydzuhri_stack_edu_python
import pygame set img = string game_images/tentacles_1.png class Coils extends Sprite begin function __init__ self begin call __init__ self set image_orig = call convert_alpha set image = image_orig set rect = call get_rect set width = integer call get_width set height = integer call get_height set animate = false set ...
import pygame img = 'game_images/tentacles_1.png' class Coils(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) image_orig = pygame.image.load(img).convert_alpha() self.image= image_orig self.rect = self.image.get_rect() self.width = int(self.im...
Python
zaydzuhri_stack_edu_python
function test_lambda_handler_fail_loading_original_image self environ_get urlopen begin set side_effect = mock_environ_get set side_effect = exception string Not found set security_key = call environ_get string THUMBNAIL_URL_SECURITY_KEY set payload = string fit-in/400x400/cat.jpg set signature = decode call hmac_sha1 ...
def test_lambda_handler_fail_loading_original_image(self, environ_get, urlopen): environ_get.side_effect = mock_environ_get urlopen.side_effect = Exception("Not found") security_key = environ_get("THUMBNAIL_URL_SECURITY_KEY") payload = 'fit-in/400x400/cat.jpg' signature = lambda...
Python
nomic_cornstack_python_v1
function get_counters counter_list begin string Get the values for the passes list of counters Args: counter_list (list): A list of counters to lookup Returns: dict: A dictionary of counters and their values if not is instance counter_list list begin raise call CommandExecutionError string counter_list must be a list o...
def get_counters(counter_list): ''' Get the values for the passes list of counters Args: counter_list (list): A list of counters to lookup Returns: dict: A dictionary of counters and their values ''' if not isinstance(counter_list, list): raise CommandExecut...
Python
jtatman_500k
function test_insert_with_four_numbered_location self add_or_replace_child_mock find_node_mock begin comment Assign set root = call Node string Root node set child = call Node string Child node call add_or_replace_child node=child index=0 set tree = call Tree root_node=root set return_value = child set node_to_be_inser...
def test_insert_with_four_numbered_location(self, add_or_replace_child_mock, find_node_mock): # Assign root = Node("Root node") child = Node("Child node") root.add_or_replace_child(node=child,...
Python
nomic_cornstack_python_v1
function __init__ self type high_elevation low_elevation begin set type = type set high_elevation = high_elevation set low_elevation = low_elevation comment use 0 to initilize tile which set occupant = 0 comment means it has not been explored. comment initialize the shade if type == string plains begin set terrain = st...
def __init__(self, type, high_elevation, low_elevation): self.type = type self.high_elevation = high_elevation self.low_elevation = low_elevation self.occupant = 0 # use 0 to initilize tile which # means it has not been explored. if type == "plains": # initialize the shade self.terrain = " " el...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 comment -*- coding: utf-8 -*- string Created on Wed Jul 5 09:30:59 2017 @author: aude New smooth initial conditions from fipy import * comment ----------------------------------------------------------------------- comment ------------------------Geometry and mesh--------------------------...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 5 09:30:59 2017 @author: aude New smooth initial conditions """ from fipy import * #----------------------------------------------------------------------- #------------------------Geometry and mesh------------------------------ #---------------...
Python
zaydzuhri_stack_edu_python
function sequencemicro l1 begin set l2 = list for i in range length l1 begin if l1 at i > 0 begin append l2 l1 at i end end for i in range length l1 begin if l1 at i < 0 begin append l2 l1 at i end end for i in range length l1 begin if l1 at i == 0 begin append l2 l1 at i end end return l2 end function set l1 = list 1...
def sequencemicro(l1): l2 = [] for i in range(len(l1)): if l1[i] > 0: l2.append(l1[i]) for i in range(len(l1)): if l1[i] < 0: l2.append(l1[i]) for i in range(len(l1)): if l1[i] == 0: l2.append(l1[i]) return l2...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Apr 18 23:14:58 2020 @author: Alex code for windows comment from typing import List class Solution begin function getHappyString self n k begin if k > 3 * 2 ^ n - 1 begin return string end set ans = string set stack = list string a string b string c set k = k - 1 wh...
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 23:14:58 2020 @author: Alex code for windows """ #from typing import List class Solution: def getHappyString(self, n: int, k: int) -> str: if k > 3 * (2**(n-1)): return '' ans = '' stack = ['a','b','c'] k -= 1 whil...
Python
zaydzuhri_stack_edu_python
function run self begin if _proxy is not none begin return call format_proxy end if _random_proxy begin return call random_proxy end end function
def run(self) -> dict: if self._proxy is not None: return self.format_proxy() if self._random_proxy: return Proxy.random_proxy()
Python
nomic_cornstack_python_v1
function paginatedUrls pattern view kwargs=none name=none begin set results = list tuple pattern view kwargs name set tail = string set mtail = search string (/+\+?\*?\??\$?)$ pattern if mtail begin set tail = call group 1 end set pattern = pattern at slice : length pattern - length tail : set results = results + li...
def paginatedUrls(pattern, view, kwargs=None, name=None): results = [(pattern, view, kwargs, name)] tail = '' mtail = re.search('(/+\+?\\*?\??\$?)$', pattern) if mtail: tail = mtail.group(1) pattern = pattern[:len(pattern) - len(tail)] results += [(pattern + "/(?P<page_number>\d+)" + tai...
Python
nomic_cornstack_python_v1
function _clean_up_temporary_files dataset_dir begin set filename = split _DATA_URL string / at - 1 set filepath = join path dataset_dir filename remove gfile filepath set tmp_dir = join path dataset_dir string flower_photos call DeleteRecursively tmp_dir end function
def _clean_up_temporary_files(dataset_dir): filename = _DATA_URL.split('/')[-1] filepath = os.path.join(dataset_dir, filename) tf.gfile.Remove(filepath) tmp_dir = os.path.join(dataset_dir, 'flower_photos') tf.gfile.DeleteRecursively(tmp_dir)
Python
nomic_cornstack_python_v1
function close self begin for stub in stubs begin close stub end end function
def close(self): for stub in self.stubs: stub.close()
Python
nomic_cornstack_python_v1
string 206. Reverse Linked List Reverse a singly linked list. class ListNode extends object begin function __init__ self x begin set val = x set next = none end function end class class Solution extends object begin function reverseList self head begin string :type head: ListNode :rtype: ListNode insert nodes into new ...
''' 206. Reverse Linked List Reverse a singly linked list. ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode insert nodes into new Linke...
Python
zaydzuhri_stack_edu_python
function solve meal_cost tippercent taxpercent begin set tip = meal_cost * tippercent / 100 set tax = meal_cost * taxpercent / 100 set total = meal_cost + tip + tax print round total end function call solve meal_cost tippercent taxpercent
def solve(meal_cost, tippercent, taxpercent): tip = meal_cost * tippercent /100 tax = meal_cost * taxpercent /100 total = meal_cost + tip +tax print (round(total)) solve(meal_cost,tippercent,taxpercent)
Python
zaydzuhri_stack_edu_python
from behave import given , when , then , step import requests decorator call given string A user with valid access token function set_access_token_in_header context begin set header = dict string Authorization string Bearer + string b3c1e915bc7874d30e268e8de481322ed3b97e454ff0a82c63ec53d07c066b91 end function decorator...
from behave import given, when, then, step import requests @given('A user with valid access token') def set_access_token_in_header(context): context.header = {"Authorization": "Bearer " + "b3c1e915bc7874d30e268e8de481322ed3b97e454ff0a82c63ec53d07c066b91"} @step('the user has email as "subornosamonto@gmail.com...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self data begin set data = data set left = none set right = none end function end class class BinarySearchTree begin function __init__ self begin set root = none end function function insert self data begin if root == none begin set root = call Node data end else begin call _insert da...
class Node: def __init__ (self, data): self.data = data self.left = None self.right = None class BinarySearchTree: def __init__ (self): self.root = None def insert (self, data): if self.root == None: self.root = Node(data) else: self...
Python
flytech_python_25k
comment !pip install nltk import nltk comment nltk.download('movie_reviews') from nltk.corpus import movie_reviews from featx import bag_of_words from featx import label_feats_from_corpus from featx import split_label_feats set lfeats = call label_feats_from_corpus movie_reviews set tuple train_feats test_feats = call ...
# !pip install nltk import nltk #nltk.download('movie_reviews') from nltk.corpus import movie_reviews from featx import bag_of_words from featx import label_feats_from_corpus from featx import split_label_feats lfeats = label_feats_from_corpus(movie_reviews) train_feats, test_feats = split_label_feats(lfeats, spli...
Python
zaydzuhri_stack_edu_python
function _on_single self begin call set_single end function
def _on_single(self) -> None: self.row_generator.set_single()
Python
nomic_cornstack_python_v1
import torch as ts import torch.nn as nn call manual_seed 1 import numpy as np import random import time from mlxtend.data import loadlocal_mnist function enforce_reproducibility seed=42 begin comment Sets seed manually for both CPU and CUDA call manual_seed seed call manual_seed_all seed comment For atomic operations ...
import torch as ts import torch.nn as nn ts.manual_seed(1) import numpy as np import random import time from mlxtend.data import loadlocal_mnist def enforce_reproducibility(seed=42): # Sets seed manually for both CPU and CUDA ts.manual_seed(seed) ts.cuda.manual_seed_all(seed) # For atomic operations...
Python
zaydzuhri_stack_edu_python
from collections import Counter function detect_anagrams word candidates begin string Takes a word and a list of possible anagrams, and returns matches An anagram is a word, phrase, or sentence formed from another by rearranging its letters :param word: input string used to match against candidates :param candidates: a...
from collections import Counter def detect_anagrams(word, candidates): """ Takes a word and a list of possible anagrams, and returns matches An anagram is a word, phrase, or sentence formed from another by rearranging its letters :param word: input string used to match against candidates :par...
Python
zaydzuhri_stack_edu_python
string Backtracking. The difference between combination sum II and I is that II allows duplicates in the number array; and each number element can be used once in each combination. Thus, when backtracking, the next level start from i+1 instead i in I. And we need sort the nums first and skip the duplicates if it is not...
""" Backtracking. The difference between combination sum II and I is that II allows duplicates in the number array; and each number element can be used once in each combination. Thus, when backtracking, the next level start from i+1 instead i in I. And we need sort the nums first and skip the duplicates if it is not st...
Python
zaydzuhri_stack_edu_python
function add self x begin if x not in indices begin set indices at x = length indices append items x end return indices at x end function
def add(self, x): if x not in self.indices: self.indices[x] = len(self.indices) self.items.append(x) return self.indices[x]
Python
nomic_cornstack_python_v1
from operator import attrgetter from praca_projektowa_2.analyzers.Analyzer import Analyzer from praca_projektowa_2.classifiers.KNeighboursClassifier import KNeighboursClassifier class KNeighboursAnalyzer extends Analyzer begin set x_train = list set x_test = list set y_train = list set y_test = list set classifier ...
from operator import attrgetter from praca_projektowa_2.analyzers.Analyzer import Analyzer from praca_projektowa_2.classifiers.KNeighboursClassifier import KNeighboursClassifier class KNeighboursAnalyzer(Analyzer): x_train = [] x_test = [] y_train = [] y_test = [] classifier = None result_mapp...
Python
zaydzuhri_stack_edu_python
comment Authors: maormiz, michael3162 comment Students We talked the exercise with: NO ONE. comment INTRO TO CS 2019-2020 EXERCISE 12 comment Additional Files: comment boggle.py, extra.py, helper.py, boggle_board_randomizer.py, screen.py, comment boggle_dict.txt, AUTHORS, README import boggle_board_randomizer class Boa...
# Authors: maormiz, michael3162 # Students We talked the exercise with: NO ONE. # INTRO TO CS 2019-2020 EXERCISE 12 # Additional Files: # boggle.py, extra.py, helper.py, boggle_board_randomizer.py, screen.py, # boggle_dict.txt, AUTHORS, README ####################################################### import boggle_board_...
Python
zaydzuhri_stack_edu_python
from tkinter import * from math import sqrt , atan , cos , sin , pi , exp , asin , acos from threading import Thread from random import randint from time import sleep , time from copy import deepcopy import pickle set fen = call Tk call geometry string 1200x1000 set fen at string bg = string white set TEMPS = time set ...
from tkinter import * from math import sqrt,atan,cos,sin,pi,exp,asin,acos from threading import Thread from random import randint from time import sleep,time from copy import deepcopy import pickle fen = Tk() fen.geometry("1200x1000") fen["bg"]="white" TEMPS=time() canvas = Canvas(fen,width=1200,height=1000,bg="white...
Python
zaydzuhri_stack_edu_python
function render_GET self request begin if not length open_connections begin call setResponseCode 204 message=b'No clients connected to SSH tarpit' return b'' end set result = list set now = now call setHeader b'Content-Type' b'application/json' for con in open_connections begin set duration = now - con at 0 set ip_add...
def render_GET(self, request): if not len(self.tarpit_factory.open_connections): request.setResponseCode(204, message=b"No clients connected " b"to SSH tarpit") return b"" result = [] now = datetime.datetime.now() request.setH...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Apr 13 21:39:10 2021 @author: PC import numpy as np import sympy as sp from math import factorial from sympy.plotting import plot function dif a begin if a == 1 begin return 1 / 3 end if a == 2 begin return 7 end end function function difii b begin if b == 2 begin ret...
# -*- coding: utf-8 -*- """ Created on Tue Apr 13 21:39:10 2021 @author: PC """ import numpy as np import sympy as sp from math import factorial from sympy.plotting import plot def dif(a): if(a==1): return 1/3 if(a==2): return 7 def difii(b): if(b==2): return 8 x=np.array([...
Python
zaydzuhri_stack_edu_python
function get_context_and_attention_probs values length logits begin comment (batch_size, seq_len, 1) set logits = call mask_attention_scores logits length comment (batch_size, seq_len, 1) set probs = softmax logits axis=1 name=string attention_softmax comment batch_dot: (batch, M, K) X (batch, K, N) –> (batch, M, N). c...
def get_context_and_attention_probs(values: mx.sym.Symbol, length: mx.sym.Symbol, logits: mx.sym.Symbol) -> Tuple[mx.sym.Symbol, mx.sym.Symbol]: # (batch_size, seq_len, 1) logits = mask_attention_scores(logits, length) # (batch_size, s...
Python
nomic_cornstack_python_v1
function match_quality self dps begin set keys = list keys dps set matched = list if string updated_at in keys begin remove keys string updated_at end set total = length keys if not call _entity_match_analyse primary_entity keys matched dps begin return 0 end for e in call secondary_entities begin if not call _entity_...
def match_quality(self, dps): keys = list(dps.keys()) matched = [] if "updated_at" in keys: keys.remove("updated_at") total = len(keys) if not self._entity_match_analyse(self.primary_entity, keys, matched, dps): return 0 for e in self.sec...
Python
nomic_cornstack_python_v1
import sys import MapReduce comment Part 1 set mr = call MapReduce comment Part 2 function mapper record begin set a = record at 0 set b = record at 1 call emit_intermediate a tuple b true call emit_intermediate b tuple a false end function comment Part 3 function reducer key relations begin set frs = set set bfrs = se...
import sys import MapReduce # Part 1 mr = MapReduce.MapReduce() # Part 2 def mapper(record): a = record[0] b = record[1] mr.emit_intermediate(a,(b,True)) mr.emit_intermediate(b,(a,False)) # Part 3 def reducer(key, relations): frs = set() bfrs = set() for r in relations: if r[1] =...
Python
zaydzuhri_stack_edu_python
function validate_1d self begin set test_loss = list eval comment Freeze gradients with no grad begin comment Iterate over test set for tuple batch_idx tuple data annotations in enumerate test_loader begin comment Select target labels according to the `dimension` if dimension == string valence begin set target = annot...
def validate_1d(self): test_loss = [] self.model.eval() # Freeze gradients with torch.no_grad(): # Iterate over test set for batch_idx, (data, annotations) in enumerate(self.test_loader): # Select target labels according to the `dimension` ...
Python
nomic_cornstack_python_v1
function json_response data status=200 **kwargs begin comment Conversion function is needed for datetime objects :/ function jsonconvert obj begin if is instance obj datetime or is instance obj date begin return call isoformat end return string obj end function set resp = call Response dumps data default=jsonconvert st...
def json_response(data, status = 200, **kwargs): # Conversion function is needed for datetime objects :/ def jsonconvert(obj): if isinstance(obj, datetime) or isinstance(obj, date): return obj.isoformat() return str(obj) resp = Response(json.dumps(data, default=jsonconvert), status=status, mimetype='application/...
Python
nomic_cornstack_python_v1
function getAction self gameState begin string *** YOUR CODE HERE *** comment print "\nSTART" comment print "gameState.getNumAgents()", gameState.getNumAgents() comment print "func_name evaluationFunction", self.evaluationFunction.func_name function merge_values agent state remaining_depth mode a b begin string mode = ...
def getAction(self, gameState): "*** YOUR CODE HERE ***" # print "\nSTART" # print "gameState.getNumAgents()", gameState.getNumAgents() # print "func_name evaluationFunction", self.evaluationFunction.func_name def merge_values(agent, state, remaining_depth, mode, a, b): ...
Python
nomic_cornstack_python_v1
function db_connect begin return call create_engine get call get_project_settings string CONNECTION_STRING end function
def db_connect(): return create_engine(get_project_settings().get("CONNECTION_STRING"))
Python
nomic_cornstack_python_v1
function save_slack_token request begin debug string Slack callback just landed set error = get query_params string error false set error_description = get query_params string error_description string if error begin raise call APIException string Slack: + error_description end set original_payload = get query_params st...
def save_slack_token(request): logger.debug("Slack callback just landed") error = request.query_params.get('error', False) error_description = request.query_params.get('error_description', '') if error: raise APIException("Slack: " + error_description) original_payload = request.query_para...
Python
nomic_cornstack_python_v1
function calc_sol sol wts param begin for k in wts begin for i in range 1 param at 1 + 1 begin if i >= k begin set sol at i = max sol at i k + sol at i - k end end end end function
def calc_sol(sol, wts, param): for k in wts: for i in range(1, param[1]+1): if i >= k: sol[i] = max(sol[i], k+sol[i - k])
Python
zaydzuhri_stack_edu_python
string This is the thing artist tester. It will extend the ArtistTester class. from artist_tester import ArtistTester from thing_artist import ThingArtist import random import math import turtle class ThingArtistTester extends ArtistTester begin comment Constructor function __init__ self begin call __init__ end functio...
''' This is the thing artist tester. It will extend the ArtistTester class. ''' from artist_tester import ArtistTester from thing_artist import ThingArtist import random import math import turtle class ThingArtistTester(ArtistTester): # Constructor def __init__(self): super().__init__() #...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import numpy as np import pandas as pd import statsmodels.api as sm import seaborn import statsmodels.formula.api as smf import matplotlib.pyplot as plt import seaborn function print_frequency data col format=string count begin set norm = if expression format == string percent then true el...
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import statsmodels.api as sm import seaborn import statsmodels.formula.api as smf import matplotlib.pyplot as plt import seaborn def print_frequency(data, col, format="count"): norm=True if format=="percent" else False print(format,'-') print(...
Python
zaydzuhri_stack_edu_python
function parse_txt txt_path debug_till_row=none join_desc=false return_max_len=false fraction=1 label_prefix=string __label__ seed=none begin with open txt_path string r as infile begin if debug_till_row not in list none - 1 begin set data = split read infile string at slice : debug_till_row : end else begin set data...
def parse_txt(txt_path, debug_till_row=None, join_desc=False, return_max_len=False, fraction=1, label_prefix="__label__", seed=None): with open(txt_path, "r") as infile: if debug_till_row not in [None, -1]: data = infile.read().split("\n")[:debug_till_row] else: ...
Python
nomic_cornstack_python_v1
string give tag for different time series. set __all__ = list string type_tag import pandas as pd from period_confirm import period_confirm from kpi.processor.preprocessing import denoise_train_data , discrete_confirm function type_tag series cfg begin string give tag for kpi series, discrete, period, non-period "has_p...
''' give tag for different time series. ''' __all__ = ["type_tag"] import pandas as pd from .period_confirm import period_confirm from kpi.processor.preprocessing import denoise_train_data, discrete_confirm def type_tag(series: pd.Series, cfg: dict): ''' give tag for kpi series, discrete, period, non-period ...
Python
zaydzuhri_stack_edu_python
function find self vport_name=none emulation_host=none **filters begin return find call super IxnActionEmulation self list string topology string deviceGroup string ipv4Loopback string ldpTargetedRouter string ldppwvpls string ipv6Loopback string ldpTargetedRouterV6 string ldpotherpws string ethernet string ipv6 string...
def find(self, vport_name=None, emulation_host=None, **filters): return super(IxnActionEmulation, self).find(["topology","deviceGroup","ipv4Loopback","ldpTargetedRouter","ldppwvpls","ipv6Loopback","ldpTargetedRouterV6","ldpotherpws","ethernet","ipv6","greoipv6","ipv4","openFlowController","ofChannelLearnedInfo...
Python
nomic_cornstack_python_v1
from Util import ListRedirect class BinaryOperator extends object begin set NAME = string function __init__ self left right begin set left = left set right = right end function function __repr__ self begin return string (%s %s %s) % tuple is instance left ListRedirect and reduce or left NAME is instance right ListRedi...
from Util import ListRedirect class BinaryOperator(object): NAME = '' def __init__(self,left,right): self.left = left self.right = right def __repr__(self): return "(%s %s %s)"%( isinstance(self.left,ListRedirect) and self.left.reduce() or self.left, self.NA...
Python
zaydzuhri_stack_edu_python
comment person.py class Person begin function __init__ self nm addr tel begin set __name = nm set __addr = addr set __tel = tel end function function set_name self begin set __name = input string Enter your name: end function function insert_name self n begin set __name = n end function function set_addr self begin set...
#person.py class Person: def __init__(self,nm,addr,tel): self.__name=nm self.__addr=addr self.__tel=tel def set_name(self): self.__name=input('Enter your name:') def insert_name(self,n): self.__name=n def set_addr(self): self.__addr=input('Enter...
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_invalid_input_int self b...
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_invalid_input_int(self): self.as...
Python
zaydzuhri_stack_edu_python
function processInitialized self begin return has attribute self string _process end function
def processInitialized(self): return hasattr(self, "_process")
Python
nomic_cornstack_python_v1
function plot_swim_speed exp_ind swim_speed begin import numpy set tuple fig ax = call subplots call set_text string Swim speed from depth change and pitch angle (m/s^2 plot exp_ind swim_speed linewidth=_linewidth label=string speed set ymax = ceil max call set_ylim 0 ymax legend loc=string upper right show return ax e...
def plot_swim_speed(exp_ind, swim_speed): import numpy fig, ax = plt.subplots() ax.title.set_text("Swim speed from depth change and pitch angle (m/s^2") ax.plot(exp_ind, swim_speed, linewidth=_linewidth, label="speed") ymax = numpy.ceil(swim_speed[~numpy.isnan(swim_speed)].max()) ax.set_ylim(0...
Python
nomic_cornstack_python_v1
function seekset func begin string [ClassMethod] Read file from start then set back to original. decorator wraps func function seekcur self *args **kw begin set seek_cur = tell _file seek _file _seekset SEEK_SET set return_ = call func self *args keyword kw seek _file seek_cur SEEK_SET return return_ end function retur...
def seekset(func): """[ClassMethod] Read file from start then set back to original.""" @functools.wraps(func) def seekcur(self, *args, **kw): seek_cur = self._file.tell() self._file.seek(self._seekset, os.SEEK_SET) return_ = func(self, *args, **kw) self._file.seek(seek_cur, o...
Python
jtatman_500k
comment program to reverse a given string set string = input string enter the string that you want to reverse comment using slice print string at slice : : - 1 set str = string comment using recursion function reverse string begin set string = join string reversed string return string end function comment using loo...
# program to reverse a given string string = input("enter the string that you want to reverse") print(string[:: -1]) # using slice str = "" def reverse(string): # using recursion string = "".join(reversed(string)) return string for x in string: # using loop str = x + str print(str) print(reverse(stri...
Python
zaydzuhri_stack_edu_python
function loadTFC contactString begin set protocol = call tfcProtocol contactString set catalog = call tfcFilename contactString set instance = call readTFC catalog set preferredProtocol = protocol return instance end function
def loadTFC(contactString): protocol = tfcProtocol(contactString) catalog = tfcFilename(contactString) instance = readTFC(catalog) instance.preferredProtocol = protocol return instance
Python
nomic_cornstack_python_v1
function setFrozen self val=string True **kwargs begin pass end function
def setFrozen(self, val='True', **kwargs): pass
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Author: Guillermo Robles comment Extract data from the register file import csv import re import sqlite3 function remove_tildes string begin string Removes tildes. Nothing more to say return replace replace replace replace replace replace replace replac...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Guillermo Robles # # Extract data from the register file import csv import re import sqlite3 def remove_tildes(string): """Removes tildes. Nothing more to say """ return string.replace('á', 'a')\ .replace('é', 'e')\ ...
Python
zaydzuhri_stack_edu_python
from Coordinate import Coordinate import copy from GameField import calculate_point , get_connected_points from datetime import datetime function if_there_path_to_win game_field player1 player2 wall begin call cleanup comment TODO Заменить как-то deepcopy set temp_field = deep copy game_field call set_wall wall set gra...
from Coordinate import Coordinate import copy from GameField import calculate_point, get_connected_points from datetime import datetime def if_there_path_to_win(game_field, player1, player2, wall): game_field.graph.cleanup() temp_field = copy.deepcopy(game_field) # TODO Заменить как-то deepcopy temp_fiel...
Python
zaydzuhri_stack_edu_python
function __init__ self filter_expression nowrap=false asvar=none message_context=none begin set asvar = asvar set message_context = message_context set filter_expression = filter_expression if is instance var string_types begin set var = call Variable string '%s' % var end set nowrap = nowrap end function
def __init__(self, filter_expression, nowrap = False, asvar=None, message_context=None): self.asvar = asvar self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, six.string_types): self.filter_expression.va...
Python
nomic_cornstack_python_v1
function get_factors_faster number begin set tuple lower_factors upper_factors = tuple list list set max_remaining_factor = number set i = 1 while i < max_remaining_factor begin set result = number / i if call is_integer begin append lower_factors i if result != i begin append upper_factors integer result end end set...
def get_factors_faster(number): lower_factors, upper_factors = [], [] max_remaining_factor = number i = 1 while i < max_remaining_factor: result = number / i if result.is_integer(): lower_factors.append(i) if result != i: upper_factors.append(int...
Python
nomic_cornstack_python_v1
string Ensembling ImageNet models for streaming DL applications. Author: Prathamesh Mandke Date created: 10/25/2019 import os import time from datetime import timedelta import torch class Ensemble begin function __init__ self model_path ensemble_type=string avg device=string cuda:0 begin string Initialize an Ensemble o...
''' Ensembling ImageNet models for streaming DL applications. Author: Prathamesh Mandke Date created: 10/25/2019 ''' import os import time from datetime import timedelta import torch class Ensemble: def __init__(self, model_path, ensemble_type='avg', device='cuda:0'): ''' Initialize an Ensemble obj...
Python
zaydzuhri_stack_edu_python
function delete_local_operator self onnx_name begin string Remove the operator whose onnx_name is the input onnx_name if onnx_name not in onnx_operator_names or onnx_name not in operators begin raise call RuntimeError string The operator to be removed not found end discard onnx_operator_names onnx_name del operators at...
def delete_local_operator(self, onnx_name): ''' Remove the operator whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_operator_names or onnx_name not in self.operators: raise RuntimeError('The operator to be removed not found') self.onnx_operato...
Python
jtatman_500k
function moduleids module begin set out = dict for tuple key thing in call itermodule module begin set out at call id thing = tuple key thing end return out end function
def moduleids(module): out = {} for key, thing in itermodule(module): out[id(thing)] = (key, thing) return out
Python
nomic_cornstack_python_v1
function azure_resource_id self begin return get pulumi self string azure_resource_id end function
def azure_resource_id(self) -> str: return pulumi.get(self, "azure_resource_id")
Python
nomic_cornstack_python_v1
function initial_velocity self begin return _initial_velocity end function
def initial_velocity(self) -> float: return self._initial_velocity
Python
nomic_cornstack_python_v1
function write self field_name value begin set field = call get_field field_name if call read_before_write begin set encoded_data = encode field value reader call get_offset call get_size end else begin set encoded_data = encode field value end return writer call get_offset call get_size encoded_data end function
def write(self, field_name, value): field = self.mem_map.get_field(field_name) if field.read_before_write(): encoded_data = field.encode(value, self.reader(field.get_offset(), field.get_size())) else: encoded_data = field.encode(value) return self.writer(field.get_offset(), fie...
Python
nomic_cornstack_python_v1
function find_radius alpha xi begin return alpha * xi end function
def find_radius(alpha, xi): return alpha * xi
Python
nomic_cornstack_python_v1
function get_plugin_options name begin return call get_options end function
def get_plugin_options(name): return get_plugin_loader(name).get_options()
Python
nomic_cornstack_python_v1
function add_tag self tag begin return add _tag_manager tag end function
def add_tag(self, tag): return self._tag_manager.add(tag)
Python
nomic_cornstack_python_v1
from random import randint set pontos_usuario = 0 set pontos_pc = 0 set empates = 0 while true begin set jogada_usuario = input string Qual é a sua jogada? (Pedra, papel ou tesoura) Ou digite 'Sair' para sair do jogo. set jogada_pc = random integer 0 3 if jogada_pc == 0 begin print string A jogada do PC é: Pedra end el...
from random import randint pontos_usuario = 0 pontos_pc = 0 empates = 0 while True: jogada_usuario = input("Qual é a sua jogada? (Pedra, papel ou tesoura) Ou digite 'Sair' para sair do jogo. ") jogada_pc = randint(0,3) if jogada_pc == 0: print("A jogada do PC é: Pedra") elif jogada_pc == 1: ...
Python
zaydzuhri_stack_edu_python
from picamera.array import PiRGBArray from picamera import PiCamera import cv2 import numpy import time import argparse from Electronics.PiVideoStream import PiVideoStream import imutils class Camera extends PiVideoStream begin string def __init__(self): self.cap = cv2.VideoCapture(0) def get_frame(self): ret, frame = ...
from picamera.array import PiRGBArray from picamera import PiCamera import cv2 import numpy import time import argparse from Electronics.PiVideoStream import PiVideoStream import imutils class Camera(PiVideoStream): ''' def __init__(self): self.cap = cv2.VideoCapture(0) def get_frame(self): ...
Python
zaydzuhri_stack_edu_python
class Test begin set a = 10 end class function get self begin print a end function set t1 = call Test set attribute t1 string get get comment t1.get() set t2 = Test set attribute t2 string get get get call t2
class Test: a = 10 def get(self): print(self.a) t1 = Test() setattr(t1, 'get', get) # t1.get() t2 = Test setattr(t2, 'get', get) t2().get()
Python
zaydzuhri_stack_edu_python
comment 아 맞았다... 난 틀리지않았어.. comment input = sys.stdin.readline 안 넣으면 무조건 시간초과 import sys set input = readline comment 도시개수, 도로개수, 거리, 출발 set tuple n m k x = map int split input set graph = list comprehension list for _ in range n + 1 set visited = list false * n + 1 for i in range m begin set tuple a b = map int split...
# 아 맞았다... 난 틀리지않았어.. # input = sys.stdin.readline 안 넣으면 무조건 시간초과 import sys input = sys.stdin.readline # 도시개수, 도로개수, 거리, 출발 n,m,k,x = map(int, input().split()) graph = [[] for _ in range(n+1)] visited = [False] * (n+1) for i in range(m): a, b = map(int, input().split()) graph[a].append(b) visited[x] = True ...
Python
zaydzuhri_stack_edu_python
import argparse from glob import glob import csv from openpyxl import Workbook import re import sys from contextlib import suppress set BAD_PN_REGEX = list string ^$ string ^X\d+_[A-Z] string \d+_SUB\d+ function _tuppled_item item_str begin if item_str begin return tuple list comprehension integer item for item in spli...
import argparse from glob import glob import csv from openpyxl import Workbook import re import sys from contextlib import suppress BAD_PN_REGEX = [r'^$', r'^X\d+_[A-Z]', r'\d+_SUB\d+'] def _tuppled_item(item_str: str) -> tuple: if item_str: return tuple([int(item) for item in item_str.split('.')]) e...
Python
zaydzuhri_stack_edu_python
function update self start_timestamp=none start_datetime=none start_date=none start_hours=none start_minutes=none duration_days=none duration_time=none duration_hours=none duration_minutes=none production_state=none enabled=none repeat=none occurrence=none days=none begin set new_params = dictionary if start_timestamp ...
def update(self, start_timestamp=None, start_datetime=None, start_date=None, start_hours=None, start_minutes=None, duration_days=None, duration_time=None, duration_hours=None, duration_minutes=None, production_state=None, enabled=None, repeat=None, occurrence=...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment ^3^ coding=utf-8 comment author: superzyx comment date: 2019/09/08 comment usage: the first one of exams comment 1.请使用Python代码分析日志(access_log)中 IP排名//状态码分布//最热资源排名(请写出各部分具体代码) set ip_dict = dict set state_dict = dict set hot_dict = dict set state_tuple = tuple string 200 string ...
#!/usr/bin/env python3 # ^3^ coding=utf-8 # # author: superzyx # date: 2019/09/08 # usage: the first one of exams # 1.请使用Python代码分析日志(access_log)中 IP排名//状态码分布//最热资源排名(请写出各部分具体代码) ip_dict = {} state_dict = {} hot_dict = {} state_tuple = ('200', '300', '400', '404', '499', '500', '505') with open(file='./source/access_...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys function solve grid R C begin set grid = list comprehension list row for row in grid set empty_rows = list set good_rows = list comment try to fill in horizontals? (greedy) for r in range R begin set first_c = 0 while first_c < C and grid at r at first_c == string ? begin set ...
#!/usr/bin/env python3 import sys def solve(grid, R, C): grid = [list(row) for row in grid] empty_rows = [] good_rows = [] # try to fill in horizontals? (greedy) for r in range(R): first_c = 0 while first_c < C and grid[r][first_c] == '?': first_c += 1 # didn...
Python
zaydzuhri_stack_edu_python
from db import db class Tag extends Model begin set __tablename__ = string tags set id = call Column Integer primary_key=true set game_id = call Column Integer call ForeignKey string decks.id nullable=false set tag_genre = call Column call String 255 set deck = call relationship string Deck back_populates=string tags f...
from .db import db class Tag(db.Model): __tablename__ = 'tags' id = db.Column(db.Integer, primary_key=True) game_id = db.Column(db.Integer, db.ForeignKey("decks.id"), nullable=False) tag_genre = db.Column(db.String(255)) deck = db.relationship("Deck", back_populates="tags") def to_dict(self)...
Python
zaydzuhri_stack_edu_python
function get_clickstream_download_links clickstream_download_links_request begin set auth = call build_authorizer set response = post url=CLICKSTREAM_API params=call to_url_params auth=auth return response end function
def get_clickstream_download_links(clickstream_download_links_request): auth = oauth2.build_oauth2(app=RESEARCH_EXPORTS_APP).build_authorizer() response = requests.post( url=CLICKSTREAM_API, params=clickstream_download_links_request.to_url_params(), auth=auth) return response
Python
nomic_cornstack_python_v1
function base_change self U begin if length self == 0 begin return self end try begin return call Factorization list comprehension tuple call U f at 0 f at 1 for f in list self unit=call U call unit end except TypeError begin raise call TypeError string Impossible to coerce the factors of %s into %s % tuple self U end ...
def base_change(self, U): if len(self) == 0: return self try: return Factorization([(U(f[0]), f[1]) for f in list(self)], unit=U(self.unit())) except TypeError: raise TypeError("Impossible to coerce the factors of %s into %s"%(self, U))
Python
nomic_cornstack_python_v1
function attributeClass self attribute begin pass end function
def attributeClass(self, attribute): pass
Python
nomic_cornstack_python_v1
function main corpus_dir index_dir num_trees=125 num_keywords=2 ngram=tuple 1 2 word_wt_file=none abbrv_file=none begin info format string {} version {} __name__ __version__ if not is directory path index_dir begin raise call FileNotFoundError format string directory not found; got {} index_dir end if not is directory ...
def main( corpus_dir, index_dir, num_trees=125, num_keywords=2, ngram=(1, 2), word_wt_file=None, abbrv_file=None, ): logger.info("{} version {}".format(__name__, v.__version__)) if not os.path.isdir(index_dir): raise FileNotFoundError( "directory not found; got {}...
Python
nomic_cornstack_python_v1
comment Developed by Prof. Roberto G. A. Veiga, Federal University of ABC, Brazil comment Version 0.4 import subprocess as sp import io import shlex class calc begin string calc -> this class implements attributes and methods that allow the user to run an electronic structure calculation with the code PW in the Quantum...
# Developed by Prof. Roberto G. A. Veiga, Federal University of ABC, Brazil # Version 0.4 import subprocess as sp import io import shlex class calc: ''' calc -> this class implements attributes and methods that allow the user to run an electronic structure calculation with the code PW in the Quantum ...
Python
zaydzuhri_stack_edu_python
function upload_template filename destination context=none use_jinja=false template_dir=none use_sudo=false backup=true mirror_local_mode=false mode=none mkdir=false chown=false user=none begin if mkdir begin set remote_dir = directory name path destination if use_sudo begin call sudo string mkdir -p %s % quote remote_...
def upload_template(filename, destination, context=None, use_jinja=False, template_dir=None, use_sudo=False, backup=True, mirror_local_mode=False, mode=None, mkdir=False, chown=False, user=None): if mkdir: remote_dir = os.path.dirname(destination)...
Python
nomic_cornstack_python_v1