code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
set r : float set area : float set r = decimal input string Digite o valor do raio do circulo: set area = 3.14159 * r * r print string AREA = { area }
r: float; area: float r = float(input("Digite o valor do raio do circulo: ")) area = 3.14159 * r * r print(f"AREA = {area:.3f}")
Python
zaydzuhri_stack_edu_python
function starship1_page begin return string <html> <head> <title>Index empty link</title> </head> <body> <div class="pi-item pi-data pi-item-spacing pi-border-color" data-source="hyperdrive"> <ul> <li>Class 1.5</li> <li>Class 10 <a href="#cite_note-Collapse-1">&#91;1&#93;</a></li> </ul> </div> </body> </html> end funct...
def starship1_page() -> str: return """<html> <head> <title>Index empty link</title> </head> <body> <div class="pi-item pi-data pi-item-spacing pi-border-color" data-source="hyperdrive"> <ul> <li>Class 1.5</li> <li>Class 10 <a href="#cite_note-Collapse-1">&#91;1&#93;</a></li> </ul> </div...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment @Time : 2019/3/19 下午11:12 comment @Author : Aries comment @Site : comment @File : UdpClient.py comment @Software: PyCharm import socket comment TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据。相对TCP,UDP则是面向无连接的协议。 comment 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包。但是,能不能到达就不...
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2019/3/19 下午11:12 # @Author : Aries # @Site : # @File : UdpClient.py # @Software: PyCharm import socket # TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据。相对TCP,UDP则是面向无连接的协议。 # # 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包。但是,能不能到达就不知道了。 # # 虽然用UDP传输数据不可靠,但它的优点是和TCP比,速度快,对于不...
Python
zaydzuhri_stack_edu_python
function findPair lst target begin for i in range 0 length lst begin for j in range i + 1 length lst begin if lst at i + lst at j == target begin return print lst at i string , lst at j end end end end function set list = list 2 4 6 8 set target = 10 call findPair list target
def findPair(lst, target): for i in range(0, len(lst)): for j in range(i + 1, len(lst)): if lst[i] + lst[j] == target: return print(lst[i],",", lst[j]) list = [2, 4, 6, 8] target = 10 findPair(list, target)
Python
jtatman_500k
function extract_first_100_chars string begin return string at slice : 100 : end function
def extract_first_100_chars(string): return string[:100]
Python
iamtarun_python_18k_alpaca
function validate_auth_option option value begin set tuple lower value = call validate option value if lower not in _AUTH_OPTIONS begin raise call ConfigurationError string Unknown authentication option: %s % tuple option end return tuple lower value end function
def validate_auth_option(option, value): lower, value = validate(option, value) if lower not in _AUTH_OPTIONS: raise ConfigurationError('Unknown ' 'authentication option: %s' % (option,)) return lower, value
Python
nomic_cornstack_python_v1
set C = decimal input set Fahrenheit = C * 9 / 5 + 32.0 print string The fahrenheit value for C string celsius is format string {:.2f} Fahrenheit string fahrenheit
C=float(input()) Fahrenheit = (C * 9/5) + 32. print("The fahrenheit value for",C,"celsius is","{:.2f}".format(Fahrenheit),"fahrenheit")
Python
zaydzuhri_stack_edu_python
import csv import logging class HardcodedRules begin function applyRules self csv_data csv_groundTruth csv_no_genre_found begin info string aplying hardcoded rules call field_size_limit 500 * 1024 * 1024 with open csv_data newline=string encoding=string UTF-8 as translation begin with open csv_groundTruth string w new...
import csv import logging class HardcodedRules: def applyRules(self, csv_data, csv_groundTruth, csv_no_genre_found): logging.info('aplying hardcoded rules') csv.field_size_limit(500 * 1024 * 1024) with open(csv_data, newline='', encoding="UTF-8") as translation: with open(csv_...
Python
zaydzuhri_stack_edu_python
import time import math from selenium import webdriver from selenium.webdriver.support.ui import Select function calc x begin return string log absolute 12 * sin integer x end function try begin set link = string http://suninjuly.github.io/selects1.html set new_link = string http://suninjuly.github.io/selects2.html set...
import time import math from selenium import webdriver from selenium.webdriver.support.ui import Select def calc(x): return str(math.log(abs(12*math.sin(int(x))))) try: link = "http://suninjuly.github.io/selects1.html" new_link = "http://suninjuly.github.io/selects2.html" browser = webdriver.Chr...
Python
zaydzuhri_stack_edu_python
function make_absolute_url self url begin set base_url = get config at string PROJECT string url if base_url is none begin raise call RuntimeError string To use absolute URLs you need to configure the URL in the project config. end return url join right strip base_url string / + string / left strip url string / end fun...
def make_absolute_url(self, url): base_url = self.db.config["PROJECT"].get("url") if base_url is None: raise RuntimeError( "To use absolute URLs you need to configure " "the URL in the project config." ) return urljoin(base_url.rstrip("/") ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2021/6/19 下午7:41 comment @Author : jt_hou comment @Email : 949241101@qq.com comment @File : 0039combinationSum.py class Solution extends object begin function combinationSum self candidates target begin string :type candidates: List[int] :type t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/6/19 下午7:41 # @Author : jt_hou # @Email : 949241101@qq.com # @File : 0039combinationSum.py class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rt...
Python
zaydzuhri_stack_edu_python
function _unload_opengl self begin pass end function
def _unload_opengl(self): pass
Python
nomic_cornstack_python_v1
comment Check if Item Exists set tuple1 = tuple string Apple string cat string banana string bed if string cat in tuple1 begin print string its there end comment Repeat Item set tuple2 = tuple string A * 3 print tuple2 comment + Operator in Tuple set tuple3 = tuple string app string android set tuple4 = tuple string be...
# Check if Item Exists tuple1 = ('Apple', 'cat', 'banana', 'bed') if 'cat' in tuple1: print('its there') # Repeat Item tuple2 = ('A',)* 3 print(tuple2) # + Operator in Tuple tuple3 = ('app', 'android') tuple4 = ('bed', 'car') print(tuple3 + tuple4) x = (3, 4, 5, 6) x = x + (1, 2, 3) print(x) # Tuple Length t...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self begin set mat = list end function function isEmpty self begin return mat == list end function function push self data begin append mat data end function function pop self begin set value = mat at - 1 del mat at - 1 return value end function function peek self begin return mat ...
class Stack: def __init__(self): self.mat = [] def isEmpty(self): return self.mat == [] def push(self, data): self.mat.append(data) def pop(self): value = self.mat[-1] del self.mat[-1] return value def peek(self): return self.mat[-1] def sizers(self): return len(self.mat) stack = Stack() s...
Python
zaydzuhri_stack_edu_python
function to_dictionary self begin set dict_contents = list string id string size string x string y set new_dict = dict for key in dict_contents begin set new_dict at key = get attribute self key end return new_dict end function
def to_dictionary(self): dict_contents = ["id", "size", "x", "y"] new_dict = {} for key in dict_contents: new_dict[key] = getattr(self, key) return new_dict
Python
nomic_cornstack_python_v1
import pprint import itertools from Graph import Graph set pretty_print = call PrettyPrinter set end_of_func = string --------------------------------------------------- class FreightBooking begin function __init__ self begin set freight_map = dictionary set train_list = list set city_list = list set analyze_list = l...
import pprint import itertools from Graph import Graph pretty_print = pprint.PrettyPrinter() end_of_func = "---------------------------------------------------" class FreightBooking: def __init__(self): self.freight_map = dict() self.train_list = [] self.city_list = [] ...
Python
zaydzuhri_stack_edu_python
from sklearn import datasets from sklearn import tree from sklearn.model_selection import train_test_split import numpy as np from sklearn.metrics import accuracy_score import graphviz set dataset = call load_iris comment print(dataset) set keys = keys dataset set data = data set target = target comment print(keys) com...
from sklearn import datasets from sklearn import tree from sklearn.model_selection import train_test_split import numpy as np from sklearn.metrics import accuracy_score import graphviz dataset = datasets.load_iris() #print(dataset) keys = dataset.keys() data = dataset.data target = dataset.target #print(keys) #print(...
Python
zaydzuhri_stack_edu_python
from trie import Trie from nltk.tokenize import WhitespaceTokenizer import unidecode import re import string class SearchIndexer begin function __init__ self begin set t = call Trie set uuids = list set decades = dict end function function add_song self song begin set tokens = call _tokenize song set decade = year at...
from trie import Trie from nltk.tokenize import WhitespaceTokenizer import unidecode import re import string class SearchIndexer: def __init__(self): self.t = Trie() self.uuids = [] self.decades = {} def add_song(self, song): tokens = self._tokenize(song) decade = song....
Python
zaydzuhri_stack_edu_python
function grouper iterable n fillvalue=none begin set args = list iterate iterable * n return list call zip_longest *args fillvalue=fillvalue end function
def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return list(zip_longest(*args, fillvalue=fillvalue))
Python
nomic_cornstack_python_v1
from django.shortcuts import get_object_or_404 , render from models import Listing from choices import price_choices , bedroom_choices , state_choices from django.core.paginator import Paginator , EmptyPage , PageNotAnInteger comment Create your views here. We use django function based views comment FBVs allows us to s...
from django.shortcuts import get_object_or_404,render from .models import Listing from .choices import price_choices,bedroom_choices,state_choices from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # Create your views here. We use django function based views # FBVs allows us to simply write python...
Python
zaydzuhri_stack_edu_python
function get_where_for_local self other begin try begin set obj_info = call get_obj_info other end except ClassInfoError begin if type other is not tuple begin set remote_variables = tuple other end else begin set remote_variables = other end end try else begin comment Don't use other here, as it might be comment secur...
def get_where_for_local(self, other): try: obj_info = get_obj_info(other) except ClassInfoError: if type(other) is not tuple: remote_variables = (other,) else: remote_variables = other else: # Don't use other here, a...
Python
nomic_cornstack_python_v1
import math from collections import Counter class ManhattanCrepeCart begin function main self begin set testcases = integer input for t in range testcases begin set tuple nr_people max_value = list comprehension integer x for x in split input string set next_locations = counter for p in range nr_people begin set values...
import math from collections import Counter class ManhattanCrepeCart: def main(self): testcases = int(input()) for t in range(testcases): nr_people, max_value = [int(x) for x in input().split(" ")] next_locations = Counter() for p in range(nr_people): ...
Python
zaydzuhri_stack_edu_python
function get_ipc_kernel self begin set key = string ipc_kernel set ipc_file = join path ref_dir paths at key try begin set kernel = call getdata ipc_file end except IOError as e begin set msg = string Error reading IPC kernel reference file: %s. % ipc_file if webapp begin set msg = msg + string (%s) % type e end else b...
def get_ipc_kernel(self): key = "ipc_kernel" ipc_file = os.path.join(self.ref_dir, self.paths[key]) try: kernel = fits.getdata(ipc_file) except IOError as e: msg = "Error reading IPC kernel reference file: %s. " % ipc_file if self.webapp: ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import sys import os set DIR_PATH = directory name path absolute path path __file__ append path join path DIR_PATH string .. string define append path join path DIR_PATH string .. string engine from define import * from engine.engineobject import EngineObjectCircle import time class Torche...
# -*- coding: utf-8 -*- import sys import os DIR_PATH = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(DIR_PATH, "..", "define")) sys.path.append(os.path.join(DIR_PATH, "..", "engine")) from define import * from engine.engineobject import EngineObjectCircle import time class Torche(EngineObj...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import json import PyBoolNet import matplotlib.pyplot as plt import numpy as np function createGraphs primes begin call create_image primes string graph.pdf set igraph = call primes2igraph primes for x in call nodes begin if string GF in x begin set node at x ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import PyBoolNet import matplotlib.pyplot as plt import numpy as np def createGraphs(primes): PyBoolNet.InteractionGraphs.create_image(primes, "graph.pdf") igraph = PyBoolNet.InteractionGraphs.primes2igraph(primes) for x in igraph.nodes(): ...
Python
zaydzuhri_stack_edu_python
function track_changes widget begin if widget in _change_trackers begin raise call RuntimeError string track_changes() called twice for same text widget end if call peer_names begin raise call RuntimeError string track_changes() must be called before create_peer_widget() end set tracker = call _ChangeTracker widget set...
def track_changes(widget: tkinter.Text) -> None: if widget in _change_trackers: raise RuntimeError("track_changes() called twice for same text widget") if widget.peer_names(): raise RuntimeError("track_changes() must be called before create_peer_widget()") tracker = _ChangeTracker(widget) ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment Parte 1 comment C) Usá el clasificador que construiste en el punto anterior y graficá la cantidad estimada de comment nombres de varón y nombres de mujer para cada año. import pandas as pd comment datos set directorio = string F:/modernizacion/ set directorio_salida = string F:/mod...
# -*- coding: utf-8 -*- # Parte 1 # C) Usá el clasificador que construiste en el punto anterior y graficá la cantidad estimada de # nombres de varón y nombres de mujer para cada año. import pandas as pd # datos directorio = 'F:/modernizacion/' directorio_salida = 'F:/modernizacion/salidas/' ...
Python
zaydzuhri_stack_edu_python
import pyshark import os function get_org_name ip begin set command = string whois + dst set process = popen command set result = string read process set marker1 = find result string Organization: + 16 if marker1 > 16 begin set marker2 = find result string RegDate: return result at slice marker1 : marker2 : end else b...
import pyshark import os def get_org_name(ip): command = "whois " + pkt.ip.dst process = os.popen(command) result = str(process.read()) marker1 = result.find('Organization:') + 16 if marker1 > 16: marker2 = result.find('RegDate:') return result[marker1:marker2] else: ret...
Python
zaydzuhri_stack_edu_python
function initialV x L c begin return - 4.0 * c / square root 1 - c ^ 2 * exp x - L / 4.0 / square root 1 - c ^ 2 / 1 + exp 2 * x - L / 4.0 / square root 1 - c ^ 2 - exp - x - L / 4.0 / square root 1 - c ^ 2 / 1 + exp 2 * - x - L / 4.0 / square root 1 - c ^ 2 end function
def initialV(x, L, c): return -4.0*c/np.sqrt(1 - c**2) * \ (np.exp((x - L/4.0)/np.sqrt(1 - c**2)) / (1 + np.exp(2*(x - L/4.0)/np.sqrt(1 - c**2))) - np.exp((-x - L/4.0)/np.sqrt(1 - c**2)) / (1 + np.exp(2*(-x - L/4.0)/(np.sqrt(1 - c**2)))))
Python
nomic_cornstack_python_v1
from tic_tac_toe.core.helpers import get_row_col function is_position_in_range position begin if 1 <= position <= 9 begin return true end return false end function function is_place_available board position begin set tuple row col = call get_row_col position if board at row at col == string begin return true end retur...
from tic_tac_toe.core.helpers import get_row_col def is_position_in_range(position): if 1 <= position <= 9: return True return False def is_place_available(board, position): row, col = get_row_col(position) if board[row][col] == ' ': return True return False def is_winner(board...
Python
zaydzuhri_stack_edu_python
from abc import ABC , abstractmethod from builtins import NotImplementedError from common.replay_buffer import EfficientReplayBuffer class AbstractAgent extends ABC begin function __init__ self buff_size obs_shape_n act_shape_n batch_size prioritized_replay=false alpha=0.6 max_step=none initial_beta=0.6 prioritized_rep...
from abc import ABC, abstractmethod from builtins import NotImplementedError from common.replay_buffer import EfficientReplayBuffer class AbstractAgent(ABC): def __init__(self, buff_size, obs_shape_n, act_shape_n, batch_size, prioritized_replay=False, alpha=0.6, max_step=None, initial_beta=0.6, p...
Python
zaydzuhri_stack_edu_python
comment AST NODE IMPLEMENTATION CLASS ################################################# comment HET PATEL ########################################################### comment 2019MCS2562 ########################################################## comment IIT DELHI #########################################################...
################################################# AST NODE IMPLEMENTATION CLASS ################################################# ########################################################### HET PATEL ########################################################### ########################################################## 2...
Python
zaydzuhri_stack_edu_python
function multiM matrix1 matrix2 begin string Returns a new matrix with each value equal to the multiplication of given matrices set newMatrix = list comprehension list comprehension 0 for i in range length matrix1 at x for x in range length matrix1 comment determines that the dimension product of new matrix will be hei...
def multiM(matrix1, matrix2): '''Returns a new matrix with each value equal to the multiplication of given matrices''' newMatrix = [[0 for i in range(len(matrix1[x]))] for x in range(len(matrix1))] # determines that the dimension product of new matrix will be height (i) of matrix1 and width (j) of matr...
Python
zaydzuhri_stack_edu_python
comment Implementation of the Linear Search on an Unsorted Sequence function linearSearch theValues target begin set n = length theValues for i in range n begin comment if the target is in the ith element, return true if theValues at i == target begin return true end return false end end function comment print(linearSe...
# Implementation of the Linear Search on an Unsorted Sequence def linearSearch(theValues, target): n = len(theValues) for i in range(n): # if the target is in the ith element, return true if theValues[i] == target: return True return False # print(linearSearch([2,5,1,6,7], ...
Python
zaydzuhri_stack_edu_python
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import datasets import os set iris = call load_iris set X = data set Y = target set flowers = target_names set features = feature_names comment print(flowers) # ['setosa' 'versicolor' 'virginica'] comment print(features) # ['sepal len...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import datasets import os iris = datasets.load_iris() X = iris.data Y = iris.target flowers = iris.target_names features = iris.feature_names #print(flowers) # ['setosa' 'versicolor' 'virginica'] #print(features) # ['sepal length ...
Python
zaydzuhri_stack_edu_python
function getMinDistance self **kwargs begin pass end function
def getMinDistance(self, **kwargs): pass
Python
nomic_cornstack_python_v1
comment Untitled - By: katka - po sep 30 2019 comment ball thresholds = ([240, 255, 80, 130, 10, 52 ]) import sensor , image , time , math from pyb import UART function printStatValues begin print string primary_ball_diameter: string primary_ball_diameter print string primary_ball_distance: string primary_ball_distance...
# Untitled - By: katka - po sep 30 2019 #ball thresholds = ([240, 255, 80, 130, 10, 52 ]) import sensor, image, time, math from pyb import UART def printStatValues(): print('primary_ball_diameter: ', str(primary_ball_diameter)) print('primary_ball_distance: ', str(primary_ball_distance)) prin...
Python
zaydzuhri_stack_edu_python
function to_numpy_dtype datatype begin function mpi2npy datatype count begin set dtype = call to_numpy_dtype datatype return if expression count == 1 then dtype else tuple dtype count end function function np_dtype spec begin try begin return call _np_dtype spec end comment pragma: no cover except NameError begin retur...
def to_numpy_dtype(datatype): def mpi2npy(datatype, count): dtype = to_numpy_dtype(datatype) return dtype if count == 1 else (dtype, count) def np_dtype(spec): try: return _np_dtype(spec) except NameError: # pragma: no cover return spec if datatype...
Python
nomic_cornstack_python_v1
function tal_path self begin return string { subject_cn } .tal end function
def tal_path(self) -> str: return f"{self.subject_cn}.tal"
Python
nomic_cornstack_python_v1
function generate_logo upscale_factor filename indent=none begin set temp = call asarray open string sample-heatmaps/logo.png set img = dot temp at tuple Ellipsis slice : 3 : list 0.299 0.587 0.144 set img = img / max img set img = call around img 2 set img = call kron img ones tuple upscale_factor upscale_factor cal...
def generate_logo(upscale_factor, filename, indent=None): temp = np.asarray(Image.open('sample-heatmaps/logo.png')) img = np.dot(temp[..., :3], [0.299, 0.587, 0.144]) img = img / np.max(img) img = np.around(img, 2) img = np.kron(img, np.ones((upscale_factor, upscale_factor))) save_arr(img,...
Python
nomic_cornstack_python_v1
function password_min_length self begin return get pulumi self string password_min_length end function
def password_min_length(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "password_min_length")
Python
nomic_cornstack_python_v1
function go_up self begin debug string issued command go up call send_cmd string Z end function
def go_up(self): log.debug("issued command go up") self.send_cmd('Z')
Python
nomic_cornstack_python_v1
from z3 import * comment Z3 is an SMT solver. In this lecture, we'll discuss comment the basis usage of Z3 through some working example, the comment primary goal is to introduce how to use Z3 to solve comment the satisfiability problems we've discussed in the past comment several lectures. comment We must emphasize tha...
from z3 import * # Z3 is an SMT solver. In this lecture, we'll discuss # the basis usage of Z3 through some working example, the # primary goal is to introduce how to use Z3 to solve # the satisfiability problems we've discussed in the past # several lectures. # We must emphasize that Z3 is just one of the many such S...
Python
zaydzuhri_stack_edu_python
import main function test_class begin set auth_file = open string authorized_keys_test string r set auth_test = read line auth_file call sync_auth_keys_with_main_file string authorized_keys_test string test_main_file set main_file = open string test_main_file string r set main_test = read line main_file print main_test...
import main def test_class(): auth_file = open('authorized_keys_test', 'r') auth_test = auth_file.readline() main.sync_auth_keys_with_main_file('authorized_keys_test', 'test_main_file') main_file = open('test_main_file', 'r') main_test = main_file.readline() print(main_test + "\n" + auth_test)...
Python
zaydzuhri_stack_edu_python
function pre_save self model_instance add begin string Updates username created on ADD only. set value = call pre_save model_instance add if not value and not add begin comment fall back to OS user if not accessing through browser comment better than nothing ... set value = call get_os_username set attribute model_inst...
def pre_save(self, model_instance, add): """Updates username created on ADD only.""" value = super(UserField, self).pre_save(model_instance, add) if not value and not add: # fall back to OS user if not accessing through browser # better than nothing ... value ...
Python
jtatman_500k
function test_create_conversion_event__when_event_is_used_in_multiple_experiments self begin set expected_params = dict string client_version __version__ ; string project_id string 111001 ; string visitors list dict string attributes list dict string entity_id string 111094 ; string type string custom ; string value st...
def test_create_conversion_event__when_event_is_used_in_multiple_experiments(self): expected_params = { 'client_version': version.__version__, 'project_id': '111001', 'visitors': [ { 'attributes': [ {'entity_id': '1...
Python
nomic_cornstack_python_v1
function do_POST self begin comment Drain the data from the client. If we don't, we might write the response comment and close the socket before the client finishes, so they die with EPIPE. set clen = integer get headers string Content-Length string 0 read rfile clen call send_response RESP_CODE RESP_MSG call end_heade...
def do_POST(self): # Drain the data from the client. If we don't, we might write the response # and close the socket before the client finishes, so they die with EPIPE. clen = int(self.headers.get('Content-Length', '0')) self.rfile.read(clen) self.send_response(self.RESP_CODE, self.RESP_MSG) s...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Jul 16 16:34:22 2018 @author: Benson comment Variables set x = 20 set x = string Billy comment Integer set x1 = 20 set x2 = 1 set x3 = 0 set x4 = - 5 set x5 = - 412 comment float set f1 = 20.587 set f2 = 1.5 set f3 = 0.0 set f4 = - 5.2 se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 16 16:34:22 2018 @author: Benson """ # Variables x = 20 x = "Billy" # Integer x1 = 20 x2 = 1 x3 = 0 x4 = -5 x5 = -412 # float f1 = 20.587 f2 = 1.5 f3 = 0.0 f4 = -5.2 f5 = -412.5 # boolean b1 = True b2 = False # string s1 = "Hello World" s2 ...
Python
zaydzuhri_stack_edu_python
function flattened_to_grdIm flattened_array nx ny mask=none begin if mask is none begin set mask = as type ones nx * ny string bool end set grd_array = ones nx * ny * nan set grd_array at mask = flattened_array set grd_im = reshape grd_array tuple nx ny order=string F return grd_im end function
def flattened_to_grdIm(flattened_array,nx,ny,mask=None): if mask is None: mask = np.ones(nx*ny).astype('bool') grd_array = np.ones(nx*ny)*np.nan grd_array[mask] = flattened_array grd_im = grd_array.reshape((nx,ny),order='F') return grd_im
Python
nomic_cornstack_python_v1
import signal class AlarmException extends Exception begin pass end class function alarmHandler signum frame begin raise AlarmException end function function Input prompt=string timeout=2 begin call signal SIGALRM alarmHandler call alarm timeout end function
import signal class AlarmException(Exception): pass def alarmHandler(signum, frame): raise AlarmException def Input(prompt='', timeout=2): signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(timeout)
Python
zaydzuhri_stack_edu_python
function mass_matrix self begin return _mass_matrix end function
def mass_matrix(self): return self._mass_matrix
Python
nomic_cornstack_python_v1
function _test_encode_message self message_obj MessageType begin comment encoding gives bytes delimited by ';' set byte_str = decode encode message_obj comment so we have to get rid of the delimiter set byte_str = split byte_str MSG_DELIM at 0 set mtg_req_obj = call decode_message byte_str MessageType comment if decodi...
def _test_encode_message(self, message_obj:"SocketMessage", MessageType): # encoding gives bytes delimited by ';' byte_str = message_obj.encode().decode() # so we have to get rid of the delimiter byte_str = byte_str.split(MSG_DELIM)[0] mtg_req_obj = decode_message(byte_str, Mes...
Python
nomic_cornstack_python_v1
import json comment JSON string set json_data = string {"employees":[{"firstName":"John","lastName":"Doe","age":30,"address":{"street":"123 Main St","city":"New York"}},{"firstName":"Jane","lastName":"Smith","age":35,"address":{"street":"456 Elm St","city":"San Francisco"}}]} comment Parsing JSON set data = loads json_...
import json # JSON string json_data = '{"employees":[{"firstName":"John","lastName":"Doe","age":30,"address":{"street":"123 Main St","city":"New York"}},{"firstName":"Jane","lastName":"Smith","age":35,"address":{"street":"456 Elm St","city":"San Francisco"}}]}' # Parsing JSON data = json.loads(json_data) # Accessing...
Python
greatdarklord_python_dataset
class OrderedDict begin function __init__ self begin set items = list end function function __setitem__ self key value begin for item in items begin if item at 0 == key begin set item at 1 = value break end end for else begin append items list key value end end function function __getitem__ self key begin for item in ...
class OrderedDict: def __init__(self): self.items = [] def __setitem__(self, key, value): for item in self.items: if item[0] == key: item[1] = value break else: self.items.append([key, value]) def __getitem__(self, key): ...
Python
flytech_python_25k
comment -*- coding: UTF-8 -*- import sys import redis comment Args Input filter comment if len(sys.argv) < 3: comment print "python server port HASH_KEY_NAME" comment sys.exit() comment else: comment hashkey = sys.argv[1] comment redis_hash_del online function redis_hash_del server port hashkey begin set r = call Redis...
# -*- coding: UTF-8 -*- import sys import redis # Args Input filter # if len(sys.argv) < 3: # print "python server port HASH_KEY_NAME" # sys.exit() #else: # hashkey = sys.argv[1] # redis_hash_del online def redis_hash_del(server, port, hashkey): r = redis.Redis(host=server, port=port, db=0) if r.e...
Python
zaydzuhri_stack_edu_python
function after_new self form instance begin comment Set the 'afternew' URL set project = project if project != none and order < 0 begin comment Calculate how many products set product_count = count projectquestionproducts comment Make sure the new project gets changed set order = product_count end comment Return positi...
def after_new(self, form, instance): ## Set the 'afternew' URL project = instance.project if project != None and instance.order < 0: # Calculate how many products product_count = project.projectquestionproducts.count() # Make sure the new project gets changed...
Python
nomic_cornstack_python_v1
function sum_integers lst begin set total = 0 set non_int_count = 0 for i in lst begin try begin set total = total + integer i end except tuple TypeError ValueError begin set non_int_count = non_int_count + 1 end end return tuple total non_int_count end function
def sum_integers(lst): total = 0 non_int_count = 0 for i in lst: try: total += int(i) except (TypeError, ValueError): non_int_count += 1 return total, non_int_count
Python
jtatman_500k
comment !/usr/bin/env python3 comment https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree comment 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。 comment 如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。 comment 给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。 comment 示例 1: comment 输入: comment 2 comment / \ comment 2 5...
#!/usr/bin/env python3 # https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree # 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。 # 如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。  # 给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。 # # 示例 1: # 输入: # 2 # / \ # 2 5 # / \ # 5 7 # 输出: 5 # 说明: 最小的值是 2 ...
Python
zaydzuhri_stack_edu_python
function _recordRepr self rec short=false begin set key_str = if expression key is none then string else string (key=%s) % tuple key set prefix = string %s%s: % tuple name key_str set data_str = if expression short then call _dataStr string data else call _dataRepr string data set data_str = replace data_str string s...
def _recordRepr(self, rec, short=False): key_str = "" if rec.key is None else " (key=%s)" % (rec.key,) prefix = '%s%s: ' % (self._server.settings[rec.ID].name, key_str) data_str = self._dataStr(str(rec.data)) if short else self._dataRepr(str(rec.data)) data_str = data_str.replace('\n...
Python
nomic_cornstack_python_v1
function make_scale begin return call RadioItems id=string scale_radio options=list dict string label string linear ; string value string linear dict string label string logarithmic ; string value string log value=string linear labelStyle=dict string display string inline-block end function
def make_scale(): return dcc.RadioItems( id='scale_radio', options=[ {'label': 'linear', 'value': 'linear'}, {'label': 'logarithmic', 'value': 'log'}, ], value='linear', labelStyle={'display': 'inline-block'}, )
Python
nomic_cornstack_python_v1
function init_group_type self group_type begin assert group_type not in groups set groups at group_type = dict set next_id at group_type = 0 end function
def init_group_type(self, group_type): assert group_type not in self.groups self.groups[group_type] = {} self.next_id[group_type] = 0
Python
nomic_cornstack_python_v1
comment gets 5 sample tweets from the collection from pymongo import MongoClient from pprint import pprint set client = call MongoClient set db = twitter set tweets = tweets set pipeline = list dict string $sample dict string size 5 set samp = call aggregate pipeline allowDiskUse=true set i = 1 for x in samp begin with...
#gets 5 sample tweets from the collection from pymongo import MongoClient from pprint import pprint client = MongoClient() db = client.twitter tweets = db.tweets pipeline = [ { "$sample": { "size": 5 } } ] samp = tweets.aggregate(pipeline, allowDiskUse=True) i = 1 for x in samp: with open('tweet_example{0}.txt'...
Python
zaydzuhri_stack_edu_python
from operator import xor from functools import reduce function r v p e begin for tuple i j in zip range p e range e - 1 p - 1 begin if i >= j begin return e end set tuple v at i ? 255 v at j ? 255 = tuple v at j ? 255 v at i ? 255 end comment why return e? e happens to be the next value of the pointer, so we can do the...
from operator import xor from functools import reduce def r(v, p, e): for (i,j) in zip(range(p,e),range(e-1,p,-1)): if i >= j: return e v[i&255],v[j&255] = v[j&255],v[i&255] return e # why return e? e happens to be the next value of the pointer, so we can do the side efffect + calculate our nex...
Python
zaydzuhri_stack_edu_python
from pyowm.owm import OWM import datetime from pyowm.utils.config import get_default_config from utils import clds , wind_converter from loll import Configs from clothes import clothes function heat_config heat temp begin if heat == 0 begin return temp end else if heat == 1 begin return temp + 2 end else if heat == - 1...
from pyowm.owm import OWM import datetime from pyowm.utils.config import get_default_config from utils import clds, wind_converter from loll import Configs from clothes import clothes def heat_config(heat, temp): if heat == 0: return temp elif heat == 1: return temp + 2 elif heat == -1: ...
Python
zaydzuhri_stack_edu_python
function zip xs ys begin return list comprehension tuple xs at index ys at index for index in range min length xs length ys end function
def zip(xs, ys): return [(xs[index], ys[index]) for index in range(min(len(xs), len(ys)))]
Python
nomic_cornstack_python_v1
string U-Net Model for Height, Weight, Mask, Tennis Ball and Joint Prediction. @author: Can Altinigne This script includes a modified version U-Net Architecture for BMAI Project. import torch import torch.nn as nn import torch.nn.functional as F class DownBlock extends Module begin string Downsampling block for U-Net A...
""" U-Net Model for Height, Weight, Mask, Tennis Ball and Joint Prediction. @author: Can Altinigne This script includes a modified version U-Net Architecture for BMAI Project. """ import torch import torch.nn as nn import torch.nn.functional as F class DownBlock(nn.Module): """ Downsampling block for...
Python
zaydzuhri_stack_edu_python
function traffic_paris_request path begin set tuple numero_mois the_day date day day_week = call traffic_paris_function_reuqest1 path set num = list for i in numero_mois begin try begin set i = integer i append num i end except any begin pass end end if the_day == day_week and num at 0 == day begin return string il y ...
def traffic_paris_request(path): numero_mois, the_day, date, day, day_week = traffic_paris_function_reuqest1(path) num = [] for i in numero_mois: try: i = int(i) num.append(i) except: pass if the_day == day_week and nu...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment vim: ai ts=4 sts=4 et sw=4 string Forms and tools to create and fill reports from generic_reports import itertools from django import forms from django.utils.safestring import mark_safe from django.forms import ValidationError import eav from simple_loc...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 """ Forms and tools to create and fill reports from generic_reports """ import itertools from django import forms from django.utils.safestring import mark_safe from django.forms import ValidationError import eav from simple_locations.mo...
Python
zaydzuhri_stack_edu_python
from microbit import * from random import randint import music set score = 0 set snake = list list 0 0 set food = list random integer 1 4 random integer 1 4 set directions = list list 1 0 list 0 - 1 list - 1 0 list 0 1 comment 0:right 1:Up 2:left 3:down global direction set direction = 0 function Rocker_loop_test begin...
from microbit import * from random import randint import music score = 0 snake = [[0, 0]] food = [randint(1, 4), randint(1, 4)] directions = [[1, 0], [0, -1], [-1, 0], [0, 1]] global direction # 0:right 1:Up 2:left 3:down direction = 0 def Rocker_loop_test(): direction = -1 x = pin1.read_analog() y = pi...
Python
zaydzuhri_stack_edu_python
string Finds the sum of the digits in a given factorial. function fact_math num begin string returns the factorial of a given number :param num: int value num :return: int value if num == 1 begin return 1 end else begin return num * call fact_math num - 1 end end function set a = call fact_math 100 print sum list compr...
""" Finds the sum of the digits in a given factorial. """ def fact_math(num): """ returns the factorial of a given number :param num: int value num :return: int value """ if num == 1: return 1 else: return num * fact_math(num-1) a = fact_math(100) print(sum([int(i) for i i...
Python
zaydzuhri_stack_edu_python
function manage_addItemsToZenMenu self menuid items=none begin if not items begin set items = list dict end set menu = get attribute zenMenus menuid none if not menu begin set menu = call manage_addZenMenu menuid end if is instance items dict begin set items = list items end for item in items begin call manage_addZenM...
def manage_addItemsToZenMenu(self, menuid, items=None): if not items: items = [{}] menu = getattr(self.zenMenus, menuid, None) if not menu: menu = self.manage_addZenMenu(menuid) if isinstance(items, dict): items = [items] for item in items: menu.manage_add...
Python
nomic_cornstack_python_v1
function list_duplicates seq begin set seen = set set seen_add = add set seen_twice = set generator expression x for x in seq if x in seen or call seen_add x return list seen_twice end function set a = list 1 2 3 2 1 5 6 5 5 5 print call list_duplicates a
def list_duplicates(seq): seen = set() seen_add = seen.add seen_twice = set( x for x in seq if x in seen or seen_add(x) ) return list( seen_twice ) a = [1,2,3,2,1,5,6,5,5,5] print(list_duplicates(a))
Python
zaydzuhri_stack_edu_python
import sqlite3 import random import time from models import * from poker import Poker from classifier import Classifier class GamePlayer extends object begin set _name = string set _cards = list set _money = 300 set _move = string checked set _bet = 0 set poker = call Poker function get_action self begin return if ex...
import sqlite3 import random import time from models import * from poker import Poker from classifier import Classifier class GamePlayer(object): _name = " " _cards = [] _money = 300 _move = "checked" _bet = 0 poker = Poker() def get_action(self): return (1 if self._move == "raised" else 2 if self._move =...
Python
zaydzuhri_stack_edu_python
function denied self begin return call cast bool get _properties string denied end function
def denied(self) -> bool: return typing.cast( bool, self._properties.get("denied"), )
Python
nomic_cornstack_python_v1
import csv import os from multiprocessing.pool import ThreadPool from time import time as timer import requests function fetch_url entry begin set tuple filename uri = entry set path = format string data/2018/matches/{0} filename if not exists path path begin set r = get requests uri stream=true if status_code == 200 b...
import csv import os from multiprocessing.pool import ThreadPool from time import time as timer import requests def fetch_url(entry): filename, uri = entry path = "data/2018/matches/{0}".format(filename) if not os.path.exists(path): r = requests.get(uri, stream=True) if r.status_code == ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from functools import reduce from itertools import count , combinations from graph import SimpleGraph class OnlineReducedGraph extends object begin function __init__ self graph state=none begin set _graph = graph if state is none begin call _initializeState end else begin set tuple _keys _v...
#!/usr/bin/env python from functools import reduce from itertools import count, combinations from graph import SimpleGraph class OnlineReducedGraph(object): def __init__(self, graph, state=None): self._graph = graph if state is None: self._initializeState() else: ...
Python
zaydzuhri_stack_edu_python
function piecewise_rbf_backward input T ep1 ep2 begin set output = clone input set below_T_inds = input < T set above_T_inds = input >= T set output at below_T_inds = call gaussian_drbf input - T ep1 at below_T_inds set output at above_T_inds = call gaussian_drbf input - T ep2 at above_T_inds return output end function
def piecewise_rbf_backward(input, T, ep1, ep2): output = input.clone() below_T_inds = input < T above_T_inds = input >= T output[below_T_inds] = gaussian_drbf(input-T, ep1)[below_T_inds] output[above_T_inds] = gaussian_drbf(input-T, ep2)[above_T_inds] return output
Python
nomic_cornstack_python_v1
function uniform_random_sampler sample_area begin set new_point = call Point set x = uniform sample_area at 0 sample_area at 1 set y = uniform sample_area at 0 sample_area at 1 return new_point end function
def uniform_random_sampler(sample_area): new_point = Point() new_point.x = random.uniform(sample_area[0], sample_area[1]) new_point.y = random.uniform(sample_area[0], sample_area[1]) return new_point
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment coding=utf-8 comment title :markup.py comment description : comment author :JackieTsui comment organization :pytoday.org comment date :2017/11/30 下午9:23 comment email :jackietsui72@gmail.com comment notes : comment ================================================== comment Import t...
#!/usr/bin/env python3 # coding=utf-8 # title :markup.py # description : # author :JackieTsui # organization :pytoday.org # date :2017/11/30 下午9:23 # email :jackietsui72@gmail.com # notes : # ================================================== # Import the module needed...
Python
zaydzuhri_stack_edu_python
function reward input begin set state = array list input at 0 input at 1 set action = input at 2 set action = call clip action - 2.0 2.0 set costs = call angle_normalize state at 0 ^ 2 + 0.1 * state at 1 ^ 2 + 0.001 * action ^ 2 return - costs end function
def reward(input): state = np.array([input[0], input[1]]) action = input[2] action = np.clip(action, -2.0, 2.0) costs = angle_normalize(state[0])**2 + .1 * state[1]**2 + .001 * (action**2) return - costs
Python
nomic_cornstack_python_v1
import http.client import json import time import timeit import sys import collections from pygexf.gexf import * comment implement your data retrieval code here set key = argv at 0 set url = string /api/v3/lego/sets/?key= + key + string &page_size=300&min_parts=1125&ordering=num_parts set connection = call HTTPSConnect...
import http.client import json import time import timeit import sys import collections from pygexf.gexf import * # # implement your data retrieval code here # key=sys.argv[0] url='/api/v3/lego/sets/?key='+ key +'&page_size=300&min_parts=1125&ordering=num_parts' connection = http.client.HTTPSConnection('rebrickable.co...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment coding: utf-8 from itertools import combinations from functools import reduce comment Числа comment Заполните код приведенных ниже функций. Функция main() уже настроена comment для вызова функций с несколькими различными параметрами, comment и выводит 'OK' в случае, если вызов функции ...
#!/usr/bin/python3 # coding: utf-8 from itertools import combinations from functools import reduce # Числа # Заполните код приведенных ниже функций. Функция main() уже настроена # для вызова функций с несколькими различными параметрами, # и выводит 'OK' в случае, если вызов функции корректен. # Начальный код каждой ф...
Python
zaydzuhri_stack_edu_python
function decision_function self x begin call check_is_fitted self list string w_ string c_w_ set x = call check_array x if shape at 1 != shape at 1 begin raise call ValueError string X has wrong number of features found=%d expected=%d % tuple shape at 1 shape at 1 end set dist = call _compute_distance x set foo = lambd...
def decision_function(self, x): check_is_fitted(self, ['w_', 'c_w_']) x = validation.check_array(x) if x.shape[1] != self.w_.shape[1]: raise ValueError("X has wrong number of features\n" "found=%d\n" "expected=%d" % (sel...
Python
nomic_cornstack_python_v1
function parse self begin comment modify context storing partial row set last_row = row at 0 comment modify context with type of row holded set row_type = string tbl_head1_ini_part end function
def parse(self): # modify context storing partial row self.context.last_row = self.row[0] # modify context with type of row holded self.context.row_type = "tbl_head1_ini_part"
Python
nomic_cornstack_python_v1
comment !python3 function calculatedMoney first second begin print format string Amount = {} * {} = {} first second first * second end function if __name__ == string __main__ begin set first = integer input string Quantity: set second = integer input string Prices : call calculatedMoney first second end
#!python3 def calculatedMoney(first, second): print("Amount = {} * {} = {}".format(first, second, first * second)) if __name__ == '__main__': first = int(input("Quantity: ")) second = int(input("Prices : ")) calculatedMoney(first, second)
Python
zaydzuhri_stack_edu_python
function on_message self data begin string Parsing data, and try to call responding message comment Trying to parse response set data = loads data if not data at string name is none begin debug string %s: receiving message %s % tuple data at string name data at string data set fct = get attribute self string on_ + data...
def on_message(self, data): """ Parsing data, and try to call responding message """ # Trying to parse response data = json.loads(data) if not data["name"] is None: logging.debug("%s: receiving message %s" % (data["name"], data["data"])) fct = getattr(self, "on_" ...
Python
jtatman_500k
import numpy as np comment def delete_column(matrix,col): comment return (np.delete(matrix,col,axis =1)) function delete_row matrix row n m begin set matrice = list for i in range 0 n begin if i != row begin set riga = list for j in range 0 m begin append riga matrix at tuple i j end append matrice riga end end retur...
import numpy as np #def delete_column(matrix,col): # return (np.delete(matrix,col,axis =1)) def delete_row(matrix,row,n,m): matrice = [] for i in range(0,n): if(i!= row): riga = [] for j in range(0,m): riga.append(matrix[i,j]) matrice.append(riga) return(np.array(matrice)) def delete_column(mat...
Python
zaydzuhri_stack_edu_python
import json comment Sample JSON data set json_data = string { "products": [ { "name": "apple", "cost": 1.99 }, { "name": "banana", "cost": 0.99 }, { "name": "carrot", "cost": 0.49 }, { "name": "orange", "cost": 1.49 } ] } comment Parse the JSON data set data = loads json_data comment Initialize variables set cheapest_p...
import json # Sample JSON data json_data = ''' { "products": [ { "name": "apple", "cost": 1.99 }, { "name": "banana", "cost": 0.99 }, { "name": "carrot", "cost": 0.49 }, { "name": "orange", "cost": 1.49 } ] } ''' # Parse the JSON data...
Python
jtatman_500k
class Solution begin function findTargetSumWays self nums S begin comment 我写的递归,是对的,但是超时。应该用动态规划…… set cnt = 0 set n = length nums function helper start_idx S begin nonlocal cnt if start_idx == n - 1 begin comment 这里正负都加1,这是因为如果最后一个数是0,+-0都可以。 if - nums at start_idx == S begin set cnt = cnt + 1 end if nums at start_idx...
class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: # 我写的递归,是对的,但是超时。应该用动态规划…… cnt = 0 n = len(nums) def helper(start_idx, S): nonlocal cnt if start_idx == n-1: # 这里正负都加1,这是因为如果最后一个数是0,+-0都可以。 if -nums[...
Python
zaydzuhri_stack_edu_python
string Created on Sat Aug 3 21:13:57 2019 @author: hitesh comment -------------- Two Sum ----------------------------------- comment Sample Input set arr = list 3 5 - 4 8 11 1 - 1 6 set t = 10 comment Both the solution works on O(n) time || O(n) Space class Solution begin function twoNumberSum self array targetSum begi...
""" Created on Sat Aug 3 21:13:57 2019 @author: hitesh """ # -------------- Two Sum ----------------------------------- # Sample Input arr = [3, 5,-4, 8, 11, 1, -1, 6] t = 10 # Both the solution works on O(n) time || O(n) Space class Solution: def twoNumberSum(self, array, targetSum): result ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf8 -*- comment Tannon Kew; UZH Einführung in die MLTA 2018 import sys import os from lxml import etree as ET import re import argparse as ap comment To run: comment $ python3 build_line_aligned_files.py <directiory containing l1 corpus, l2 ## corpus and alignment file...
# !/usr/bin/env python3 # -*- coding: utf8 -*- # Tannon Kew; UZH Einführung in die MLTA 2018 import sys import os from lxml import etree as ET import re import argparse as ap ## To run: ## $ python3 build_line_aligned_files.py <directiory containing l1 corpus, l2 ## corpus and alignment file> <lang1_code> <lang2_cod...
Python
zaydzuhri_stack_edu_python
function maximum_dot_count self begin return _maximum_dot_count end function
def maximum_dot_count(self) -> Union[int, None]: return self._maximum_dot_count
Python
nomic_cornstack_python_v1
from django.conf import settings from pymongo import MongoClient class MongoConn extends object begin set clients = dict decorator classmethod function client cls name=string default begin if name not in clients begin if name not in MONGODB begin return none end set clients at name = call cls get MONGODB name end retu...
from django.conf import settings from pymongo import MongoClient class MongoConn(object): clients = {} @classmethod def client(cls, name='default'): if name not in cls.clients: if name not in settings.MONGODB: return None cls.clients[name] = cls(settings.MON...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf8 -*- string Created on 2019/7/11 13:51 @author: WMaker string 15 图像阈值 目标 • 本节你将学到简单阈值,自适应阈值,Otsu’s 二值化等 • 将要学习的函数有 cv2.threshold,cv2.adaptiveThreshold 等。 15.1 简单阈值 与名字一样,这种方法非常简单。但像素值高于阈值时,我们给这个像素 赋予一个新值(可能是白色),否则我们给它赋予另外一种颜色(也许是黑色)。 这个函数就是 cv2.threshhold()。这个函数的第一个参数就是原图像,原图 像应该是灰度图。第二个参数就是用来对像素...
# -*- coding:utf8 -*- """ Created on 2019/7/11 13:51 @author: WMaker """ ''' 15 图像阈值 目标 • 本节你将学到简单阈值,自适应阈值,Otsu’s 二值化等 • 将要学习的函数有 cv2.threshold,cv2.adaptiveThreshold 等。 15.1 简单阈值 与名字一样,这种方法非常简单。但像素值高于阈值时,我们给这个像素 赋予一个新值(可能是白色),否则我们给它赋予另外一种颜色(也许是黑色)。 这个函数就是 cv2.threshhold()。这个函数的第一个参数就是原图像,原图 像应该是灰度图。第二个参数就是用来对像素值进行分类的...
Python
zaydzuhri_stack_edu_python
function order_query self query begin return call order_by call desc end function
def order_query(self, query: Query) -> Query: return query.order_by(self.get_model().created_at.desc())
Python
nomic_cornstack_python_v1
function replace_gdd_climo ctx df table date1 date2 begin comment Short circuit if we are not doing departures if ctx at string var in list string gdd_sum string sdd_sum begin return df end set d1 = string format time date1 string %m%d set d2 = string format time date2 string %m%d set daylimit = string sday >= ' { d1 }...
def replace_gdd_climo(ctx, df, table, date1, date2): # Short circuit if we are not doing departures if ctx["var"] in ["gdd_sum", "sdd_sum"]: return df d1 = date1.strftime("%m%d") d2 = date2.strftime("%m%d") daylimit = f"sday >= '{d1}' and sday <= '{d2}'" if d1 > d2: daylimit = f"...
Python
nomic_cornstack_python_v1
function send_stats_reply_table self xid table_stats reply_more=false begin call _log_send_msg string OFPT_STATS_REPLY / OFPST_TABLE table_stats=table_stats reply_more=reply_more call _send_stats_reply xid OFPST_TABLE reply_more=reply_more data=list comprehension call serialize for ts in table_stats end function
def send_stats_reply_table(self, xid, table_stats, reply_more=False): self._log_send_msg('OFPT_STATS_REPLY / OFPST_TABLE', table_stats=table_stats, reply_more=reply_more) self._send_stats_reply( xid, OFPST_TABLE, reply_more=reply_more, data=[ts.seriali...
Python
nomic_cornstack_python_v1
import click from xeriff_ripoll import actions decorator call group function cli begin pass end function decorator call command function fetch begin set action = call FetchAndSaveLyrics execute action end function decorator call command decorator call argument string song_id function get song_id begin set action = call...
import click from xeriff_ripoll import actions @click.group() def cli(): pass @cli.command() def fetch(): action = actions.FetchAndSaveLyrics() action.execute() @cli.command() @click.argument('song_id') def get(song_id): action = actions.GetSongById() song = action.execute(song_id) print_...
Python
zaydzuhri_stack_edu_python
function user_absent name begin string Ensure a user is not present name username to remove if it exists Examples: .. code-block:: yaml delete: onyx.user_absent: - name: daniel set ret = dict string name name ; string result false ; string changes dict ; string comment string set old_user = call string get_user usern...
def user_absent(name): ''' Ensure a user is not present name username to remove if it exists Examples: .. code-block:: yaml delete: onyx.user_absent: - name: daniel ''' ret = {'name': name, 'result': False, 'changes': {}, ...
Python
jtatman_500k
function phone_configs self begin return get pulumi self string phone_configs end function
def phone_configs(self) -> Sequence['outputs.GetQuickConnectQuickConnectConfigPhoneConfigResult']: return pulumi.get(self, "phone_configs")
Python
nomic_cornstack_python_v1