code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait set driver = ca...
import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait driver = webd...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder , OneHotEncoder from sklearn.preprocessing import StandardScaler from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from bokeh.plot...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder,OneHotEncoder from sklearn.preprocessing import StandardScaler from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from bokeh.plotti...
Python
zaydzuhri_stack_edu_python
function _latex_item_to_string item escape=false post_convert=none begin if has attribute item string dumps begin set s = dumps end else begin set s = string item if escape begin set s = call escape_latex s end end if post_convert begin return call post_convert s end return s end function
def _latex_item_to_string(item, escape=False, post_convert=None): if hasattr(item, 'dumps'): s = item.dumps() else: s = str(item) if escape: s = escape_latex(s) if post_convert: return post_convert(s) return s
Python
nomic_cornstack_python_v1
async function test_add_new_binary_sensor_ignored hass aioclient_mock mock_deconz_websocket begin set sensor = dict string name string Presence sensor ; string type string ZHAPresence ; string state dict string presence false ; string config dict string on true ; string reachable true ; string uniqueid string 00:00:00:...
async def test_add_new_binary_sensor_ignored( hass, aioclient_mock, mock_deconz_websocket ): sensor = { "name": "Presence sensor", "type": "ZHAPresence", "state": {"presence": False}, "config": {"on": True, "reachable": True}, "uniqueid": "00:00:00:00:00:00:00:00-00", ...
Python
nomic_cornstack_python_v1
function get_2d_markers_linearized self component_info=none data=none component_position=none index=none begin return call _get_2d_markers data component_info component_position index=index end function
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): return self._get_2d_markers( data, component_info, component_position, index=index )
Python
nomic_cornstack_python_v1
function test_config_defaults self begin set config = call parser MOCK_CONFIG_ONLY_DEFAULTS assert true config at string local_ip == string 127.0.0.1 assert true config at string local_port == 0 assert true config at string event_batch_size == 100 assert true config at string workers == 2 end function
def test_config_defaults(self): config = parser(MOCK_CONFIG_ONLY_DEFAULTS) self.assertTrue(config['local_ip'] == "127.0.0.1") self.assertTrue(config['local_port'] == 0) self.assertTrue(config['event_batch_size'] == 100) self.assertTrue(config['workers'] == 2)
Python
nomic_cornstack_python_v1
import numpy as np import csv import matplotlib.pyplot as plt from matplotlib import cm import matplotlib.colors as colors import scipy.stats as stats from scipy.stats import poisson comment from scipy.stats import gamma from scipy.stats import nbinom from numpy import log as ln import statsmodels.api as sm from dateti...
import numpy as np import csv import matplotlib.pyplot as plt from matplotlib import cm import matplotlib.colors as colors import scipy.stats as stats from scipy.stats import poisson # from scipy.stats import gamma from scipy.stats import nbinom from numpy import log as ln import statsmodels.api as sm from d...
Python
zaydzuhri_stack_edu_python
string 编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x, x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可, 其不需要被置于左右两部分之间。 示例: 输入: head = 3->5->8->5->10->2->1, x = 5 输出: 3->1->2->10->5->5->8 class ListNode begin function __init__ self x begin set val = x set next = none end function end class set head = call ListNode 1...
""" 编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x, x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可, 其不需要被置于左右两部分之间。 示例: 输入: head = 3->5->8->5->10->2->1, x = 5 输出: 3->1->2->10->5->5->8 """ class ListNode: def __init__(self, x): self.val = x self.next = None head = ListNode(1) head.next = ListNod...
Python
zaydzuhri_stack_edu_python
set n1 = integer input string Digite um número set n2 = integer input string Digite outro número set soma = n1 + n2 print string A soma entre os números é soma
n1 = int(input('Digite um número ')) n2 = int(input('Digite outro número ')) soma = n1 + n2 print('A soma entre os números é', soma)
Python
zaydzuhri_stack_edu_python
function __upgrade_image_format self progtrack allow_unprivileged=false begin try begin comment Ensure Image directory structure is valid. call mkdirs end except PermissionsException as e begin if not allow_unprivileged begin raise end comment An unprivileged user is attempting to use the comment new client with an old...
def __upgrade_image_format(self, progtrack, allow_unprivileged=False): try: # Ensure Image directory structure is valid. self.mkdirs() except apx.PermissionsException as e: if not allow_unprivileged: ...
Python
nomic_cornstack_python_v1
string Unit test for main.py import os import sys set main_path = join path string .. string src string app append path main_path import main import unittest class KnownValues extends TestCase begin function testDisplayNameKnownValues self begin string displayName should give knows result set name = string Jean set exp...
"""Unit test for main.py""" import os import sys main_path = os.path.join('..','src','app') sys.path.append(main_path) import main import unittest class KnownValues(unittest.TestCase): def testDisplayNameKnownValues(self): """displayName should give knows result""" name = "Jean" expected_r...
Python
zaydzuhri_stack_edu_python
function get_authorization_url self redirect_url state scope=none params=none begin comment type: (Text, Text, Optional[Iterable[Text]], Optional[Dict[Text, Text]]) -> Text comment type: Iterable[Text] set _scope = scope or list comment type: Dict[Text, Text] set _params = params or dict update _params dict string cl...
def get_authorization_url(self, redirect_url, state, scope=None, params=None): # type: (Text, Text, Optional[Iterable[Text]], Optional[Dict[Text, Text]]) -> Text _scope = scope or [] # type: Iterable[Text] _params = params or {} # type: Dict[Text, Text] _params.update({ 'c...
Python
nomic_cornstack_python_v1
function create_instance c_instance begin return call Launchpad c_instance end function
def create_instance(c_instance): return Launchpad(c_instance)
Python
nomic_cornstack_python_v1
function string_to_array args begin set a = list args set answer = list set word = string for arg in args begin if not arg == string begin set word = word + arg end else begin append answer word set word = string end end append answer word return answer end function comment https://www.codewars.com/kata/57e76bc428d...
def string_to_array(args): a = list(args) answer = [] word = '' for arg in args: if not arg == ' ': word += arg else: answer.append(word) word = '' answer.append(word) return answer # https://www.codewars.com/kata/57e76bc428d6fbc2d500036d
Python
zaydzuhri_stack_edu_python
import pandas as pd import os from quant.param.param import Parameter from WindPy import w start w class StockFactorFileDfc extends object begin string 读取自己的股票因子数据 get_barra_risk_factor_dfc() function __init__ self begin pass end function function get_alpha_factor_dfc_file self factor_name begin set param_path = call g...
import pandas as pd import os from quant.param.param import Parameter from WindPy import w w.start() class StockFactorFileDfc(object): """ 读取自己的股票因子数据 get_barra_risk_factor_dfc() """ def __init__(self): pass def get_alpha_factor_dfc_file(self, factor_name): param_path...
Python
zaydzuhri_stack_edu_python
function calcularTotal self begin set subtotales = list for row in range 0 call rowCount begin append subtotales decimal call text end return sum subtotales end function
def calcularTotal(self): subtotales=[] for row in range(0,self.tableNC.rowCount()): subtotales.append(float(self.tableNC.item(row,2).text())) return sum(subtotales)
Python
nomic_cornstack_python_v1
function permute input *axis begin set ndim = call rank input set perm = call check_transpose_axis axis ndim return permute F input perm end function
def permute(input, *axis): ndim = F.rank(input) perm = validator.check_transpose_axis(axis, ndim) return F.permute(input, perm)
Python
nomic_cornstack_python_v1
function handle_rich_comp_not_implemented begin if is_py2 begin raise call TypeError end else begin return NotImplemented end end function
def handle_rich_comp_not_implemented(): if is_py2: raise TypeError() else: return NotImplemented
Python
nomic_cornstack_python_v1
comment Compute the depth of a list of lists set depth = lambda list_ -> is instance list_ list and max map depth list_ + 1 comment Flatten a list of lists function flatten list_ begin set flattened = list_ while is instance flattened at 0 list begin set flattened = list comprehension item for sublist in flattened for ...
# Compute the depth of a list of lists depth = lambda list_: isinstance(list_, list) and max(map(depth, list_)) + 1 # Flatten a list of lists def flatten(list_): flattened = list_ while isinstance(flattened[0], list): flattened = [item for sublist in flattened for item in sublist] return flattened ...
Python
zaydzuhri_stack_edu_python
function do_debug self arg begin call interact none none __dict__ end function
def do_debug(self, arg): code.interact(None, None, self.__dict__)
Python
nomic_cornstack_python_v1
from KnowledgeBase import KnowledgeBase function main begin string Driver Method set kb = call KnowledgeBase print string ====================================== print string Looking for { the_character at string Name } . print string { the_character at string Name } looks like this: { the_character } print string The p...
from KnowledgeBase import KnowledgeBase def main(): """ Driver Method """ kb = KnowledgeBase() print("======================================") print(f"Looking for {kb.the_character['Name']}.") print(f"{kb.the_character['Name']} looks like this: {kb.the_character}") print("The popu...
Python
zaydzuhri_stack_edu_python
comment number of test cases set tst = integer input comment iterating over test cases for i in range tst begin comment size of the array set size = integer input comment heights of the columns set arr = list map int split input comment p iterates over the array, direction is a boolean specifying whether we are going u...
#number of test cases tst = int(input()) #iterating over test cases for i in range(tst): #size of the array size = int(input()) #heights of the columns arr = list(map(int, input().split())) #p iterates over the array, direction is a boolean specifying whether we are going up (true) or down (false) ...
Python
zaydzuhri_stack_edu_python
function _dict_to_ints strdict begin return dictionary comprehension _k : call _to_int _attr for tuple _k _attr in items strdict end function
def _dict_to_ints(strdict): return {_k: _to_int(_attr) for _k, _attr in strdict.items()}
Python
nomic_cornstack_python_v1
function test_us_25_hs4 self begin set gedcom_data = call parse_gedcom_file string ./sampledata/us25testdata.ged for family in gedcom_data at 0 begin set children_ids = children for id in children_ids begin if id in gedcom_data at 1 begin get gedcom_data at 1 id if id == string hs4 begin assert false call validate_chil...
def test_us_25_hs4(self): gedcom_data = parse_gedcom_file("./sampledata/us25testdata.ged") for family in gedcom_data[0]: children_ids = gedcom_data[0].get(family).children for id in children_ids: if id in gedcom_data[1]: gedcom_data[1].get(id) ...
Python
nomic_cornstack_python_v1
function _replace self **kwargs begin for k in kwargs begin if is instance kwargs at k Marginalisation begin set kwargs at k = integer kwargs at k end end return call _replace keyword kwargs end function
def _replace(self, **kwargs): for k in kwargs: if isinstance(kwargs[k], Marginalisation): kwargs[k] = int(kwargs[k]) return super(Kernel, self)._replace(**kwargs)
Python
nomic_cornstack_python_v1
function findMedianSortedArrays self nums1 nums2 begin set a = list for i in range length nums1 begin append a nums1 at i end for j in range length nums2 begin append a nums2 at j end sort a set mid = length a // 2 set res = a at mid + a at ? mid / 2 return res end function
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: a = [] for i in range(len(nums1)): a.append(nums1[i]) for j in range(len(nums2)): a.append(nums2[j]) a.sort() mid = len(a) // 2 res = (a[mid]+ a[~mid])/ 2 return res
Python
zaydzuhri_stack_edu_python
set my_list = list 1 2 3 4 5 for num in my_list begin set square = num ^ 2 print square end
my_list = [1, 2, 3, 4, 5] for num in my_list: square = num ** 2 print(square)
Python
jtatman_500k
function update self begin return call _process string update end function
def update(self): return self._process('update')
Python
nomic_cornstack_python_v1
from flask import Flask from flask_graphql import GraphQLView from graphene_utils.utils import createGrapheneClass import graphene set app = call Flask __name__ set NestedObject = call createGrapheneClass string NestedObject list tuple string name str tuple string age int tuple string body string json class DataObject ...
from flask import Flask from flask_graphql import GraphQLView from graphene_utils.utils import createGrapheneClass import graphene app = Flask(__name__) NestedObject = createGrapheneClass( "NestedObject", [("name", str), ("age", int), ("body", "json")]) class DataObject(object): def __init__(self, **kwargs...
Python
zaydzuhri_stack_edu_python
while true begin set current_password = input if password == current_password begin print string Welcome { user_name } ! break end end
while True: current_password = input() if password == current_password: print(f'Welcome {user_name}!') break
Python
zaydzuhri_stack_edu_python
class Germany begin function __init__ self begin set members = list string Bonn, Koeln, Muenchen, Duesseldorf, Essen end function end class
class Germany: def __init__(self): self.members = ["Bonn, Koeln, Muenchen, Duesseldorf, Essen"]
Python
zaydzuhri_stack_edu_python
function deepcopy self sliced=true begin if is instance self Alignment begin set reversed = reverse end else begin set reversed = reverse end set new_seqs = dictionary set db = if expression reversed and sliced then none else deep copy annotation_db for seq in seqs begin try begin set new_seq = deep copy sliced=sliced ...
def deepcopy(self, sliced: bool = True): if isinstance(self, Alignment): reversed = self.seqs[0].map.reverse else: reversed = self.seqs[0]._seq.reverse new_seqs = dict() db = None if reversed and sliced else deepcopy(self.annotation_db) for seq in self.seq...
Python
nomic_cornstack_python_v1
function get_content_loss X_content X_pre begin set content_features = dict set content_net = call net X_pre set content_features at CONTENT_LAYER = content_net at CONTENT_LAYER set preds = call net X_content / 255.0 set preds_pre = call preprocess preds set net = call net preds_pre set content_size = call _tensor_siz...
def get_content_loss(X_content, X_pre): content_features = {} content_net = vgg.net(X_pre) content_features[CONTENT_LAYER] = content_net[CONTENT_LAYER] preds = transform.net(X_content/255.0) preds_pre = vgg.preprocess(preds) net = vgg.net(preds_pre) content_size = _tensor_size(content_fe...
Python
nomic_cornstack_python_v1
class Animal begin function __init__ self name begin set name = name end function function eat self begin raise call NotImplementedError string Subclass must implement this method end function function __str__ self begin return string I am an animal called { name } end function end class
class Animal: def __init__(self, name): self.name = name def eat(self): raise NotImplementedError("Subclass must implement this method") def __str__(self): return f'I am an animal called {self.name}'
Python
zaydzuhri_stack_edu_python
from core.internally_named import Internally_Named from core.owning import Owner from hand import Hand from realm import Realm from piece_tray import Piece_Tray class Player extends Internally_Named Owner begin function __init__ self name color begin call __init__ self name call __init__ self set _color = color set _ha...
from core.internally_named import Internally_Named from core.owning import Owner from .hand import Hand from .realm import Realm from .piece_tray import Piece_Tray class Player(Internally_Named, Owner): def __init__(self, name, color): Internally_Named.__init__(self, name) Owner.__init__(self) ...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 string Python script to automatically grade based on pull requests. import csv import grader import sys from pull_request import PullRequest from student import Student set REPO = string startup-systems/static set SURVEY_DATA_PATH = argv at 1 set OUTPUT_PATH = argv at 2 if __name__ == string __mai...
# coding: utf-8 """Python script to automatically grade based on pull requests.""" import csv import grader import sys from pull_request import PullRequest from student import Student REPO = "startup-systems/static" SURVEY_DATA_PATH = sys.argv[1] OUTPUT_PATH = sys.argv[2] if __name__ == '__main__': pull_reque...
Python
zaydzuhri_stack_edu_python
function node_click self id begin if id in states begin remove states id end else begin append states id end end function
def node_click(self, id): if id in self.states: self.states.remove(id) else: self.states.append(id)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment Enchère class Bid begin function __init__ self begin comment Couleur de l'enchère set color = none comment Valeur de l'enchère set value = none end function end class
# -*- coding: utf-8 -*- # Enchère class Bid(): def __init__(self): self.color = None # Couleur de l'enchère self.value = None # Valeur de l'enchère
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import random import time while true begin sleep 0.5 set a = call randrange 1 7 set b = call randrange 1 7 end
#!/usr/bin/python import random import time while True: time.sleep(0.5) a = random.randrange(1,7) b = random.randrange(1,7)
Python
zaydzuhri_stack_edu_python
comment WORKS function is_valid_username self username begin set done1 = execute cur format string SELECT username FROM users WHERE username="{}" username set done2 = execute cur format string SELECT username FROM admins WHERE username="{}" username comment If both queries are unsuccessful, username doesn't exist in bo...
def is_valid_username(self, username): # WORKS done1 = self.cur.execute("SELECT username FROM users WHERE username=\"{}\"".format(username)) done2 = self.cur.execute("SELECT username FROM admins WHERE username=\"{}\"".format(username)) if done1 == 0 and done2 == 0: # If both queries are unsucces...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import ast set f = open string centerError string r set i = 0 set j = 0 set t1 = list set centerError = list while i != string begin set i = read line f - 1 end
import matplotlib.pyplot as plt import ast f = open('centerError','r') i = 0 j = 0 t1 = [] centerError = [] while i != '': i = f.readline(-1)
Python
zaydzuhri_stack_edu_python
print is alphanumeric string Ram123 print is alpha string Ram123 print is alpha string ram print is digit string ram print is digit string 123 print is lower string ram print is lower string Ram print is lower string ram123 print is upper string RAM print call istitle print call istitle print is space string
print('Ram123'.isalnum()) print('Ram123'.isalpha()) print('ram'.isalpha()) print('ram'.isdigit()) print('123'.isdigit()) print('ram'.islower()) print('Ram'.islower()) print('ram123'.islower()) print('RAM'.isupper()) print('Ram Sita Laxman'.istitle()) print('Ram sita Laxman'.istitle()) print(' '.isspace())
Python
zaydzuhri_stack_edu_python
function emp_reject self begin for emp in self begin set state = string rejected end end function
def emp_reject(self): for emp in self: emp.state = 'rejected'
Python
nomic_cornstack_python_v1
string Controller code module import json from flask import Request from flask_restful import Resource , marshal_with from injector import inject from model import USER_FIELDS from service import UserService set DEFAULT_PAGE_SIZE = 20 class UserList extends Resource begin string User Resource: The API for multiple user...
"""Controller code module""" import json from flask import Request from flask_restful import Resource, marshal_with from injector import inject from model import USER_FIELDS from service import UserService DEFAULT_PAGE_SIZE = 20 class UserList(Resource): """User Resource: The API for multiple user requests""" ...
Python
zaydzuhri_stack_edu_python
from generator import Commander , GeneratorStateMaster function make_generator_entry caption state begin string Convenience function used to return one option 'row' using the caption and state append action (the common operation) :param caption: string to be used as an action's caption :param state: state to be appende...
from generator import Commander, GeneratorStateMaster def make_generator_entry(caption, state): """ Convenience function used to return one option 'row' using the caption and state append action (the common operation) :param caption: string to be used as an action's caption :param state: state to...
Python
zaydzuhri_stack_edu_python
comment coding: UTF-8 string Created on 2014-04-21 @author: mingliu import time if __name__ == string __main__ begin set t1 = time end
#coding: UTF-8 ''' Created on 2014-04-21 @author: mingliu ''' import time if __name__ == '__main__': t1 = time.time()
Python
zaydzuhri_stack_edu_python
function __init__ __self__ name=none product=none promotion_code=none publisher=none version=none begin if name is not none begin set __self__ string name name end if product is not none begin set __self__ string product product end if promotion_code is not none begin set __self__ string promotion_code promotion_code e...
def __init__(__self__, *, name: Optional[pulumi.Input[str]] = None, product: Optional[pulumi.Input[str]] = None, promotion_code: Optional[pulumi.Input[str]] = None, publisher: Optional[pulumi.Input[str]] = None, version: Optional[pulum...
Python
nomic_cornstack_python_v1
from django.core.management.base import BaseCommand , CommandError import csv from movie.models import Movies from datetime import datetime class Command extends BaseCommand begin function handle self *args **options begin with open string data/netflix_titles.csv string r as csv_file begin set reader = reader csv_file ...
from django.core.management.base import BaseCommand, CommandError import csv from movie.models import Movies from datetime import datetime class Command(BaseCommand): def handle(self, *args, **options): with open('data/netflix_titles.csv', 'r') as csv_file: reader = csv.reader(csv_file) ...
Python
zaydzuhri_stack_edu_python
comment neeraj varshney (2014A7PS0103P) from final_program import * import time import copy set a = integer input string Option 1: Display the room environment Option 2: Find the path (action sequence) and path cost using T1 Option 3: Find the path (action sequence) and path cost using T2 Option 4: Show all results and...
#neeraj varshney (2014A7PS0103P) from final_program import * import time import copy a=(int)(input("\nOption 1: Display the room environment\nOption 2: Find the path (action sequence) and path cost using T1\nOption 3: Find the path (action sequence) and path cost using T2\nOption 4: Show all results and graphs in the G...
Python
zaydzuhri_stack_edu_python
function set_canvas plot_residual begin if plot_residual begin set canvas = call CanvasImage string residual set data = call clip data 1.0 max set data = - 2.5 * call log10 data / 480.0 / ps ^ 2 + 27.2 set tuple yc xc r = tuple 775 1251 90 for x in array range xc - r xc + r begin for y in array range yc - r yc + r begi...
def set_canvas(plot_residual): if plot_residual: canvas = cv.CanvasImage("residual") canvas.data = np.clip(canvas.data, 1., canvas.data.max()) canvas.data = -2.5 * np.log10( canvas.data / 480. / canvas.ps ** 2) + 27.2 yc, xc, r = 775, 1251, 90 for x in np.a...
Python
nomic_cornstack_python_v1
function once_only self begin return __once_only end function
def once_only(self) -> bool: return self.__once_only
Python
nomic_cornstack_python_v1
from queue import * class Country begin function __init__ self name age begin set name = name set age = age end function function __str__ self begin return string The %s country is %s years old. % tuple name age end function end class
from queue import * class Country: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "The %s country is %s years old." % (self.name, self.age)
Python
zaydzuhri_stack_edu_python
function compare_averages_shell_pspec_dft begin comment degrees set select_radius = 5.0 set Nside = 256 set Npix = 12 * Nside ^ 2 set Omega = 4 * pi / decimal Npix set Nfreq = 100 set freqs = linear space 167.0 177.0 Nfreq set dnu = diff np freqs at 0 set Z = 1420 / freqs - 1.0 set sig = 2.0 set mu = 0.0 set shell = ca...
def compare_averages_shell_pspec_dft(): select_radius = 5. #degrees Nside=256 Npix = 12 * Nside**2 Omega = 4*np.pi/float(Npix) Nfreq = 100 freqs = np.linspace(167.0, 177.0, Nfreq) dnu = np.diff(freqs)[0] Z = 1420/freqs - 1. sig = 2.0 mu = 0.0 shell = np.random.normal(mu, ...
Python
nomic_cornstack_python_v1
function show_condor_jobs self condor_jobs long legend begin set long_val = integer long set column_descr = dict string id list string string : Condor cluster ID ; string site list string string : Job site ; string stat string Condor job status ; string in_state string Time job spent in current Condor status ; string...
def show_condor_jobs(self, condor_jobs: list, long: bool, legend: bool): long_val = int(long) column_descr = { "id": ["", ": Condor cluster ID "], "site": ["", ": Job site\n"], "stat": "Condor job status", "in_state": "Time job spent in current Condor sta...
Python
nomic_cornstack_python_v1
comment encoding: utf-8 comment https://qiita.com/makaishi2/items/63b7986f6da93dc55edd comment book: 三四郎 comment wget http://www.aozora.gr.jp/cards/000148/files/794_ruby_4237.zip comment Janomeのロード from janome.tokenizer import Tokenizer import codecs comment ファイル読込み、内部表現化 set f = open string sanshiro.txt string r strin...
# encoding: utf-8 # # https://qiita.com/makaishi2/items/63b7986f6da93dc55edd # # book: 三四郎 # wget http://www.aozora.gr.jp/cards/000148/files/794_ruby_4237.zip # # Janomeのロード from janome.tokenizer import Tokenizer # import codecs # ファイル読込み、内部表現化 f = codecs.open('sanshiro.txt', "r", "sjis") text = f.read() f.close() #qu...
Python
zaydzuhri_stack_edu_python
function is_host_local host begin set addresses = list call all_addrs host set local_count = length list comprehension a for a in addresses if call is_addr_local a if local_count == 0 begin return NONE_LOCAL end else if local_count == length addresses begin return ALL_LOCAL end else begin return SOME_LOCAL end end func...
def is_host_local(host): addresses = list(all_addrs(host)) local_count = len([a for a in addresses if is_addr_local(a)]) if local_count == 0: return NONE_LOCAL elif local_count == len(addresses): return ALL_LOCAL else: return SOME_LOCAL
Python
nomic_cornstack_python_v1
from diceSet import DiceSet import itertools class Search begin function __init__ self begin pass end function function choices self diceSet begin return list product list true false repeat=nbDices end function end class
from diceSet import DiceSet import itertools class Search: def __init__(self) -> None: pass def choices(self, diceSet: DiceSet): return list(itertools.product([True, False], repeat=diceSet.nbDices))
Python
zaydzuhri_stack_edu_python
function secondSmoothnessLoss tensorFlow begin set tuple delta_u delta_v = call _secondOrderDeltas tensorFlow return call charbonnierLoss delta_u + call charbonnierLoss delta_v end function
def secondSmoothnessLoss(tensorFlow): delta_u, delta_v = _secondOrderDeltas(tensorFlow) return charbonnierLoss(delta_u) + charbonnierLoss(delta_v)
Python
nomic_cornstack_python_v1
import sys set stdin = open string 2806.txt set d = list tuple 1 1 tuple 1 - 1 tuple - 1 1 tuple - 1 - 1 function check r c begin if row at r == 1 begin return 0 end if col at c == 1 begin return 0 end for tuple dr dc in d begin for i in range N begin set tuple nr nc = tuple r + dr * i c + dc * i if 0 <= nr < N and 0 <...
import sys sys.stdin = open('2806.txt') d = [(1, 1), (1, -1), (-1, 1), (-1, -1)] def check(r, c): if row[r] == 1: return 0 if col[c] == 1: return 0 for dr, dc in d: for i in range(N): nr, nc = r + dr * i, c + dc * i if 0 <= nr < N and 0 <= nc < N and v...
Python
zaydzuhri_stack_edu_python
comment module for reusable decorators from flask import abort , request , current_app as app from functools import wraps function authenticate_token func begin decorator wraps func function wrapper *args **kwargs begin set token = none set token = get headers string Api-Key if token is none begin call abort 400 string...
# module for reusable decorators from flask import abort, request, current_app as app from functools import wraps def authenticate_token(func): @wraps(func) def wrapper(*args, **kwargs): token = None token = request.headers.get('Api-Key') if token is None: abort(400, 'expect...
Python
zaydzuhri_stack_edu_python
comment Lista encargada de la informacion de los nodos conocidos from lista_nodos_nodo import nodo from modelo_lista_nodos import modelo_lista_nodos from PyQt4 import QtCore class lista_nodos begin function __init__ self l=list padre=call QObject begin set lista = l set modelo = call modelo_lista_nodos padre lista end...
#Lista encargada de la informacion de los nodos conocidos from lista_nodos_nodo import nodo from modelo_lista_nodos import modelo_lista_nodos from PyQt4 import QtCore class lista_nodos: def __init__(self, l = [], padre = QtCore.QObject()): self.lista = l self.modelo = modelo_lista_nodos(padre, self.lista) def...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import time import os set doorstatus = 0 from RPi import GPIO call setmode BOARD setup GPIO 18 IN pull_up_down=PUD_DOWN while true begin set inputval1 = input 18 end
#!/usr/bin/python import time import os doorstatus = 0 from RPi import GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: inputval1 = GPIO.input(18)
Python
zaydzuhri_stack_edu_python
comment This example implements a 5 invader SDMI game with a Brute force Capture order import sdmiFuncLib as sfl import numpy as np import matplotlib.pyplot as plt comment Invader Locations comment I0 => [-12.25709932 4.44973388] comment I1 => [ -6.6489077 21.23919568] comment I2 => [ 0.41996017 24.16072049] comment I3...
#This example implements a 5 invader SDMI game with a Brute force Capture order import sdmiFuncLib as sfl import numpy as np import matplotlib.pyplot as plt #Invader Locations #I0 => [-12.25709932 4.44973388] #I1 => [ -6.6489077 21.23919568] #I2 => [ 0.41996017 24.16072049] #I3 => [ 8.51769598 11....
Python
zaydzuhri_stack_edu_python
import os import pandas as pd import matplotlib.pyplot as plt if not ends with get current directory string etl begin change directory string ./data_science/lessons/etl end set df = read csv string data/gdp_data.csv skiprows=4 drop df string Unnamed: 62 axis=1 inplace=true set count_null_vals = sum comment put the data...
import os import pandas as pd import matplotlib.pyplot as plt if not os.getcwd().endswith("etl"): os.chdir("./data_science/lessons/etl") df = pd.read_csv('data/gdp_data.csv', skiprows=4) df.drop('Unnamed: 62', axis=1, inplace=True) count_null_vals = df.isnull().sum() # put the data set into long form instead of...
Python
zaydzuhri_stack_edu_python
function testFileHashLargeMulti self begin set b = call urandom MAX_READ_SZ * 3 + 112 call hashFileHelper b list string md5 string sha1 end function
def testFileHashLargeMulti(self): b = os.urandom(MAX_READ_SZ*3 + 112) self.hashFileHelper(b, ['md5', 'sha1'])
Python
nomic_cornstack_python_v1
function save_plot_as_png self begin set file_save_path = call getSaveFileName self string Save Plot PNG string string PNG (*.png)|*.png if file_save_path at 0 begin save figure file_save_path at 0 bbox_inches=string tight call about self string Success! string Your plot has been saved as png image successfully. end e...
def save_plot_as_png(self): file_save_path = QFileDialog.getSaveFileName(self, 'Save Plot PNG', "", "PNG (*.png)|*.png") if file_save_path[0]: self.figure.savefig(file_save_path[0], bbox_inches='tight') QMessageBox.about(self, "Success!", "Your plot has been saved as png image s...
Python
nomic_cornstack_python_v1
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt set df = read csv string train.csv comment print(df.dtypes) #function giving the datatypes of all columns set features = list string People string Population string Width(m) string Length(m) string Months set X = df at features set Y = df at stri...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv("train.csv") #print(df.dtypes) #function giving the datatypes of all columns features = ['People','Population','Width(m)','Length(m)','Months'] X = df[features] Y = df['Survival '] people_replace_dict = { "People" : {"S...
Python
zaydzuhri_stack_edu_python
comment 闭包可以理解为一个将一系列相关的环境变量与一个函数一同打包返回 comment 然后后面再使用函数的时候所附带的环境变量则跟随着函数起作用 function addbase n begin function add x begin return x + n end function return add end function comment 手动设定闭包中的环境变量为10 set add = call addbase 10 comment 输出结果为"10+12"=22 print add 12 comment 删除addbase的定义 del addbase comment 再次执行,返回110 print a...
#闭包可以理解为一个将一系列相关的环境变量与一个函数一同打包返回 #然后后面再使用函数的时候所附带的环境变量则跟随着函数起作用 def addbase(n): def add(x): return x + n return add add = addbase(10)#手动设定闭包中的环境变量为10 print(add(12))#输出结果为"10+12"=22 del addbase#删除addbase的定义 print(add(100))#再次执行,返回110
Python
zaydzuhri_stack_edu_python
function get_ellipses im_markers start_coord margin=5 begin set im_thresh = im_markers at tuple slice margin : - margin : slice margin : - margin : set im_thresh = call GaussianBlur im_thresh tuple 7 7 3 set im_thresh = as type im_thresh < 175 uint8 comment kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5)) ...
def get_ellipses(im_markers, start_coord, margin=5): im_thresh = im_markers[margin:-margin, margin:-margin] im_thresh = cv.GaussianBlur(im_thresh, (7, 7), 3) im_thresh = (im_thresh < 175).astype(np.uint8) # kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5)) # im_roi = cv.morphologyEx(im_thr...
Python
nomic_cornstack_python_v1
function moveZeroes self nums begin set length = length nums set i = 0 for j in range 0 length begin if nums at j != 0 begin set nums at i = nums at j set i = i + 1 end end for x in range i length begin set nums at x = 0 end return nums end function
def moveZeroes(self, nums: List[int]) -> None: length = len(nums) i = 0 for j in range(0, length): if nums[j] != 0: nums[i] = nums[j] i += 1 for x in range(i, length): nums[x] = 0 return nums
Python
nomic_cornstack_python_v1
import graphene import json class Query extends ObjectType begin set isStaff = call Boolean function resolve_isStaff self info begin return true end function end class function main begin set schema = call Schema query=Query set result = execute schema string { isStaff } end function
import graphene import json class Query(graphene.ObjectType): isStaff = graphene.Boolean() def resolve_isStaff(self, info): return True def main(): schema = graphene.Schema(query=Query) result = schema.execute( ''' { isStaff } ''' )...
Python
zaydzuhri_stack_edu_python
function _UpdateSudoer self user sudoer=false begin string Update sudoer group membership for a Linux user account. Args: user: string, the name of the Linux user account. sudoer: bool, True if the user should be a sudoer. Returns: bool, True if user update succeeded. if sudoer begin info string Adding user %s to the G...
def _UpdateSudoer(self, user, sudoer=False): """Update sudoer group membership for a Linux user account. Args: user: string, the name of the Linux user account. sudoer: bool, True if the user should be a sudoer. Returns: bool, True if user update succeeded. """ if sudoer: s...
Python
jtatman_500k
comment Do strony z listą pracowników dodaj formularz, umożliwiający dodanie nowego pracownika. Powinien zawierać osobne pole comment tekstowe dla każdej informacji o pracowniku. Przesłanie formularza powinno spowodować dodanie pracownika i wyświetlenie comment zaktualizowanej listy. from flask import Flask , render_te...
# Do strony z listą pracowników dodaj formularz, umożliwiający dodanie nowego pracownika. Powinien zawierać osobne pole # tekstowe dla każdej informacji o pracowniku. Przesłanie formularza powinno spowodować dodanie pracownika i wyświetlenie # zaktualizowanej listy. from flask import Flask, render_template, request, ...
Python
zaydzuhri_stack_edu_python
while i < length s - 2 begin if s at i == string , begin set i = i + 1 end set s = s at slice : i + 1 : + string , + s at slice i + 1 : : set i = i + 1 end set ls = split s string , for i in range 0 length ls - 1 begin set j = i + 1 while j < length ls begin if ordinal ls at i > ordinal ls at j begin set temp = ls ...
while i<len(s)-2: if s[i]==",": i=i+1 s=s[:i+1]+","+s[i+1:] i=i+1 ls=s.split(",") for i in range(0,len(ls)-1): j=i+1 while j<len(ls): if ord(ls[i])>ord(ls[j]): temp=ls[j] ls[j]=ls[i] ls[i]=temp j=j+1 print(''.join(ls)) ...
Python
zaydzuhri_stack_edu_python
function partition l r a begin string This function creates a partition taking the element at the index position r given in the function as partition(l,'r',{array}) as the pivot element, from the 'l' index to the r index, returning the correct position of the pivot in the sorted array. set mark = l for i in range l r b...
def partition(l,r,a): """This function creates a partition taking the element at the index position r given in the function as partition(l,'r',{array}) as the pivot element, from the 'l' index to the r index, returning the correct position of the pivot in the sorted array.""" mark=l for i in range(l,r): if a[i]<a[...
Python
zaydzuhri_stack_edu_python
import sklearn.datasets as DT from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error , r2_score import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures...
import sklearn.datasets as DT from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error,r2_score import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures f...
Python
zaydzuhri_stack_edu_python
class RandomListNode begin function __init__ self value begin set label = value set next = none set random = none end function end class class Solution begin function Clone self pHead begin if not pHead begin return none end set pHead = call cloneList pHead set pHead = call copyRandomP pHead set pCloneHead = call split...
class RandomListNode: def __init__(self, value): self.label = value self.next = None self.random = None class Solution: def Clone(self, pHead): if not pHead: return None pHead = self.cloneList(pHead) pHead = self.copyRandomP(pHead) pCloneHead...
Python
zaydzuhri_stack_edu_python
comment 원화를 입력, 환율 입력 -> 달러값 set won = input string 원화금액을 입력 하세요>>> set dollar = input string 환율을 입력 하세요>>> comment 예외가 발생 할 수 있는 코드 try begin print integer won / integer dollar end comment 예외가 발행했을 때 실행되는 코드 except ValueError as e begin print string 문자열 예외가 발생했습니다. e end except ZeroDivisionError as e begin print strin...
# 원화를 입력, 환율 입력 -> 달러값 won = input("원화금액을 입력 하세요>>>") dollar = input("환율을 입력 하세요>>>") try: # 예외가 발생 할 수 있는 코드 print(int(won) / int(dollar)) except ValueError as e: # 예외가 발행했을 때 실행되는 코드 print("문자열 예외가 발생했습니다.", e) except ZeroDivisionError as e: print("나누기 0은 불가능 합니다.", e) else: print("예외가 발생하지 않았을 때 실헹되는 코드"...
Python
zaydzuhri_stack_edu_python
function err self begin return call getvalue end function
def err(self): return self._err.getvalue()
Python
nomic_cornstack_python_v1
function get_rule_from_response self response begin set _matches = lambda r -> call matches_response response for rule in call ifilter _matches _rules begin comment return first match of iterator return rule end end function
def get_rule_from_response(self, response): _matches = lambda r: r.matcher.matches_response(response) for rule in ifilter(_matches, self._rules): # return first match of iterator return rule
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment Author: Yunlong Feng <ylfeng@ir.hit.edu.cn> import numpy as np function cycle iterable begin while true begin yield from iterable end end function class MultiTaskDataloader begin function __init__ self tau=1.0 **dataloaders begin set dataloaders = dataloaders set Z = sum generator ...
#! /usr/bin/env python # Author: Yunlong Feng <ylfeng@ir.hit.edu.cn> import numpy as np def cycle(iterable): while True: yield from iterable class MultiTaskDataloader: def __init__(self, tau=1.0, **dataloaders): self.dataloaders = dataloaders Z = sum(pow(v, tau) for v in self.datal...
Python
zaydzuhri_stack_edu_python
function test_pick_latest_file self begin set max = FILES_LIST at 0 for f in FILES_LIST begin if call getctime join path FILES_DIR f > call getctime join path FILES_DIR max begin set max = f end end set max = FILES_DIR + max set latest = call pick_latest_file assert equal max latest end function
def test_pick_latest_file(self): max = FILES_LIST[0] for f in FILES_LIST: if os.path.getctime(os.path.join(FILES_DIR, f)) > os.path.getctime(os.path.join(FILES_DIR, max)): max = f max = FILES_DIR + max latest = pick_latest_file() self...
Python
nomic_cornstack_python_v1
function get_state_no self var state_name begin if state_names begin return name_to_no at var at state_name end else begin return state_name end end function
def get_state_no(self, var, state_name): if self.state_names: return self.name_to_no[var][state_name] else: return state_name
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- set __author__ = string p.olifer set __version__ = string 1.0 function make_averager begin set count = 0 set total = 0 function averager new_value begin nonlocal count total set count = count + 1 set total = total + new_value return total / count end function return averager end function i...
# -*- coding: utf-8 -*- __author__ = 'p.olifer' __version__ = '1.0' def make_averager(): count = 0 total = 0 def averager(new_value): nonlocal count, total count += 1 total += new_value return total/count return averager if __name__ == '__main__': avg = make_av...
Python
zaydzuhri_stack_edu_python
function printMove fr to begin string +just printing the move +carry on XO Pressly print string move from + string fr + string to + string to end function function Towers n fr to spare begin string The base case is the move case, recursive +becoming things, to move is to become comment base case, when tower is of size ...
def printMove(fr,to): ''' +just printing the move +carry on XO Pressly ''' print('move from '+str(fr)+' to '+str(to)) def Towers(n,fr,to,spare): ''' The base case is the move case, recursive +becoming things, to move is to become ''' if n==1: #base case, when tow...
Python
zaydzuhri_stack_edu_python
function all_alpha_or_dash s begin return all generator expression is alpha c or c == string - for c in s end function
def all_alpha_or_dash(s): return all(c.isalpha() or c == '-' for c in s)
Python
nomic_cornstack_python_v1
for i in shoes begin if i not in have begin append have i end end print 4 - length have
for i in shoes: if i not in have: have.append(i) print(4 - len(have))
Python
zaydzuhri_stack_edu_python
function balls_bowled player against_batsman batting_types innings_number tournaments=none venue=none years=none overs_range=none begin comment Grabbing all balls bowled by this player set required_balls = df_ball at df_ball at string bowler == player comment Grabbing all matches to map ids set required_matches = df_ma...
def balls_bowled(player, against_batsman, batting_types, innings_number, tournaments=None, venue=None, years=None, overs_range=None): # Grabbing all balls bowled by this player required_balls = df_ball[df_ball["bowler"] == player] # Grabbing all matches to map ids required_matches = df_match ...
Python
nomic_cornstack_python_v1
comment coding=UTF-8 comment anti_euler_v2の改良版 comment 重い処理は外側でやった方が良い comment x_1 ^n + x_2 ^n + .. + x_{n-1} ^n = y^n comment となるような n>=3 で存在するかの話 comment GCD(x_1,x_2,...,x_{n-1}) = 1 これは実質的な解なだけ comment 今回は n=5 の話 comment ここを変更しても別の例を求められる訳ではない set n = 5 import sys import time import math import bisect comment ハッシュテー...
#coding=UTF-8 # anti_euler_v2の改良版 # 重い処理は外側でやった方が良い # x_1 ^n + x_2 ^n + .. + x_{n-1} ^n = y^n # となるような n>=3 で存在するかの話 # GCD(x_1,x_2,...,x_{n-1}) = 1 これは実質的な解なだけ # 今回は n=5 の話 # ここを変更しても別の例を求められる訳ではない n=5 import sys import time import math import bisect # ハッシュテーブルをリストで記録し、探索に二分探索を用いる # 辞書より速いかどうかは不明 # 辞書の方は平均 O(1) と書...
Python
zaydzuhri_stack_edu_python
function rec_default self begin pass end function
def rec_default(self): pass
Python
nomic_cornstack_python_v1
function configure_states_introspection state_options time_options control_options parameter_options polynomial_control_options ode begin set time_units = time_options at string units for tuple state_name options in items state_options begin set user_targets = options at string targets set user_units = options at strin...
def configure_states_introspection(state_options, time_options, control_options, parameter_options, polynomial_control_options, ode): time_units = time_options['units'] for state_name, options in state_options.items(): user_targets = options['targets'] user_un...
Python
nomic_cornstack_python_v1
function verify_route_table_label device label=none php_label=none max_time=60 check_interval=10 begin set timeout = call Timeout max_time check_interval while call iterate begin try begin set out = parse device format string show route table mpls.0 label {label} label=label end except SchemaEmptyParserError begin slee...
def verify_route_table_label(device, label=None, php_label=None, max_time=60, check_interval=10): timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out...
Python
nomic_cornstack_python_v1
import torch.nn as nn class A extends Module begin function __init__ self target c begin call __init__ comment we 'detach' the target content from the tree used comment to dynamically compute the gradient: this is a stated value, comment not a variable. Otherwise the forward method of the criterion comment will throw a...
import torch.nn as nn class A(nn.Module): def __init__(self, target, c): super(A, self).__init__() # we 'detach' the target content from the tree used # to dynamically compute the gradient: this is a stated value, # not a variable. Otherwise the forward method of the criterion ...
Python
zaydzuhri_stack_edu_python
string 三个点号,表示的是模块(module)的注释,请知悉哦 import Basic_Python.chapter5 as t set name = string Peter set age = 17 comment print(t.sys.path) comment infos = dir() comment print(infos) print string name: __name__ print string file: __file__ print string package: __package__ print string doc: __doc__
''' 三个点号,表示的是模块(module)的注释,请知悉哦 ''' import Basic_Python.chapter5 as t name = 'Peter' age = 17 # print(t.sys.path) # infos = dir() # # print(infos) print("name:",__name__) print("file:",__file__) print("package:",__package__) print("doc:",__doc__)
Python
zaydzuhri_stack_edu_python
import dialogflow comment Define the project ID and session ID set PROJECT_ID = string <my project id>
import dialogflow # Define the project ID and session ID PROJECT_ID = '<my project id>'
Python
iamtarun_python_18k_alpaca
function push s begin call push end function
def push(s): s.push()
Python
nomic_cornstack_python_v1
function exec_run self cid cmd begin set execid = call exec_create cid cmd return call exec_start execid at string Id end function
def exec_run(self, cid: str, cmd: str) -> bytes: execid = self._client.exec_create(cid, cmd) return self._client.exec_start(execid['Id'])
Python
nomic_cornstack_python_v1
function trigger_event self module_name event begin if module_name begin call process_event module_name event end end function
def trigger_event(self, module_name, event): if module_name: self._py3_wrapper.events_thread.process_event(module_name, event)
Python
nomic_cornstack_python_v1
string Utitlity functions for summarizing and analyzing data from the litter database. Used with a jupyter notebook. Creates folder structures, groups data, creates graphs and outputs JSON format data. See the repo @hammerdirt/three_year_final for the accompanying notebooks and intended use. Contact roger@hammerdirt.ch...
""" Utitlity functions for summarizing and analyzing data from the litter database. Used with a jupyter notebook. Creates folder structures, groups data, creates graphs and outputs JSON format data. See the repo @hammerdirt/three_year_final for the accompanying notebooks and intended use. Contact roger@hammerdirt.ch...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Apr 15 01:55:33 2021 @author: Loai import numpy as np import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf __version__ comment Importing the dataset set df = read csv string data important.csv set X = iloc at tuple slice : : slice 2 : 12 : s...
# -*- coding: utf-8 -*- """ Created on Thu Apr 15 01:55:33 2021 @author: Loai """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf tf.__version__ # Importing the dataset df = pd.read_csv('data important.csv') X=df.iloc[:,2:12] Y=df.iloc[:,1:2] # print(df...
Python
zaydzuhri_stack_edu_python