code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function cartesian_product squeal_table1 squeal_table2 begin set result_table = dict comment All columns in the database have the same length, so the length of an comment arbitrary column from any table in the database is sufficent set t1_col_len = length squeal_table1 at list squeal_table1 at 0 set t2_col_len = lengt...
def cartesian_product(squeal_table1, squeal_table2): result_table = {} #All columns in the database have the same length, so the length of an #arbitrary column from any table in the database is sufficent t1_col_len = len(squeal_table1[list(squeal_table1)[0]]) t2_col_len = len(squeal_table2[lis...
Python
nomic_cornstack_python_v1
function inverse_index_str self s begin set nth_tok = 0 set position_to_nth = dict for tuple i c in enumerate s begin if c == string begin set nth_tok = nth_tok + 1 end set position_to_nth at i = nth_tok end return position_to_nth end function
def inverse_index_str(self, s): nth_tok = 0 position_to_nth = {} for i, c in enumerate(s): if c == " ": nth_tok += 1 position_to_nth[i] = nth_tok return position_to_nth
Python
nomic_cornstack_python_v1
with open string followers.txt as f1 ; open string followings.txt as f2 begin set s1 = set comprehension strip line for line in f1 set s2 = set comprehension strip line for line in f2 set diff = difference s2 s1 end for i in diff begin print i end
with open("followers.txt") as f1, open("followings.txt") as f2: s1 = {line.strip() for line in f1} s2 = {line.strip() for line in f2} diff = s2.difference(s1) for i in diff: print(i)
Python
zaydzuhri_stack_edu_python
import sys set stdin = open string input.txt string r set n = integer input set data = list for i in range n begin append data list split input end set data = sorted data key=lambda x -> tuple - integer x at 1 integer x at 2 - integer x at 3 x at 0 print string DATA ?? data
import sys sys.stdin = open("input.txt",'r') n = int(input()) data = [] for i in range(n): data.append(list(input().split())) data =sorted(data,key = lambda x : ( -int(x[1]), int(x[2]), -int(x[3]), x[0])) print("DATA ??",data)
Python
zaydzuhri_stack_edu_python
function execute self begin comment Subscribe graph vertices to the protocol_finished Event for tuple vertex_name vertex in items vertices begin set handler_name = format string {}_close_handler vertex_name if not call has_handler handler_name begin set protocol_finished = protocol_finished + call EventHandler handler_...
def execute(self): # Subscribe graph vertices to the protocol_finished Event for vertex_name, vertex in self.graph.vertices.items(): handler_name = "{}_close_handler".format(vertex_name) if not self.protocol_finished.has_handler(handler_name): self.protocol_finish...
Python
nomic_cornstack_python_v1
function procedures self begin return settings at string procedures end function
def procedures(self): return self.settings["procedures"]
Python
nomic_cornstack_python_v1
string これは間違って作ったやつ ファイルの分割数ではなく、ファイルの分割行 import string set N = integer input string 分割行数を入力してください: set a_Z = ascii_letters set path_I = string hightemp.txt set path_O = string path_f_splited.txt set lists = list with open path_I string r as I begin for i in I begin append lists i end end comment a-z用のインデックス set d = 0...
""" これは間違って作ったやつ ファイルの分割数ではなく、ファイルの分割行 """ import string N = int(input('分割行数を入力してください:')) a_Z = string.ascii_letters path_I = "hightemp.txt" path_O = "path_f_splited.txt" lists = [] with open(path_I,'r') as I: for i in I: lists.append(i) d = 0 # a-z用のインデックス while len(lists) > 0: with open(pa...
Python
zaydzuhri_stack_edu_python
function test_binary_global begin seed 0 set image = uniform size=tuple 20 20 set threshold = call threshold_otsu image set expected = image > threshold set tuple workspace module = call make_workspace image set value = TS_GLOBAL set value = TM_OTSU run workspace set output = call get_image OUTPUT_IMAGE_NAME assert all...
def test_binary_global(): numpy.random.seed(0) image = numpy.random.uniform(size=(20, 20)) threshold = skimage.filters.threshold_otsu(image) expected = image > threshold workspace, module = make_workspace(image) module.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL module.g...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri Jul 3 10:42:03 2020 @author: pavankunchala import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import seaborn as sns call set_style string darkgrid import random comment Parameters comment Discounting Rate range from ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 3 10:42:03 2020 @author: pavankunchala """ import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') import random #Parameters gamma = 1 #Discounting Rate range from (0 to 1) rewar...
Python
zaydzuhri_stack_edu_python
function init self begin comment Create the default project files call create_from_templates comment Add all the newly created files to the git staging area call add_all_untracked comment Check that a compatible version of Python is available; install it if not call ensure_python call get_python_version comment Create ...
def init(self): # Create the default project files self.create_from_templates() # Add all the newly created files to the git staging area self.add_all_untracked() # Check that a compatible version of Python is available; install it if not self._pyenv.ensure_python(self....
Python
nomic_cornstack_python_v1
function check_deepcopying self scene bounds error=0.0101 begin comment Test if the MayaVi2 visualization can be deep-copied. comment Pop the source object. set source = pop children comment Add it back to see if that works without error. append children source call check scene bounds error comment Now deepcopy the sou...
def check_deepcopying(self, scene, bounds, error = 1.01e-02): ############################################################ # Test if the MayaVi2 visualization can be deep-copied. # Pop the source object. source = scene.children.pop() # Add it back to see if that wor...
Python
nomic_cornstack_python_v1
import os , sys import xml.etree.ElementTree as ET set path = absolute path path directory name path argv at 0 comment tree = ET.parse(os.path.join(path, 'haute-normandie-latest.osm')) set tree = parse ET join path path string france_fuel.osm set root = get root tree comment Check first 50 elements comment for i in ran...
import os, sys import xml.etree.ElementTree as ET path = os.path.abspath(os.path.dirname(sys.argv[0])) # tree = ET.parse(os.path.join(path, 'haute-normandie-latest.osm')) tree = ET.parse(os.path.join(path, 'france_fuel.osm')) root = tree.getroot() ## Check first 50 elements #for i in range(50): # print '\n', root[i]...
Python
zaydzuhri_stack_edu_python
function delete self dn begin string delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. call _debug string delete self comment get copy of cache set result = call _cache_get_for_dn dn comment remove special values that can't be added function delete_attribute name begin ...
def delete(self, dn: str) -> None: """ delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ _debug("delete", self) # get copy of cache result = self._cache_get_for_dn(dn) # remove special values that ca...
Python
jtatman_500k
import math import time import pygame as pygame set win = call set_mode tuple 500 500 set clock = call Clock set map_size = call Vector2 30 30 set tile_size = call Vector2 call get_width / x call get_height / y set game_map = dict for y in range integer y begin for x in range integer x begin set game_map at tuple x y ...
import math import time import pygame as pygame win = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() map_size = pygame.math.Vector2(30, 30) tile_size = pygame.math.Vector2(win.get_width() / map_size.x, win.get_height() / map_size.y) game_map = {} for y in range(int(map_size.y)): for x in range(...
Python
zaydzuhri_stack_edu_python
function auth_delete_creds self username=none begin string Delete the credentials for a specific username if specified or all stored credentials. :param str username: The username of the credentials to delete. if not username begin set __config at string basic_auth = dict info string basic authentication database has ...
def auth_delete_creds(self, username=None): """ Delete the credentials for a specific username if specified or all stored credentials. :param str username: The username of the credentials to delete. """ if not username: self.__config['basic_auth'] = {} self.logger.info('basic authentication database ...
Python
jtatman_500k
function append self row_dict begin string Add a row to the spreadsheet, returns the new row comment TODO validate row_dict.keys() match comment TODO check self.is_authed set entry = call InsertRow row_dict key worksheet append entry entry return call GDataRow entry sheet=self deferred_save=deferred_save end function
def append(self, row_dict): """Add a row to the spreadsheet, returns the new row""" # TODO validate row_dict.keys() match # TODO check self.is_authed entry = self.client.InsertRow(row_dict, self.key, self.worksheet) self.feed.entry.append(entry) return GDataRow(entry, she...
Python
jtatman_500k
string Test suit of policies microserver. It checks that right policy messages are given. Tests run with pytest import pytest from import run as msv from import policies as pol decorator fixture function client begin set config at string TESTING = true with call test_client as client begin yield client end end functi...
""" Test suit of policies microserver. It checks that right policy messages are given. Tests run with pytest """ import pytest from .. import run as msv from .. import policies as pol @pytest.fixture def client(): msv.app.config['TESTING'] = True with msv.app.test_client() as client: yield c...
Python
zaydzuhri_stack_edu_python
function newrawobject data commdct key block=none defaultvalues=true begin string Make a new object for the given key. Parameters ---------- data : Eplusdata object Data dictionary and list of objects for the entire model. commdct : list of dicts Comments from the IDD file describing each item type in `data`. key : str...
def newrawobject(data, commdct, key, block=None, defaultvalues=True): """Make a new object for the given key. Parameters ---------- data : Eplusdata object Data dictionary and list of objects for the entire model. commdct : list of dicts Comments from the IDD file describing each it...
Python
jtatman_500k
import SubmarineGameManager import client import host set WELCOME_MESSAGE = string Welcome to a game of SUBMARINES set CHOICE = string Choose Host or Client: 1 or 2 set HOST = string 1 set CLIENT = string 2 set WRONG_INPUT = string Wrong input , try again class GameClient begin function menu self begin try begin print ...
import SubmarineGameManager import client import host WELCOME_MESSAGE = "Welcome to a game of SUBMARINES" CHOICE = "Choose Host or Client: 1 or 2\n" HOST = "1" CLIENT = "2" WRONG_INPUT = "Wrong input , try again" class GameClient: def menu(self): try: print(WELCOME_MESSAGE) subm...
Python
zaydzuhri_stack_edu_python
import sqlalchemy import pandas as pd function start begin set db_connection_str = string mysql+pymysql://root:0000@localhost/imdb set db_connection = call create_engine db_connection_str set conn = call connect set crew = read csv string title.crew.tsv sep=string low_memory=false print string crew 불러오기 완료 set name_ba...
import sqlalchemy import pandas as pd def start(): db_connection_str = 'mysql+pymysql://root:0000@localhost/imdb' db_connection = sqlalchemy.create_engine(db_connection_str) conn = db_connection.connect() crew = pd.read_csv('title.crew.tsv', sep='\t', low_memory=False) print("crew 불러오기 완료") n...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment descarga_youtube comment Copyright 2018 gnusyscamus <gnusyscamus@gnusyscamus-SVE14113ELW> from pytube import YouTube import base64 import time import urllib , urllib2 from lxml import etree from StringIO import StringIO from bs4 import BeautifulSoup as ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # descarga_youtube # # Copyright 2018 gnusyscamus <gnusyscamus@gnusyscamus-SVE14113ELW> from pytube import YouTube import base64 import time import urllib, urllib2 from lxml import etree from StringIO import StringIO from bs4 import BeautifulSoup as BS import base64...
Python
zaydzuhri_stack_edu_python
function test_no_install_metadata visualstudio tmp_path begin assert install_metadata is none end function
def test_no_install_metadata(visualstudio, tmp_path): assert visualstudio.install_metadata is None
Python
nomic_cornstack_python_v1
function _pad_x self x_val kernel_height kernel_width begin set tuple _ _ padding x_pad_shape = call _get_shapes shape kernel_height kernel_width set tuple _ in_height_pad in_width_pad _ = x_pad_shape set tuple pad_top pad_bot pad_left pad_right = padding set x_pad_val = if expression has attribute self string _pad_val...
def _pad_x(self, x_val, kernel_height, kernel_width): _, _, padding, x_pad_shape = self._get_shapes( x_val.shape, kernel_height, kernel_width) _, in_height_pad, in_width_pad, _ = x_pad_shape pad_top, pad_bot, pad_left, pad_right = padding x_pad_val = (np.ones(x_pad_shape) * self._pad_value ...
Python
nomic_cornstack_python_v1
function fetch_image begin set url = get args string image set req = call get_image_from_plex url set response = call make_response content set headers at string Content-Type = headers at string Content-Type return response end function
def fetch_image(): url = request.args.get('image') req = status.modules['plex'].get_image_from_plex(url) response = make_response(req.content) response.headers['Content-Type'] = req.headers['Content-Type'] return response
Python
nomic_cornstack_python_v1
from node import * comment A class implementing Multiset as a linked list. class Multiset begin function __init__ self begin string Produces a newly constructed empty Multiset. __init__: -> Multiset Field: _head points to the first node in the linked list set _head = none end function function empty self begin string C...
from node import * # A class implementing Multiset as a linked list. class Multiset: def __init__(self): """ Produces a newly constructed empty Multiset. __init__: -> Multiset Field: _head points to the first node in the linked list """ self._head = None def ...
Python
zaydzuhri_stack_edu_python
function merge arr start mid end begin set start2 = mid + 1 comment If the direct merge is already sorted if arr at mid <= arr at start2 begin return end comment Two pointers to maintain start comment of both arrays to merge while start <= mid and start2 <= end begin comment If element 1 is in right place if arr at sta...
def merge(arr, start, mid, end): start2 = mid + 1 # If the direct merge is already sorted if (arr[mid] <= arr[start2]): return # Two pointers to maintain start # of both arrays to merge while (start <= mid and start2 <= end): # If element 1 is in right place ...
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Jan 22 11:54:41 2019 @author: hchagrao This is a a script to sort list. set my_list = list 26 54 93 17 77 31 44 55 20 function find_max my_list begin set count = 0 for x in my_list begin if count == 0 begin set maximum = x end else if x >...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 22 11:54:41 2019 @author: hchagrao This is a a script to sort list. """ my_list =[26, 54, 93, 17, 77,31, 44, 55, 20] def find_max(my_list): count = 0 for x in my_list: if count == 0: maximum = x elif x > maximum:...
Python
zaydzuhri_stack_edu_python
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 and month == 2 begin print format string Month 2 in year {0} has 29 days year end else if month == 2 begin print format string Month 2 in year {0} has 28 days year end else if month in months_with_30_days begin print format string Month {0} in year {1} has 30 days...
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0) and month == 2: print("Month 2 in year {0} has 29 days".format(year)) elif month == 2: print("Month 2 in year {0} has 28 days".format(year)) elif month in months_with_30_days: print("Month {0} in year {1} has 30 days".format(month,year)) elif month...
Python
zaydzuhri_stack_edu_python
function convert_string_to_list string begin comment Remove leading and trailing whitespace set string = strip string comment Create an empty list to store the characters set characters = list comment Iterate over each character in the string for i in range length string begin comment Append the current character to t...
def convert_string_to_list(string): # Remove leading and trailing whitespace string = string.strip() # Create an empty list to store the characters characters = [] # Iterate over each character in the string for i in range(len(string)): # Append the current character to the list ...
Python
jtatman_500k
function parameter_chain self param begin if not _fitset begin return none end if is instance param str begin set paridx = _param_order at lower param end else begin set paridx = integer param if paridx < 0 or paridx > 5 begin raise call ValueError format string invalid parameter index {:d} paridx end end return flatte...
def parameter_chain(self, param): if not self._fitset: return None if isinstance(param, str): paridx = self._param_order[param.lower()] else: paridx = int(param) if paridx < 0 or paridx > 5: raise ValueError("invalid parameter ind...
Python
nomic_cornstack_python_v1
class CPYImmediate extends object begin function __init__ self begin call __init__ end function function run self cpu begin set byte_r = call immediate print string CPY memory byte read: %s % hexadecimal byte_r print string CPY register Y read: %s % hexadecimal y print string CPY processor status Carry read: %s % hexad...
class CPYImmediate(object): def __init__(self): super(CPYImmediate, self).__init__() def run(self, cpu): byte_r = cpu.immediate() print("CPY memory byte read: %s" % hex(byte_r)) print("CPY register Y read: %s" % hex(cpu.y)) print("CPY processor status Carry read: %s" % h...
Python
zaydzuhri_stack_edu_python
function vios_create context values transaction=none begin return call vios_create context values transaction=transaction end function
def vios_create(context, values, transaction=None): return IMPL.vios_create(context, values, transaction=transaction)
Python
nomic_cornstack_python_v1
function dropout_layer name_scope input_tensor keep_prob=0.5 begin comment TODO: is name_scope really needed? with call name_scope name_scope begin return call droupout input_tensor keep_prob end end function
def dropout_layer(name_scope, input_tensor, keep_prob=0.5): #TODO: is name_scope really needed? with tf.name_scope(name_scope): return tf.nn.droupout(input_tensor, keep_prob)
Python
nomic_cornstack_python_v1
function failover_target self begin return get pulumi self string failover_target end function
def failover_target(self) -> bool: return pulumi.get(self, "failover_target")
Python
nomic_cornstack_python_v1
function create_sansanito begin set sql = string --sql CREATE TABLE SANSANITO ( id number GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, poke_name nvarchar2(50) REFERENCES poyo (poke_name), type1 varchar2(50), type2 varchar2(50), hp_curr number, hp_max number, debuff varchar2(50) DEFAULT 'NONE' CHECK (debuff in ('ENVENE...
def create_sansanito(): sql = '''--sql CREATE TABLE SANSANITO ( id number GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, poke_name nvarchar2(50) REFERENCES poyo (poke_name), type1 varchar2(50), type2 varchar2(50), hp_curr number, hp_max number, debuff varch...
Python
nomic_cornstack_python_v1
comment This gets replaced by another version if another strategy is provided. function execute self begin print format string {} is used! name end function
def execute(self): # This gets replaced by another version if another strategy is provided. print("{} is used!".format(self.name))
Python
nomic_cornstack_python_v1
from color import Color from direction import Direction class Cell extends object begin function __init__ self row=none col=none boxes=none walls=none has_agent=false has_target=false begin comment Current row and column are optional set row = row set col = col comment Boxes are saved as a set of colors set boxes = if ...
from .color import Color from .direction import Direction class Cell(object): def __init__(self, row=None, col=None, boxes=None, walls=None, has_agent=False, has_target=False): # Current row and column are optional self.row = row self.col = col # Boxes are saved as a set of colors ...
Python
zaydzuhri_stack_edu_python
function line marker linestyle **kwargs begin call _plot params=dict string marker marker ; string linestyle linestyle keyword kwargs end function
def line(marker: str, linestyle: str, **kwargs) -> None: _plot(params={"marker": marker, "linestyle": linestyle}, **kwargs)
Python
nomic_cornstack_python_v1
import pytest from bs4 import BeautifulSoup from scraper import get_movie_list from test_rc.results import top_rated_movies_list , most_popular_movies_list function read_file_and_get_soup file_name begin set file_str = string with open file_name string r as file begin set file_str = read file end return call Beautiful...
import pytest from bs4 import BeautifulSoup from scraper import ( get_movie_list ) from test_rc.results import ( top_rated_movies_list, most_popular_movies_list ) def read_file_and_get_soup(file_name): file_str = '' with open(file_name, 'r') as file: file_str = file.read() return Be...
Python
zaydzuhri_stack_edu_python
function to_dict self begin set rv = dictionary payload or tuple set rv at string message = message if error_data begin set rv at string error_data = error_data end if status_message is not none begin set rv at string status = status_message end return rv end function
def to_dict(self): rv = dict(self.payload or ()) rv["message"] = self.message if self.error_data: rv["error_data"] = self.error_data if self.status_message is not None: rv["status"] = self.status_message return rv
Python
nomic_cornstack_python_v1
function string_bits string begin set result = string for i in range length string begin if i % 2 == 0 begin set result = result + string at i end end return result end function
def string_bits(string): result = ""; for i in range(len(string)): if(i % 2 == 0): result = result + string[i]; return result;
Python
zaydzuhri_stack_edu_python
async function get_followers db account start follow_type limit begin set account_id = await call _get_account_id db account set start_id = if expression start then await call _get_account_id db start else none set state = if expression follow_type == string ignore then tuple 2 3 else tuple 1 3 set seek = string if st...
async def get_followers(db, account: str, start: str, follow_type: str, limit: int): account_id = await _get_account_id(db, account) start_id = await _get_account_id(db, start) if start else None state = (2,3) if follow_type == 'ignore' else (1,3) seek = '' if start_id: seek = """AND hf.cre...
Python
nomic_cornstack_python_v1
function test_patch_hyperflex_server_model self begin pass end function
def test_patch_hyperflex_server_model(self): pass
Python
nomic_cornstack_python_v1
function get_forward_returns factor periods=none bundle=none begin if not bundle begin set bundle = call _get_bundle if not bundle begin set bundle = call get_default_bundle if not bundle begin raise call ValidationError string you must specify a bundle or set a default bundle end set bundle = bundle at string default_...
def get_forward_returns( factor: Union['pd.Series[Any]', 'pd.DataFrame'], periods: Union[Union[int, Literal['oc', 'co']], list[Union[int, Literal['oc', 'co']]]] = None, bundle: str = None, ) -> pd.DataFrame: if not bundle: bundle = _get_bundle() if not bundle: bundle = g...
Python
nomic_cornstack_python_v1
comment Code for insertion into a priority queue comment implemented as a binary tree comment Written by Jt for COMP9021 from binary_tree import * from math import log import copy set orders = list none set i = 0 class PriorityQueue extends BinaryTree begin function __init__ self begin call __init__ end function functi...
# Code for insertion into a priority queue # implemented as a binary tree # # Written by Jt for COMP9021 from binary_tree import * from math import log import copy orders=[None] i=0 class PriorityQueue(BinaryTree): def __init__(self): super().__init__() def insert(self, value): global i ...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict import csv import json import os from os.path import join from matplotlib import pyplot as plt from matplotlib.axes import Axes from user_utility import getDataset , saveFigureAsPNG , saveListAsTxt , saveDictAsTxt , saveLListAsCSV from ActiveDrivers import getRecentDrivers from Visua...
from collections import defaultdict import csv import json import os from os.path import join from matplotlib import pyplot as plt from matplotlib.axes import Axes from user_utility import getDataset, saveFigureAsPNG, saveListAsTxt, saveDictAsTxt, saveLListAsCSV from ActiveDrivers import getRecentDrivers from Visualis...
Python
zaydzuhri_stack_edu_python
function maxElementInMatrix I begin set width = list for i in range length I begin append width call width item I i end return index width max width end function
def maxElementInMatrix(I): width = [] for i in range(len(I)): width.append(interval.width(I.item(i))) return width.index(max(width))
Python
nomic_cornstack_python_v1
string Sorts an array from a file and prints intermediate steps + the sorted array import math from typing import List set FILE = string data.txt set MY_ARRAY = list try begin with open FILE string r as f begin for line in f begin append MY_ARRAY integer line end end end except ValueError begin print string Error in f...
"""Sorts an array from a file and prints intermediate steps + the sorted array""" import math from typing import List FILE = "data.txt" MY_ARRAY = [] try: with open(FILE, 'r') as f: for line in f: MY_ARRAY.append(int(line)) except ValueError: print("Error in file, couldnt parse to int, ex...
Python
zaydzuhri_stack_edu_python
comment Import the relevant libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression comment Load the dataset set data = read csv string posts.csv comment Preprocess the data set data at string is_recent = data at string date > now - time delta...
# Import the relevant libraries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # Load the dataset data = pd.read_csv('posts.csv') # Preprocess the data data['is_recent'] = data['date'] > (pd.datetime.now() - pd.Timedelta(days=1)) # Create th...
Python
flytech_python_25k
function default_options self begin set start_frame = integer call playbackOptions query=true animationStartTime=true set end_frame = integer call playbackOptions query=true animationEndTime=true return dict string cameras false ; string smoothingGroups false ; string hardEdges false ; string tangents false ; string sm...
def default_options(self): start_frame = int(cmds.playbackOptions(query=True, animationStartTime=True)) end_frame = int(cmds.playbackOptions(query=True, animationEndTime=True)) return { "cam...
Python
nomic_cornstack_python_v1
function test_create_reverse self begin assert equal url string /ordomatic/calendars/create/ end function
def test_create_reverse(self): self.assertEqual(self.url, '/ordomatic/calendars/create/')
Python
nomic_cornstack_python_v1
function reorderList self head begin set tuple prev slow fast = tuple none head head while fast and next begin set tuple prev slow fast = tuple slow next next end if not prev begin return head end comment reverse 2nd helf function reverse root begin set tuple node nxt = tuple root next set next = none while node and nx...
def reorderList(self, head: Optional[ListNode]) -> None: prev, slow, fast = None, head, head while fast and fast.next: prev, slow, fast = slow, slow.next, fast.next.next if not prev: return head # reverse 2nd helf def reverse(root): node, nxt = ...
Python
nomic_cornstack_python_v1
import os comment encoding: utf-8 comment Formas literais de escrever números comment int print 1 comment float print 1.0 comment também float print 1.0 comment número complexo print 1 + 2j comment Funções embutidas print integer 1.0 print integer string 9 print decimal 1 print decimal string 9.2 print decimal string -...
import os #encoding: utf-8 #Formas literais de escrever números print(1)#int print(1.0)#float print(1.)#também float print(1+2j)#número complexo #Funções embutidas print(int(1.0)) print(int('9')) print(float(1)) print(float('9.2')) print(float('-inf')) print(float('+inf')) print(float('nan')) print(complex('1,2')) ...
Python
zaydzuhri_stack_edu_python
function combine_std n mean std begin string Compute combined standard deviation for subsets. See https://stats.stackexchange.com/questions/43159/ how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances- mean for derivation. Parameters ---------- n : numpy array of sample sizes mean : numpy array of ...
def combine_std(n, mean, std): """Compute combined standard deviation for subsets. See https://stats.stackexchange.com/questions/43159/\ how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-\ mean for derivation. Parameters ---------- n : numpy array of sampl...
Python
jtatman_500k
function deep_add to_add start=0 begin global sum global data_type set data_type = Decimal set sum = none call d_deep_add to_add call d_deep_add start if data_type == timedelta begin return time delta sum end return sum end function
def deep_add(to_add, start=0): global sum global data_type data_type = Decimal sum = None d_deep_add(to_add) d_deep_add(start) if data_type == timedelta: return timedelta(sum) return sum
Python
nomic_cornstack_python_v1
import random import sys set list_words = list string honour string object string sustained string reasonable set word_choice = random choice list_words set hidden_word = list string - * length word_choice set used_letters = list set lives = 8 comment menu print string H A N G M A N set authorization = string while a...
import random import sys list_words = ['honour', 'object', 'sustained', 'reasonable'] word_choice = random.choice(list_words) hidden_word = list('-' * len(word_choice)) used_letters = [] lives = 8 #menu print("H A N G M A N") authorization = '' while authorization != 'ok': menu = input('Type "play" to play the ga...
Python
zaydzuhri_stack_edu_python
import requests , bs4 , pyperclip comment smiles2clip.py scrapes wikipedia for the smiles code of a given compound and copies it to your clipboard. print string input compound name set compound = input set res = get requests string https://en.wikipedia.org/wiki/ + compound call raise_for_status set wikiSoup = call Beau...
import requests, bs4, pyperclip # smiles2clip.py scrapes wikipedia for the smiles code of a given compound and copies it to your clipboard. print('input compound name') compound = input() res = requests.get('https://en.wikipedia.org/wiki/'+ compound) res.raise_for_status() wikiSoup = bs4.BeautifulSoup(res.text, "lxm...
Python
zaydzuhri_stack_edu_python
function args_contained_in a b begin return all list comprehension bi in a for bi in b end function
def args_contained_in(a, b): return all([bi in a for bi in b])
Python
nomic_cornstack_python_v1
function getMax a b c begin if a > b and a > c begin return a end else if b > a and b > c begin return b end else begin return c end end function print call getMax 2 5 7
def getMax(a,b,c): if a > b and a > c: return a elif b > a and b > c: return b else: return c print(getMax(2, 5, 7))
Python
flytech_python_25k
function get_day_of_week self begin return call isoweekday end function
def get_day_of_week(self) -> int: return self.date.isoweekday()
Python
nomic_cornstack_python_v1
comment 1 function mxel l begin set m = list for i in l begin set n = max i append m tuple n i sort m reverse m end print m end function comment 2 function mean *a begin set q = 0 for i in a begin set q = q + i end set z = q / length a print z end function call mxel list list 1 2 list 1 - 1 list 5 8 list - 4 - 2 list ...
#1 def mxel(l): m = [] for i in l: n = max(i) m.append((n, i)) m.sort() m.reverse() print(m) #2 def mean(*a): q = 0 for i in a: q += i z = q/len(a) print(z) mxel([[1,2],[1,-1],[5,8],[-4,-2],[4,3]]) mean(1,2,3)
Python
zaydzuhri_stack_edu_python
function _marshal_json self extras=tuple begin string Marshal various policies into json str/bytes. set policies = policies at slice : : extend policies extras if _content_length_range begin append policies list string content-length-range + list _content_length_range end set policy_stmt = dict string expiration str...
def _marshal_json(self, extras=()): """ Marshal various policies into json str/bytes. """ policies = self.policies[:] policies.extend(extras) if self._content_length_range: policies.append(['content-length-range'] + list(self._conte...
Python
jtatman_500k
function convolutional_norm f begin comment """ original """ comment fs = t.sqrt(f ** 2 + 1e-8) # ensure numerical stability comment l2fs = t.sqrt(t.sum(fs ** 2, axis=0)) # l2 norm of example dimension comment nfs = fs / l2fs.dimshuffle('x', 0, 1, 2) # normalize non-example dimensions comment l2fn = t.sqrt(t.sum(nfs **...
def convolutional_norm(f): # """ original """ # fs = t.sqrt(f ** 2 + 1e-8) # ensure numerical stability # l2fs = t.sqrt(t.sum(fs ** 2, axis=0)) # l2 norm of example dimension # nfs = fs / l2fs.dimshuffle('x', 0, 1, 2) # normalize non-example dimensions # l2fn =...
Python
nomic_cornstack_python_v1
from pymf import BNMF import pandas as pd import numpy as np set K = 100 comment Read in ratings data set ratings = read csv string ./data/1M/ratings.dat sep=string :: engine=string python set columns = list string userId string movieId string rating string timestamp comment Pivot into matrix set rm = call pivot index=...
from pymf import BNMF import pandas as pd import numpy as np K = 100 # Read in ratings data ratings = pd.read_csv("./data/1M/ratings.dat", sep='::', engine='python') ratings.columns = ['userId', 'movieId', 'rating', 'timestamp'] # Pivot into matrix rm = ratings.pivot(index="movieId", columns="userId", values="rating...
Python
zaydzuhri_stack_edu_python
function main Year begin set remainder_1 = Year % 400 set remainder_2 = Year % 4 set remainder_3 = Year % 100 if remainder_1 and remainder_2 != 0 begin print Year string is not a leap year. end else if remainder_2 == 0 and remainder_3 == 0 begin print Year string is not a leap year. end else if remainder_1 or remainder...
def main(Year): remainder_1 = Year%400 remainder_2 = Year%4 remainder_3 = Year%100 if remainder_1 and remainder_2 !=0: print(Year,"is not a leap year.") elif remainder_2 == 0 and remainder_3 == 0: print(Year,"is not a leap year.") elif remainder_1 or remainde...
Python
zaydzuhri_stack_edu_python
function _on_nid_changed self nid col begin comment The node data may not have been set up for the nid yet. Ignore it if comment it hasn't. try begin set tuple _ node obj = call _get_node_data nid end except Exception begin return end set new_label = call unicode call text col set old_label = call get_label obj if new_...
def _on_nid_changed(self, nid, col): # The node data may not have been set up for the nid yet. Ignore it if # it hasn't. try: _, node, obj = self._get_node_data(nid) except Exception: return new_label = unicode(nid.text(col)) old_label = node.get...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Aug 11 08:24:48 2018 @author: ltengy comment http连接需要用到 import urllib comment 解析网页数据用 import json comment 读取剪切板数据 import win32clipboard as wc comment 获得当前鼠标信息 from pymouse import PyMouse comment 自带的GUI库,生成文本框 import Tkinter comment 定时器,减少占用 import time import win32con...
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 08:24:48 2018 @author: ltengy """ import urllib #http连接需要用到 import json #解析网页数据用 import win32clipboard as wc #读取剪切板数据 from pymouse import PyMouse #获得当前鼠标信息 import Tkinter #自带的GUI库,生成文本框 import time #定时器,减少占用 import win32con currentData='' def trans...
Python
zaydzuhri_stack_edu_python
comment from <FileName> import * comment import unittest comment class TestName(unittest.TestCase): comment # @unittest.SkipTest comment def test_name_0(self): comment genome = '' comment output = Func() comment a_ints = ' '.join([str(x) for x in output]) comment a_words = ' '.join(output) comment b = '' comment self.a...
# from <FileName> import * # import unittest # # # class TestName(unittest.TestCase): # # @unittest.SkipTest # def test_name_0(self): # genome = '' # output = Func() # a_ints = ' '.join([str(x) for x in output]) # a_words = ' '.join(output) # b = '' # self.assertE...
Python
zaydzuhri_stack_edu_python
function map_source_maf_id_to_target_intervals source_maf_ids target_bed_files begin set return_dict = dictionary comment Consistency checks assert is instance source_maf_ids list assert is instance target_bed_files list assert length source_maf_ids == length set source_maf_ids assert length source_maf_ids == length ta...
def map_source_maf_id_to_target_intervals(source_maf_ids, target_bed_files): return_dict = dict() # Consistency checks assert isinstance(source_maf_ids, list) assert isinstance(target_bed_files, list) assert len(source_maf_ids) == len(set(source_maf_ids)) assert len(source_maf_ids) == len(targ...
Python
nomic_cornstack_python_v1
function load type_tuple into=none begin set type_dict = dict call new type_dict *type_tuple set deposit = if expression into is not none and is instance into dict then into else dict for reified_type in values type_dict begin set deposit at __name__ = reified_type end return deposit end function
def load(type_tuple, into=None): type_dict = {} TypeFactory.new(type_dict, *type_tuple) deposit = into if (into is not None and isinstance(into, dict)) else {} for reified_type in type_dict.values(): deposit[reified_type.__name__] = reified_type return deposit
Python
nomic_cornstack_python_v1
try begin set t = integer t print string Invalid Input end except any begin set res = string set i = true for x in t begin if x == string G begin set res = res + string C end else if x == string C begin set res = res + string G end else if x == string T begin set res = res + string A end else if x == string A begin se...
try: t=int(t) print("Invalid Input") except: res="" i=True for x in t: if x=="G": res+="C" elif x=="C": res+="G" elif x=="T": res+="A" elif x=="A": res+="U" else: print("Invalid Input") i=...
Python
zaydzuhri_stack_edu_python
string https://leetcode.com/problems/pascals-triangle/ Easy Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] from typing imp...
""" https://leetcode.com/problems/pascals-triangle/ Easy Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] """ from ty...
Python
zaydzuhri_stack_edu_python
function als_results ofname p_dict obs_dict ylims=none begin comment Altimeter data!!!!!!!! set Alt05 = obs_dict at string Alt05 set Alt04 = obs_dict at string Alt04 set Alt03 = obs_dict at string Alt03 comment wave data set Adopp_35 = obs_dict at string Adopp_35 set AWAC6m = obs_dict at string AWAC6m set AWAC8m = obs_...
def als_results(ofname, p_dict, obs_dict, ylims=None): # Altimeter data!!!!!!!! Alt05 = obs_dict['Alt05'] Alt04 = obs_dict['Alt04'] Alt03 = obs_dict['Alt03'] # wave data Adopp_35 = obs_dict['Adopp_35'] AWAC6m = obs_dict['AWAC6m'] AWAC8m = obs_dict['AWAC8m'] # get rid of this and i...
Python
nomic_cornstack_python_v1
import __includes__ import os import sys import time import warnings import numpy as np from scipy import io import matplotlib.pyplot as plt from dynamics.ode_solver import OdeIntegration from dynamics.dmd_solver import DMD_integration comment warnings.filterwarnings("ignore") seed 123 function f1 x t begin return 1.0 ...
import __includes__ import os import sys import time import warnings import numpy as np from scipy import io import matplotlib.pyplot as plt from dynamics.ode_solver import OdeIntegration from dynamics.dmd_solver import DMD_integration # warnings.filterwarnings("ignore") np.random.seed(123) def f1(x,t): return 1. / n...
Python
zaydzuhri_stack_edu_python
comment @Time: 2020/3/21 23:29 comment @Author: R.Jian comment @Note: 随从类 class SuiChongBase begin function __init__ self attach blood ishand begin set attach = attach set blood = blood set isattached = false set ishand = ishand end function function be_attached self attach begin set blood = blood - attach if blood < 1...
# @Time: 2020/3/21 23:29 # @Author: R.Jian # @Note: 随从类 class SuiChongBase(): def __init__(self,attach,blood,ishand): self.attach = attach self.blood = blood self.isattached = False self.ishand = ishand def be_attached(self,attach): self.blood = self.blood-attach ...
Python
zaydzuhri_stack_edu_python
function __init__ self batch_size num_context x_size=1 y_size=1 l1_scale=0.4 sigma_scale=1.0 random_kernel_parameters=true testing=false begin set _batch_size = batch_size set _num_context = num_context set _x_size = x_size set _y_size = y_size set _l1_scale = l1_scale set _sigma_scale = sigma_scale set _random_kernel_...
def __init__(self, batch_size, num_context, x_size=1, y_size=1, l1_scale=0.4, sigma_scale=1.0, random_kernel_parameters=True, testing=False): self._batch_size = batch_size ...
Python
nomic_cornstack_python_v1
function ccbill_allowed_types self ccbill_allowed_types begin set _ccbill_allowed_types = ccbill_allowed_types end function
def ccbill_allowed_types(self, ccbill_allowed_types): self._ccbill_allowed_types = ccbill_allowed_types
Python
nomic_cornstack_python_v1
string Created on Nov 16, 2016 @author: menon import turtle string This recursive function draw a binary tree. To understand recursion you have to first understand recursion :D function binaryTree branch_length_of_tree tree begin if branch_length_of_tree > 5 begin if branch_length_of_tree <= 30 begin comment this give ...
''' Created on Nov 16, 2016 @author: menon ''' import turtle ''' This recursive function draw a binary tree. To understand recursion you have to first understand recursion :D ''' def binaryTree(branch_length_of_tree, tree): if branch_length_of_tree > 5: if branch_length_of_tree <= 30: ...
Python
zaydzuhri_stack_edu_python
function get_network_info args begin set config_drive = join path root string mnt/config set network_info_file = string %s/openstack/latest/network_info.json % config_drive set network_data_file = string %s/openstack/latest/network_data.json % config_drive set vendor_data_file = string %s/openstack/latest/vendor_data.j...
def get_network_info(args): config_drive = os.path.join(args.root, 'mnt/config') network_info_file = '%s/openstack/latest/network_info.json' % config_drive network_data_file = '%s/openstack/latest/network_data.json' % config_drive vendor_data_file = '%s/openstack/latest/vendor_data.json' % config_drive ...
Python
nomic_cornstack_python_v1
comment Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. comment Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 comment ou em galões de 3,6 litros, que c...
# Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. # Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 # ou em galões de 3,6 litros, que custam R$ 25,00. ...
Python
zaydzuhri_stack_edu_python
function test_RealPred_copy self begin from copy import copy , deepcopy set the = call RealPred string the string q set cat = call RealPred string cat string n string 1 set the_copy = copy the set the_deep = deep copy the set cat_copy = copy cat set cat_deep = deep copy cat assert equal the the_copy assert equal the th...
def test_RealPred_copy(self): from copy import copy, deepcopy the = RealPred('the','q') cat = RealPred('cat','n','1') the_copy = copy(the) the_deep = deepcopy(the) cat_copy = copy(cat) cat_deep = deepcopy(cat) self.assertEqual(the, the_copy) self.a...
Python
nomic_cornstack_python_v1
function setTransponder self txpdr modNumber begin comment self.setInputSource("PN", modNumber) #Input set to Load for testing of SLG class. Default should be seto to PN23 for mods 1-16 and LOAD for 17-32 since the SLG is not able to set data on mods higher than 16. comment self.setMode(txpdr.getMode(), modNumber) set ...
def setTransponder(self, txpdr, modNumber): #self.setInputSource("PN", modNumber) #Input set to Load for testing of SLG class. Default should be seto to PN23 for mods 1-16 and LOAD for 17-32 since the SLG is not able to set data on mods higher than 16. # self.setMode(txpdr.getMode(), modNumber) bcstd = txpdr.ge...
Python
nomic_cornstack_python_v1
function number_of_capital_deputies self number_of_capital_deputies begin set _number_of_capital_deputies = number_of_capital_deputies end function
def number_of_capital_deputies(self, number_of_capital_deputies): self._number_of_capital_deputies = number_of_capital_deputies
Python
nomic_cornstack_python_v1
comment ASSIGNMENT NAME: FINAL comment NAME: Chance Cardona comment EMAIL: ccardona@mymail.mines.edu comment DATE: 12/9/18 comment DESCRIPTION: Finds number of lychrel numbers below a number r. comment OTHER NOTES: (if applicable) import numpy as np function palindrome n begin set strIn = string n set strRev = strIn at...
# ASSIGNMENT NAME: FINAL # NAME: Chance Cardona # EMAIL: ccardona@mymail.mines.edu # DATE: 12/9/18 # DESCRIPTION: Finds number of lychrel numbers below a number r. # OTHER NOTES: (if applicable) import numpy as np def palindrome(n): strIn = str(n) strRev = strIn[::-1] if strIn == strRev: return...
Python
zaydzuhri_stack_edu_python
import logging import os import zmq call basicConfig level=DEBUG format=string %(asctime)s : %(levelname)s : %(message)s set log = call getLogger set ctx = call Context class Zmq begin function send self thing begin info string send %s thing return call send_json thing end function function receive self begin return ca...
import logging import os import zmq logging.basicConfig(level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s') log = logging.getLogger() ctx = zmq.Context() class Zmq: def send(self, thing): log.info("send %s", thing) return self.socket.send_json(thing) def receive(self)...
Python
zaydzuhri_stack_edu_python
function isValidSent s d begin set i = 0 set j = 0 while i != length s begin if s at slice i : j : in d begin set i = j end if j >= length s begin set i = i + 1 set j = i end set j = j + 1 end if i == j - 1 begin return true end else begin return false end end function set d = list string apple,best,it,of,the,times,wa...
def isValidSent(s, d): i = 0 j = 0 while(i!= len(s)): if(s[i:j] in d): i=j if(j>=len(s)): i = i +1 j=i j = j + 1 if(i==j-1): return True else: return False d = ["apple,best,it,of,the,times,was"]; print(isValidSent("itwasthebestoftimes", d))
Python
zaydzuhri_stack_edu_python
function test_netCDF_to_memory self begin set f = call example_field 4 comment on non-compressed array call to_memory compress string indexed_contiguous inplace=true comment on compressed array call to_memory end function
def test_netCDF_to_memory(self): f = cfdm.example_field(4) f.data.to_memory() # on non-compressed array f.compress("indexed_contiguous", inplace=True) f.data.to_memory() # on compressed array
Python
nomic_cornstack_python_v1
function optionHandler_output self path begin set outputfile = path end function
def optionHandler_output(self, path): self.outputfile = path
Python
nomic_cornstack_python_v1
function get_lat self begin return string lat end function
def get_lat(self): return str(self.lat)
Python
nomic_cornstack_python_v1
import sys set input = readline comment ------------- set S = input comment ------------- set S = list S set count = count S string o print integer 700 + 100 * count
import sys input = sys.stdin.readline #------------- S = input() #------------- S = list(S) count = S.count("o") print(int(700+100*count))
Python
zaydzuhri_stack_edu_python
function harmRec n begin if n == 1 begin return 1 end else begin return 1 / n + call harmRec n - 1 end end function print call harmRec 5
def harmRec(n): if n == 1: return 1 else: return (1/n)+harmRec(n-1) print(harmRec(5))
Python
zaydzuhri_stack_edu_python
import pandas as pd , numpy as np , time import os , dotenv from dotenv import load_dotenv call load_dotenv comment import matplotlib.pyplot as plt, seaborn as sn comment from decimal import * comment Import robin-stocks module import robin_stocks from robin_stocks import * comment robin_stocks documentation: http://ww...
import pandas as pd, numpy as np, time import os, dotenv from dotenv import load_dotenv load_dotenv() #import matplotlib.pyplot as plt, seaborn as sn #from decimal import * ##Import robin-stocks module import robin_stocks from robin_stocks import * ##robin_stocks documentation: http://www.robin-stocks.com/en/latest/r...
Python
zaydzuhri_stack_edu_python
function read_attr_type_file begin with open attr_type_file_path string r as f begin set content = read lines f end comment Strip lines of newline/return characters in csv file set content = list comprehension strip x string for x in content comment Generate dictionary of types and their count set attribute_type_dict =...
def read_attr_type_file(): with open(args.attr_type_file_path, 'r') as f: content = f.readlines() # Strip lines of newline/return characters in csv file content = [x.strip(' \t\n\r') for x in content] # Generate dictionary of types and their count attribute_type_dict = {} for item in c...
Python
nomic_cornstack_python_v1
comment solution comment 1. 각 노드당 연결되어 있는 노드들을 리스트로 표현해준다 comment 2. deque를 이용하여 1번 노드에서 빼내어 가장 멀리 떨어진 노드들을 찾고 comment 3. 뺴낼 때마다 count를 세준다 from collections import deque function solution n edge begin comment 먼저 인덱스마다 1부터 n까지 edge에서 연결된 것을 할당해준다 comment depth에 대한 문제 comment num[depth]와 같이 해당 인덱스에 depth 넘버를 기재 comment n...
# solution # 1. 각 노드당 연결되어 있는 노드들을 리스트로 표현해준다 # 2. deque를 이용하여 1번 노드에서 빼내어 가장 멀리 떨어진 노드들을 찾고 # 3. 뺴낼 때마다 count를 세준다 from collections import deque def solution(n, edge): # 먼저 인덱스마다 1부터 n까지 edge에서 연결된 것을 할당해준다 # depth에 대한 문제 # num[depth]와 같이 해당 인덱스에 depth 넘버를 기재 # num[i]=depth? # 다음 노드가 있으면 depth를 증가...
Python
zaydzuhri_stack_edu_python
comment 定义类,实现字符串逆序 set str = string abcdte print str at slice : : - 1
# 定义类,实现字符串逆序 str = 'abcdte' print(str[::-1])
Python
zaydzuhri_stack_edu_python
function check_queens cols begin set board = call number_of_conflicts cols for i in range 0 length cols begin if board at i at cols at i != 0 begin return false end end return true end function function number_of_conflicts current_state begin set n = length current_state comment create board set board = dict for i in ...
def check_queens(cols): board = number_of_conflicts(cols) for i in range(0, len(cols)): if board[i][cols[i]] != 0: return False return True def number_of_conflicts(current_state): n = len(current_state) # create board board = {} for i in range(0, n): board[i] = list({}) for k in range(0, n): board...
Python
zaydzuhri_stack_edu_python
function is_devops_root_dir devops_home begin for subdir in list string bin string roles string vars begin if not is directory path join path devops_home subdir begin return false end end return is file path join path devops_home string ansible.cfg end function
def is_devops_root_dir(devops_home): for subdir in ['bin', 'roles', 'vars']: if not os.path.isdir(os.path.join(devops_home, subdir)): return False return os.path.isfile(os.path.join(devops_home, 'ansible.cfg'))
Python
nomic_cornstack_python_v1
function set_detailed_logs detailed begin global shell_handler set color = call has_color_support stdout set formatter = if expression detailed then call DetailedFormatter color else call CustomFormatter color call setFormatter formatter end function
def set_detailed_logs(detailed): global shell_handler color = has_color_support(sys.stdout) formatter = DetailedFormatter(color) \ if detailed else CustomFormatter(color) shell_handler.setFormatter(formatter)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- import logging call basicConfig set logger = call getLogger call setLevel INFO import os import subprocess import dataset import tqdm import deco decorator concurrent function read_pdf_disc discurso_file pres_dir disc_dir disc_file begin comment print os.getpid() s...
#!/usr/bin/python # -*- coding: utf-8 -*- import logging logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) import os import subprocess import dataset import tqdm import deco @deco.concurrent def read_pdf_disc(discurso_file, pres_dir, disc_dir, disc_file): # print os.getpid() o...
Python
zaydzuhri_stack_edu_python
function class_str_to_index self obj_label begin if label in classes begin return index classes label + 1 end raise call ValueError format string Invalid class string {}, not in {} label classes end function
def class_str_to_index(self, obj_label: EnnosObjectLabel): if obj_label.label in self.dataset_config.classes: return self.dataset_config.classes.index(obj_label.label) + 1 raise ValueError('Invalid class string {}, not in {}'.format(obj_label.label, self.dataset_config.classes))
Python
nomic_cornstack_python_v1