code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function generate_random_state length=48 chars=UNICODE_ASCII_CHARACTER_SET
begin
set rand = call SystemRandom
return join string generator expression random choice chars for x in range length
end function | def generate_random_state(length=48, chars=UNICODE_ASCII_CHARACTER_SET):
rand = SystemRandom()
return "".join(rand.choice(chars) for x in range(length)) | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
comment import matplotlib.pyplot as plt
import cv2 as cv
import os
import tensorflow as tf
from tensorflow.keras.models import load_model
comment Load Keras models
comment for Emopy inspired CNN trained for 50 epochs on image size (64,64)
set model = call load_model string /home/b... | import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
import cv2 as cv
import os
import tensorflow as tf
from tensorflow.keras.models import load_model
# Load Keras models
# for Emopy inspired CNN trained for 50 epochs on image size (64,64)
model = load_model("/home/becode/AI/skyebase/Bagaar/model_em... | Python | zaydzuhri_stack_edu_python |
import unittest
import numpy as np
from npv import NPV
from npv import generate_annuity
class TestNPVClass extends TestCase
begin
function setUp self
begin
set rate_a = 0.000123456
set rate_b = 0
set rate_c = 0.1
end function
comment test .shift_to() works
comment test .shift_to() checks type
comment shift_to formula: ... | import unittest
import numpy as np
from npv import NPV
from npv import generate_annuity
class TestNPVClass(unittest.TestCase):
def setUp(self):
self.rate_a = 0.000123456
self.rate_b = 0
self.rate_c = 0.1
# test .shift_to() works
# test .shift_to() checks type
# shift_to formula: Price / ((1 + rate) ^ time... | Python | zaydzuhri_stack_edu_python |
function level_to_mag level min_mag max_mag
begin
if level is none
begin
return round call rand * max_mag - min_mag + min_mag 1
end
else
begin
return round level / _MAX_LEVEL * max_mag - min_mag + min_mag 1
end
end function | def level_to_mag(level: Optional[int], min_mag: float,
max_mag: float) -> float:
if level is None:
return round(np.random.rand() * (max_mag - min_mag) + min_mag, 1)
else:
return round(level / _MAX_LEVEL * (max_mag - min_mag) + min_mag, 1) | Python | nomic_cornstack_python_v1 |
import numpy as np
function create_confusion_matrix real_classes pred_classes classes
begin
string Creates a confusion matrix based on prediction and the respective predictions. real_classes : array containing the real classes (the order of the instances must match the predicted classes array) pred_classes : array cont... | import numpy as np
def create_confusion_matrix(real_classes, pred_classes, classes):
"""Creates a confusion matrix based on prediction and the respective predictions.
real_classes : array containing the real classes (the order of the instances must match the predicted classes array)
pred_classes : array co... | Python | zaydzuhri_stack_edu_python |
function buildPackets self
begin
return input
end function | def buildPackets(self):
return self.input | Python | nomic_cornstack_python_v1 |
string Created on 12/04/2013 @author: Javier
set archivo = string A-large.in
set entrada = call file archivo
set jugador_x = string X
set jugador_0 = string O
set comodin = string T
set libre = string .
function procesaTablero tablero caso
begin
set libres = 0
set celda = string
for i in range 0 4
begin
comment vertic... | '''
Created on 12/04/2013
@author: Javier
'''
archivo = "A-large.in"
entrada = file(archivo)
jugador_x = "X"
jugador_0 = "O"
comodin = "T"
libre = "."
def procesaTablero(tablero, caso):
libres = 0
celda = ""
for i in range(0, 4):
#vertical
celda = tablero[0][i]
en... | Python | zaydzuhri_stack_edu_python |
from db import db
from typing import Dict , Optional , List
class Detector extends Model
begin
string Represents detector that a user wants to be notified for Fields: id --> url ID. Unique to every detector. keywords --> The keywords that the user is detectoring for min_price --> The minimum price that is associated wi... | from db import db
from typing import Dict, Optional, List
class Detector(db.Model):
"""
Represents detector that a user wants to be notified for\n
Fields:\n
id --> url ID. Unique to every detector.\n
keywords --> The keywords that the user is detectoring for\n
min_price --> The minimum price th... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
import urllib2
import time , datetime
comment Internet libs
import httplib , socket , urlparse , urllib , urllib2
comment XML Parsing for API
from xml.dom import minidom
function send_request webpage
begin
set request = call Request encode webpage string utf8
comme... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import time, datetime
import httplib, socket, urlparse, urllib, urllib2 #Internet libs
from xml.dom import minidom #XML Parsing for API
def send_request(webpage):
request = urllib2.Request(webpage.encode('utf8'))
# request.add_header('User-Agent',... | Python | zaydzuhri_stack_edu_python |
string VIEWS FILE MANAGE PRODUCTS
from django.shortcuts import render , redirect
from webapp.modules.tools.clean_sentence import remove_special_char
from webapp.modules.tools.builder import build_data
from webapp.modules.psql.db_manager import save_research
from webapp.modules.psql.db_manager import add_data , add_nutr... | """
VIEWS FILE MANAGE PRODUCTS
"""
from django.shortcuts import render, redirect
from webapp.modules.tools.clean_sentence import remove_special_char
from webapp.modules.tools.builder import build_data
from webapp.modules.psql.db_manager import save_research
from webapp.modules.psql.db_manager import add_data, add_nutr... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2
function euclidDistance point1 point2
begin
string Input : 2 lists Get euclidean distance of point1 and point2.
return norm array point1 - array point2
end function
function clusters_distance cluster1 cluster2
begin
string Input : 2 cluster lists Get distance between two clusters.
return m... | import numpy as np
import cv2
def euclidDistance(point1, point2):
"""
Input : 2 lists
Get euclidean distance of point1 and point2.
"""
return np.linalg.norm(np.array(point1) - np.array(point2))
def clusters_distance(cluster1, cluster2):
"""
Input : 2 cluster lists
Get distance betwee... | Python | zaydzuhri_stack_edu_python |
for word in range 0 length data 2
begin
set key = data at word
set value = data at word + 1
set bakery at key = integer value
end
set search_product = split input
for product in search_product
begin
if product in bakery
begin
print string We have { bakery at product } of { product } left
end
else
begin
print string Sor... | for word in range(0, len(data), 2):
key = data[word]
value = data[word + 1]
bakery[key] = int(value)
search_product = input().split()
for product in search_product:
if product in bakery:
print(f'We have {bakery[product]} of {product} left')
else:
print(f"Sorry, we don't have {produc... | Python | zaydzuhri_stack_edu_python |
import csv
from random import *
global letter_count
set race_name = string grippli
set letter_count = 0
class letter
begin
comment Each letter has a lowercase character, an uppercase character, and
comment identifiers as vowel or consonant.
function __init__ self lowerchar upperchar is_vowel is_consonant
begin
global l... | import csv
from random import *
global letter_count
race_name = 'grippli'
letter_count = 0
class letter():
# Each letter has a lowercase character, an uppercase character, and
# identifiers as vowel or consonant.
def __init__(self, lowerchar, upperchar, is_vowel, is_consonant):
global ... | Python | zaydzuhri_stack_edu_python |
function test_dtype_int_multigraph self
begin
set G = call MultiGraph call complete_graph 3
set A = call to_numpy_array G dtype=int
call assert_equal dtype int
end function | def test_dtype_int_multigraph(self):
G = nx.MultiGraph(nx.complete_graph(3))
A = nx.to_numpy_array(G, dtype=int)
assert_equal(A.dtype, int) | Python | nomic_cornstack_python_v1 |
import complex.complex_pb2 as complex_pb2
set complex_message = call ComplexMessage
set id = 123
set name = string I am a dummy message
print string Complex Message with one dummy complex_message
comment Multiple dummy
set first_multiple_dummy = add multiple_dummy
set id = 345
set name = string I the first element
prin... | import complex.complex_pb2 as complex_pb2
complex_message = complex_pb2.ComplexMessage()
complex_message.one_dummy.id = 123
complex_message.one_dummy.name = "I am a dummy message"
print("Complex Message with one dummy",complex_message)
#Multiple dummy
first_multiple_dummy = complex_message.multiple_dummy.add()
fir... | Python | zaydzuhri_stack_edu_python |
import csv
import requests
from bs4 import BeautifulSoup as bs
from fake_useragent import UserAgent
set url = string https://datalab.naver.com/keyword/realtimeList.naver?where=main
set headers = dict string User-Agent chrome
set response = get requests url headers=headers
comment 요청한 페이지 확인하기
comment print(response.con... | import csv
import requests
from bs4 import BeautifulSoup as bs
from fake_useragent import UserAgent
url = "https://datalab.naver.com/keyword/realtimeList.naver?where=main"
headers = {"User-Agent": UserAgent().chrome}
response = requests.get(url, headers=headers)
# 요청한 페이지 확인하기
# print(response.content)
html = bs(res... | Python | zaydzuhri_stack_edu_python |
from nltk import word_tokenize , pos_tag
from nltk.corpus import wordnet as wn
import nltk
import string , re
function penn_to_wn tag
begin
string Convert between a Penn Treebank tag to a simplified Wordnet tag
if starts with tag string N
begin
return string n
end
if starts with tag string V
begin
return string v
end
i... | from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
import nltk
import string ,re
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if ... | Python | zaydzuhri_stack_edu_python |
from time import time
set start = time
function isPrime n
begin
if n == 2 or n == 3
begin
return true
end
if n <= 1 or n % 2 == 0 or n % 3 == 0
begin
return false
end
comment Prime numbers > 3 are in form of 6k +/- 1.
if n % 6 != 1 and n % 6 != 5
begin
return false
end
set sqr = integer n ^ 0.5 + 0.5
for i in range 5 s... | from time import time
start = time()
def isPrime(n):
if n==2 or n==3:
return True
if n<=1 or n%2==0 or n%3==0:
return False
if n%6!=1 and n%6!=5: # Prime numbers > 3 are in form of 6k +/- 1.
return False
sqr = int(n**0.5 + 0.5)
for i in range(5, sqr+1, 6):
if n%i==... | Python | zaydzuhri_stack_edu_python |
function selector self
begin
return get pulumi self string selector
end function | def selector(self) -> Optional[str]:
return pulumi.get(self, "selector") | Python | nomic_cornstack_python_v1 |
function test_nmos_registration_callback_add_ipv6_on_ipv6_system self
begin
call assert_registered_callback_correctly_handles_data_from_mdns string nmos-registration string add name string bbc1:bbc2::bbc4 prefer_ipv6=true
end function | def test_nmos_registration_callback_add_ipv6_on_ipv6_system(self):
self.assert_registered_callback_correctly_handles_data_from_mdns('nmos-registration', "add", mock.sentinel.name, "bbc1:bbc2::bbc4", prefer_ipv6=True) | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
set cap = call VideoCapture 1
comment definir kernels
comment kernel 1
set Hx = array list list - 1 0 1 list - 1 0 1 list - 1 0 1
set Hy = array list list - 1 - 1 - 1 list 0 0 0 list 1 1 1
while true
begin
set tuple ret frame = read cap
comment convertir a gris
set gris = call cvtColor fra... | import numpy as np
import cv2
cap=cv2.VideoCapture(1)
#definir kernels
#kernel 1
Hx=np.array([[-1,0,1],
[-1,0,1],
[-1,0,1]])
Hy=np.array([[-1,-1,-1],
[0,0,0],
[1,1,1]])
while True:
ret,frame=cap.read()
#convertir a gris
gris=cv2.cvtColor(fram... | Python | zaydzuhri_stack_edu_python |
function get_taxes cls
begin
return list all
end function | def get_taxes(cls):
return list(cls.objects.all()) | Python | nomic_cornstack_python_v1 |
comment here's some new strange stuff, remember type it exactly
set days = string Mon Tue Wed thu Fri Sat Sun
set months = string Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
print string Here are the days: days
print string Here are the months: months
print string months %s % months
print string There's something g... | #here's some new strange stuff, remember type it exactly
days = "Mon Tue Wed thu Fri Sat Sun"
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print("Here are the days:", days)
print("Here are the months:", months)
print("months %s" % months)
print( """
There's something going on here.
With th... | Python | zaydzuhri_stack_edu_python |
comment plain_LZ77Decompress.py
comment Decompresses a compressed file written with the LZ77 algorithm, with 3-byte (length, character, distance) triples written in sequence
import heapq as hq
import sys
import huff_functions as huff
set search_capacity = 255
set distance_bits = 8
set search_size = 0
if length argv == ... | # plain_LZ77Decompress.py
# Decompresses a compressed file written with the LZ77 algorithm, with 3-byte (length, character, distance) triples written in sequence
import heapq as hq
import sys
import huff_functions as huff
search_capacity = 255
distance_bits = 8
search_size = 0
if len(sys.argv) == 3:
inputname = ... | Python | zaydzuhri_stack_edu_python |
function test_graph_nesting3_topology_copy_one_module_default_outputs self
begin
set dl = call RealFunctionDataLayer n=10 batch_size=1 name=string tgn3_dl
comment Create the "inner graph".
with call NeuralGraph operation_mode=training name=string tgn3_g1 as g1
begin
set tuple xg1 tg1 = call dl
end
comment Create the "o... | def test_graph_nesting3_topology_copy_one_module_default_outputs(self):
dl = RealFunctionDataLayer(n=10, batch_size=1, name="tgn3_dl")
# Create the "inner graph".
with NeuralGraph(operation_mode=OperationMode.training, name="tgn3_g1") as g1:
xg1, tg1 = dl()
# Create the "ou... | Python | nomic_cornstack_python_v1 |
function set_remote_exception self remote_exc_info
begin
string Raises an exception as a :exc:`RemoteException`.
set tuple exc_type exc_str filename lineno = remote_exc_info at slice : 4 :
set exc_type = call compose exc_type
set exc = call exc_type exc_str filename lineno worker_info
if length remote_exc_info > 4
be... | def set_remote_exception(self, remote_exc_info):
"""Raises an exception as a :exc:`RemoteException`."""
exc_type, exc_str, filename, lineno = remote_exc_info[:4]
exc_type = RemoteException.compose(exc_type)
exc = exc_type(exc_str, filename, lineno, self.worker_info)
if len(remote... | Python | jtatman_500k |
function generate_eig_plots_QoI cost_matrices param_names folder sampling enz_ratio_name niters threshold save=true
begin
for func_name in QOI_NAMES
begin
set tuple eigs eigvals = call eigh cost_matrices at func_name
set eigs = call flip eigs
set eigsvals = call flip eigvals axis=1
call eig_plots eigs eigvals param_nam... | def generate_eig_plots_QoI(cost_matrices,param_names,folder,sampling,
enz_ratio_name,niters,threshold, save=True):
for func_name in QOI_NAMES:
eigs, eigvals = np.linalg.eigh(cost_matrices[func_name])
eigs = np.flip(eigs)
eigsvals = np.flip(eigvals, axis=1)
eig_... | Python | nomic_cornstack_python_v1 |
function create_frc_flux filename eta_rho=10 xi_rho=10 ntimes=1 cycle=none reftime=default_epoch clobber=false cdl=none title=string My Flux
begin
comment Generate the Structure
set tuple dims vars attr = call cdl_parser if expression cdl is none then _cdl_dir + string frc_fluxclm.cdl else cdl
comment Fill in the appro... | def create_frc_flux(filename, eta_rho=10, xi_rho=10, ntimes=1,
cycle=None, reftime=default_epoch, clobber=False,
cdl=None, title="My Flux"):
# Generate the Structure
dims, vars, attr = cdl_parser(
_cdl_dir + "frc_fluxclm.cdl" if cdl is None else cdl)
# Fill i... | Python | nomic_cornstack_python_v1 |
function get_images_and_labels_nc
begin
set refs = call get_ref_df
set images = dict
for tuple _ data in call iterrows
begin
if data at string ProbeFileName in images
begin
continue
end
set im = data at string ProbeFileName
set images at im = if expression data at string IsTarget == string Y then 1 else 0
end
return i... | def get_images_and_labels_nc():
refs = get_ref_df()
images = {}
for _, data in refs.iterrows():
if data['ProbeFileName'] in images:
continue
im = data['ProbeFileName']
images[im] = 1 if data['IsTarget'] == 'Y' else 0
return images | Python | nomic_cornstack_python_v1 |
function test_signed_changes self
begin
set dbsg = call Debsign changes_path passphrase=string password keyid=keyid gnupghome=gnupghome
call initialize
call copyfile string %s.signed % changes_path changes_path
call copyfile string %s.signed % dsc_path dsc_path
assert true call debsign_process changes_path passphrase=s... | def test_signed_changes(self):
dbsg = debsign.Debsign(self.changes_path,
passphrase='password',
keyid=self.keyid,
gnupghome=self.gnupghome)
dbsg.initialize()
shutil.copyfile('%s.signed' % self.changes_pa... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[16]:
import sys
print version
call system string {sys.executable} -m pip install --upgrade pip
call system string {sys.executable} -m pip install iexfinance
call system string {sys.executable} -m pip install --no-deps empyrical
call system string {sys.execut... | #!/usr/bin/env python
# coding: utf-8
# In[16]:
import sys
print(sys.version)
get_ipython().system('{sys.executable} -m pip install --upgrade pip')
get_ipython().system('{sys.executable} -m pip install iexfinance')
get_ipython().system('{sys.executable} -m pip install --no-deps empyrical')
get_ipython().system('{sys... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: cp936 -*-
comment while ѭ
set name = string
while not strip name
begin
set name = call raw_input string please enter your name:
end | # -*- coding: cp936 -*-
#while ѭ
name=''
while not name.strip():
name = raw_input('please enter your name:') | Python | zaydzuhri_stack_edu_python |
function dump self with_organization=false
begin
set user = dict string id string id ; string email email ; string name name ; string role role ; string registered_on call isoformat
if with_organization
begin
if organization
begin
set user at string organization = dump with_users=false
end
else
begin
set user at string... | def dump(self, with_organization: bool = False):
user = {
'id': str(self.id),
'email': self.email,
'name': self.name,
'role': self.role,
'registered_on': self.registered_on.isoformat(),
}
if with_organization:
if self.organ... | Python | nomic_cornstack_python_v1 |
function _update_progress self progress_text progress_value
begin
if not is instance progress_value int or progress_value < 0
begin
raise call ValueError string Value provided + string progress_value + string . It must be an integer >=0 and <=100.
end
if progress_value > 100
begin
set progress_value = 100
end
call upda... | def _update_progress(
self,
progress_text: str,
progress_value: int):
if not isinstance(progress_value, int) \
or progress_value < 0:
raise ValueError('Value provided '
+ str(progress_value)
... | Python | nomic_cornstack_python_v1 |
function search phrase
begin
return dictionary comprehension k : call to_queryset for tuple k s in items call get_search_queries phrase
end function | def search(phrase):
return {k: s.to_queryset() for k, s in get_search_queries(phrase).items()} | Python | nomic_cornstack_python_v1 |
function __iter__ self
begin
return iterate reversed _stack
end function | def __iter__(self):
return iter(reversed(self._stack)) | Python | nomic_cornstack_python_v1 |
function add num1 num2
begin
set sum = num1 + num2
print sum
end function
comment Driver code
set num1 = integer input string Enter num1:
set num2 = integer input string Enter num2:
add num1 num2 | def add(num1, num2):
sum = num1 + num2
print(sum)
# Driver code
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
add(num1, num2) | Python | jtatman_500k |
import pytest
from main import get_github_organization_stats
decorator call parametrize string organization list none string
function test_getting_stats_invalid_inputs organization
begin
with raises Exception as expected_exception
begin
call get_github_organization_stats organization
end
assert string organization is r... | import pytest
from main import get_github_organization_stats
@pytest.mark.parametrize("organization", [None, ''])
def test_getting_stats_invalid_inputs(organization):
with pytest.raises(Exception) as expected_exception:
get_github_organization_stats(organization)
assert "organization is required and ... | Python | zaydzuhri_stack_edu_python |
class Iterator extends Object
begin
function __init__ self containter
begin
call __init__
set _container = containter
end function
function __iter__ self
begin
return self
end function
function next self
begin
pass
end function
set next = call abstractmethod next
end class | class Iterator(Object):
def __init__(self, containter):
super(Object, self).__init__()
self._container = containter
def __iter__(self):
return self
def next(self):
pass
next = abstractmethod(next)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Apr 22 16:14:00 2018 @author: zailchen
import numpy as np
import cv2
from math import sin , cos , radians
function rotate_image img angle
begin
if angle == 0
begin
return img
end
comment print("checked for shape".format(image.shape))
set ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 16:14:00 2018
@author: zailchen
"""
import numpy as np
import cv2
from math import sin, cos, radians
def rotate_image(img, angle):
if angle == 0: return img
# print("checked for shape".format(image.shape))
height, width = img.shape... | Python | zaydzuhri_stack_edu_python |
function environment_id self
begin
return get pulumi self string environment_id
end function | def environment_id(self) -> Optional[str]:
return pulumi.get(self, "environment_id") | Python | nomic_cornstack_python_v1 |
from attr import dataclass
from functions.database import utils
function insert id name fields
begin
if call getMeme name is not none
begin
return string Deze meme staat al in de database.
end
set connection = call connect
set cursor = call cursor
execute cursor string INSERT INTO memes(id, name, fields) VALUES (%s, %s... | from attr import dataclass
from functions.database import utils
def insert(id, name, fields):
if getMeme(name) is not None:
return "Deze meme staat al in de database."
connection = utils.connect()
cursor = connection.cursor()
cursor.execute("INSERT INTO memes(id, name, fields) VALUES (%s, %s... | Python | zaydzuhri_stack_edu_python |
function print_items storyWords
begin
for word in storyWords
begin
print decode word string 'utf-8
end
end function | def print_items(storyWords):
for word in storyWords:
print(word.decode("'utf-8")) | Python | nomic_cornstack_python_v1 |
function request self config query
begin
set url = call build_url config query
set response = get requests url
set normalized_data = call normalize response
return normalized_data
end function | def request(self, config, query):
url = self.build_url(config, query)
response = requests.get(url)
normalized_data = self.normalize(response)
return normalized_data | Python | nomic_cornstack_python_v1 |
function getLibs self
begin
return _libs
end function | def getLibs(self):
return self._libs | Python | nomic_cornstack_python_v1 |
class Solution
begin
function wordBreak self s wordDict
begin
comment String size
set size = length s
comment Dynamic programming array that define if the
comment prefix of s of size i (index of the list) is a word break
set prefix = list false * size + 1
comment Base condition assume true null prefix
set prefix at 0 =... | class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
# String size
size = len(s)
# Dynamic programming array that define if the
# prefix of s of size i (index of the list) is a word break
prefix = [False]*(size+1)
# Base condition assume true nu... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment Copyright (c) 2010-2014 by Cisco Systems, Inc.
comment THIS SAMPLE CODE IS PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY
comment BY CISCO SOLELY FOR THE PURPOSE of PROVIDING PROGRAMMING EXAMPLES.
comment CISCO SHALL NOT BE HELD LIABLE FOR ANY USE OF THE SAMPLE CODE IN AN... | #! /usr/bin/env python
# Copyright (c) 2010-2014 by Cisco Systems, Inc.
#
# THIS SAMPLE CODE IS PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY
# BY CISCO SOLELY FOR THE PURPOSE of PROVIDING PROGRAMMING EXAMPLES.
# CISCO SHALL NOT BE HELD LIABLE FOR ANY USE OF THE SAMPLE CODE IN ANY
# APPLICATION.
#
# Redi... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2019/4/1 17:02
comment @Author : Jamming
comment @Email : gaojiaming24@163.com
comment @File : tensorflow_Machine_Translation_DataProcess.py
comment @Software: PyCharm
import os
import re
import jieba
import numpy as np
import collections
from sklearn.utils import shuffle
f... | # -*- coding: utf-8 -*-
# @Time : 2019/4/1 17:02
# @Author : Jamming
# @Email : gaojiaming24@163.com
# @File : tensorflow_Machine_Translation_DataProcess.py
# @Software: PyCharm
import os
import re
import jieba
import numpy as np
import collections
from sklearn.utils import shuffle
from tensorflow.python.platf... | Python | zaydzuhri_stack_edu_python |
function get_objects_data self
begin
return dictionary items=objects
end function | def get_objects_data(self):
return dict(items=self.objects) | Python | nomic_cornstack_python_v1 |
import socket
set REC_IP = string 192.168.1.245
comment REC_IP = "127.0.0.1"
set REC_PORT = 5005
set SEND_IP = string 127.0.0.1
set SEND_PORT = 5006
comment TCP SEND
set send = call socket AF_INET SOCK_STREAM
call connect tuple SEND_IP SEND_PORT
comment TCP Receive
set receive = call socket AF_INET SOCK_STREAM
call bin... | import socket
REC_IP = "192.168.1.245"
#REC_IP = "127.0.0.1"
REC_PORT = 5005
SEND_IP = "127.0.0.1"
SEND_PORT = 5006
send = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP SEND
send.connect((SEND_IP, SEND_PORT))
receive = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Receive
receive.bind((REC_IP, REC_... | Python | zaydzuhri_stack_edu_python |
function add self next_f
begin
set next_f = reshape _n next_f tuple n 1
add BroydenSolver self next_x - next_f
end function | def add(self, next_f):
next_f = _n.reshape(next_f, (self.n, 1))
BroydenSolver.add(self, self.next_x - next_f) | Python | nomic_cornstack_python_v1 |
function name self
begin
return get pulumi self string name
end function | def name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
function CacheKey self
begin
raise call NotImplementedError
end function | def CacheKey(self):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function get_color_cell cell
begin
global game
set pos = cell at string position
return call get_color call get_grid game pos at 0 pos at 1
end function | def get_color_cell(cell):
global game
pos = cell['position']
return get_color(get_grid(game), pos[0], pos[1]) | Python | nomic_cornstack_python_v1 |
function test_parse_genome_data_3 self
begin
set genome_list = call parse_genome_data engine phage_id_list=list string Trixie phage_query=PHAGE_QUERY gene_query=GENE_QUERY trna_query=TRNA_QUERY tmrna_query=TMRNA_QUERY
with call subTest
begin
assert equal length genome_list 1
end
with call subTest
begin
assert equal id ... | def test_parse_genome_data_3(self):
genome_list = mysqldb.parse_genome_data(
self.engine, phage_id_list=["Trixie"],
phage_query=PHAGE_QUERY, gene_query=GENE_QUERY,
trna_query=TRNA_QUERY, tmrna_query=TMRNA_QUERY)
with self.subTest():... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 使用dict和set
comment dict #################################
comment 1. dict 全称 dictionary,在其他语言中也称为 map, 键-值( key-value)
comment 2. dict 可以用在需要高速查找的很多地方
comment 3. 需要牢记的第一条就是 dict 的 key 必须是不可变对象
comment 在 Python 中,字符串、整数等都是不可变的,因此,可以放心地作为 key。而 list 是可变的... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 使用dict和set
############ dict #################################
# 1. dict 全称 dictionary,在其他语言中也称为 map, 键-值( key-value)
# 2. dict 可以用在需要高速查找的很多地方
# 3. 需要牢记的第一条就是 dict 的 key 必须是不可变对象
# 在 Python 中,字符串、整数等都是不可变的,因此,可以放心地作为 key。而 list 是可变的,就不能作为 key.
dict={'king':9... | Python | zaydzuhri_stack_edu_python |
function _fix_win_executable cls exe
begin
comment Note that this assumes the executable is QtWebEngineProcess.
call _create_qt_conf exe
end function | def _fix_win_executable(cls, exe):
# Note that this assumes the executable is QtWebEngineProcess.
cls._create_qt_conf(exe) | Python | nomic_cornstack_python_v1 |
function cross a b
begin
return list comprehension s + t for s in a for t in b
end function | def cross(a, b):
return [s + t for s in a for t in b] | Python | nomic_cornstack_python_v1 |
function phi_inv_prime self u
begin
return 1 / call phi_prime call phi_inv u
end function | def phi_inv_prime(self, u):
return 1/self.phi_prime(self.phi_inv(u)) | Python | nomic_cornstack_python_v1 |
function is_shared_content_download self
begin
return _tag == string shared_content_download
end function | def is_shared_content_download(self):
return self._tag == 'shared_content_download' | Python | nomic_cornstack_python_v1 |
import random
comment Generates N random numbers
set numbers = list comprehension random integer 0 N for i in range N | import random
# Generates N random numbers
numbers = [random.randint(0, N) for i in range(N)]
| Python | flytech_python_25k |
function __str__ self
begin
set msg = string <<type='%s' timestep='%s' parent='%s' date='%s' + string user='%s'>>
return msg % tuple type self timestep parent date user
end function | def __str__(self):
msg = "<<type='%s' timestep='%s' parent='%s' date='%s'" + \
"user='%s'>>"
return msg % (type(self),
self.timestep,
self.parent,
self.date,
self.user) | Python | nomic_cornstack_python_v1 |
function get self key
begin
set idx = call hash key
set current = head
while current
begin
if value at string key == key
begin
return value at string value
end
set current = next
end
raise call ValueError string No such key exists
end function | def get(self, key):
idx = self.hash(key)
current = self.buckets[idx].head
while current:
if current.value['key'] == key:
return current.value['value']
current = current.next
raise ValueError('No such key exists') | Python | nomic_cornstack_python_v1 |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function generate_amazon_config self role authtype userid password
begin
return dict string endpoint dict string role role ; string authentication dict string authtype authtype ; string userid userid ; string password password
end function | def generate_amazon_config(self, role, authtype, userid, password):
return {'endpoint': {'role': role},
'authentication': {'authtype': authtype, 'userid': userid,
'password': password}} | Python | nomic_cornstack_python_v1 |
function get_by_quote_asset self quote_asset
begin
try
begin
comment Getting symbols in dataframe format
set symbols = call get_symbols dataframe=true
set symbols at string requestDate = call isoformat
set new_df = symbols at symbols at string quoteAsset == quote_asset
return new_df at columns
end
except Exception as e... | def get_by_quote_asset(self, quote_asset):
try:
# Getting symbols in dataframe format
symbols = self.get_symbols.get_symbols(dataframe=True)
symbols["requestDate"] = datetime.now().isoformat()
new_df = symbols[symbols["quoteAsset"] == quote_asset]
r... | Python | nomic_cornstack_python_v1 |
comment to explain yield, lets use our code from our last lesson,
comment we had something that looks similar to this
comment for student in f.readlines():
comment but what does .readlines() do? well lets write our own function that does the same thing
set students = list
comment <- f is the file we pass in just like ... | # to explain yield, lets use our code from our last lesson,
# we had something that looks similar to this
# for student in f.readlines():
# but what does .readlines() do? well lets write our own function that does the same thing
students = []
def read_students(f): # <- f is the file we pass in just like our readl... | Python | zaydzuhri_stack_edu_python |
function getValues self
begin
set dvDict = dict
comment we need to loop over each DVGeo object and get the DVs
for comp in compNames
begin
set dvDictComp = call getValues
comment we need to loop over these DVs
for tuple k v in items dvDictComp
begin
set dvDict at k = v
end
end
return dvDict
end function | def getValues(self):
dvDict = {}
# we need to loop over each DVGeo object and get the DVs
for comp in self.compNames:
dvDictComp = self.comps[comp].DVGeo.getValues()
# we need to loop over these DVs
for k, v in dvDictComp.items():
dvDict[k] = ... | Python | nomic_cornstack_python_v1 |
function print_name
begin
set name = string Robert
print name
end function
call print_name | def print_name():
name = "Robert"
print(name)
print_name() | Python | zaydzuhri_stack_edu_python |
for i in range 0 t
begin
set tuple r string = split call raw_input string
set r = integer r
set out = string
for ch in string
begin
set out = out + ch * r
end
end | for i in range(0, t):
r, string = raw_input().split(' ')
r = int(r)
out=""
for ch in string:
out += ch*r | Python | zaydzuhri_stack_edu_python |
string 790. Domino and Tromino Tiling 多米诺和托米诺平铺 有两种形状的瓷砖:一种是 2x1 的多米诺形,另一种是形如 "L" 的托米诺形。两种形状都可以旋转。 XX <- 多米诺 XX <- "L" 托米诺 X 给定 N 的值,有多少种方法可以平铺 2 x N 的面板?返回值 mod 10^9 + 7。 (平铺指的是每个正方形都必须有瓷砖覆盖。两个平铺不同,当且仅当面板上有四个方向上的相邻单元中的两个,使得恰好有一个平铺有一个瓷砖占据两个正方形。) 示例: 输入: 3 输出: 5 解释: 下面列出了五种不同的方法,不同字母代表不同瓷砖: XYZ XXZ XYY XXY XYY XYZ YYZ X... | """
790. Domino and Tromino Tiling 多米诺和托米诺平铺
有两种形状的瓷砖:一种是 2x1 的多米诺形,另一种是形如 "L" 的托米诺形。两种形状都可以旋转。
XX <- 多米诺
XX <- "L" 托米诺
X
给定 N 的值,有多少种方法可以平铺 2 x N 的面板?返回值 mod 10^9 + 7。
(平铺指的是每个正方形都必须有瓷砖覆盖。两个平铺不同,当且仅当面板上有四个方向上的相邻单元中的两个,使得恰好有一个平铺有一个瓷砖占据两个正方形。)
示例:
输入: 3
输出: 5
解释:
下面列出了五种不同的方法,不同字母代表不同瓷砖:
XYZ XXZ XYY XXY XYY
XYZ Y... | Python | zaydzuhri_stack_edu_python |
function add_element_output_locations self xy epsgIN start end step
begin
set elementIds = call get_element_output_locations xy epsgIN
if elementIds != list
begin
call add_element_output_locations elementIds start end step
end
end function | def add_element_output_locations(self, xy, epsgIN,start,end,step):
elementIds = self.grid.get_element_output_locations(xy,epsgIN)
if(elementIds != []):
self.run_nc.add_element_output_locations(elementIds,start,end,step) | Python | nomic_cornstack_python_v1 |
function _check_loss_value self loss_value
begin
comment test reduction
assert equal 0 ndim
comment Test backward
backward loss_value
end function | def _check_loss_value(self, loss_value: torch.FloatTensor) -> None:
# test reduction
self.assertEqual(0, loss_value.ndim)
# Test backward
loss_value.backward() | Python | nomic_cornstack_python_v1 |
function uri self element expand=true
begin
if is instance element tuple EnumDefinition SubsetDefinition
begin
comment TODO: fix schema view to handle URIs for enums and subsets
return call name element
end
return call get_uri element expand=expand
end function | def uri(self, element: Element, expand=True) -> str:
if isinstance(element, (EnumDefinition, SubsetDefinition)):
# TODO: fix schema view to handle URIs for enums and subsets
return self.name(element)
return self.schemaview.get_uri(element, expand=expand) | Python | nomic_cornstack_python_v1 |
function indirectInitialMatrix self initialState
begin
string Given some initial state, this iteratively determines new states. We repeatedly call the transition function on unvisited states in the frontier set. Each newly visited state is put in a dictionary called 'mapping' and the rates are stored in a dictionary.
s... | def indirectInitialMatrix(self, initialState):
"""
Given some initial state, this iteratively determines new states.
We repeatedly call the transition function on unvisited states in the frontier set.
Each newly visited state is put in a dictionary called 'mapping' and the rates are stor... | Python | jtatman_500k |
class TrieNode extends object
begin
function __init__ self val
begin
set val = val
set children = dictionary
set isEnd = false
end function
end class
class WordDictionary extends object
begin
function __init__ self
begin
string initialize your data structure here.
set root = call TrieNode - 1
end function
function addW... | class TrieNode(object):
def __init__(self, val):
self.val = val
self.children = dict()
self.isEnd = False
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.root = TrieNode(-1)
def addWord(self, word):... | Python | zaydzuhri_stack_edu_python |
from simply import *
if __name__ == string __main__
begin
set s0 = string The deadline is approximately midnight though it could vary.
set s1 = string She is a fascinating lady; she has an astonishing smile, an alluring voice and an entertaining sense of humor.
set s2 = string The topic is appealing nevertheless the sp... | from simply import *
if __name__ == "__main__":
s0 = "The deadline is approximately midnight though it could vary."
s1 = "She is a fascinating lady; she has an astonishing smile, an alluring voice and an entertaining sense of humor."
s2 = "The topic is appealing nevertheless the speaker was too monotonous.... | Python | zaydzuhri_stack_edu_python |
comment Add 1 to value
function inc value
begin
return value + 1
end function
function dec value
begin
return value - 1
end function
function zero
begin
return 0
end function
function one
begin
return 1
end function
function isZero value
begin
return value == 0
end function
function isSame number1 number2
begin
return ... | # Add 1 to value
def inc(value):
return value+1
def dec(value):
return value-1
def zero():
return 0
def one():
return 1
def isZero(value):
return value == 0
def isSame(number1, number2):
return number1 == number2
# i/o is value ==> value
# Only use functions
# Not use +, -, ==, > , < n... | Python | zaydzuhri_stack_edu_python |
comment this program skips the other element in the list
function skip_elements elements
begin
set a = length elements
return elements at slice 0 : a : 2
end function
comment Should be ['a', 'c', 'e', 'g']
print call skip_elements list string a string b string c string d string e string f string g
comment Should be ['O... | #this program skips the other element in the list
def skip_elements(elements):
a = len(elements)
return elements[0:a:2]
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange',... | Python | zaydzuhri_stack_edu_python |
comment The first time the expression was executed without 'print' in front the following appeared in Shell.
comment with no expression
comment ================== RESTART: C:/Users/Demba/Desktop/test1.py ==================
comment >>>
comment The second time with 'print' is was displayed in Shell and I was able to run ... | # The first time the expression was executed without 'print' in front the following appeared in Shell.
# with no expression
# ================== RESTART: C:/Users/Demba/Desktop/test1.py ==================
# >>>
# The second time with 'print' is was displayed in Shell and I was able to run properly.
#>>>
#===========... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function calculate self lst
begin
set c = 0
comment print(lst)
for i in lst
begin
if i == 1
begin
set c = c + 1
end
end
comment print(c)
if c >= 2
begin
return 1
end
else
begin
return 0
end
end function
end class
if __name__ == string __main__
begin
set t = integer input
set obj = call Solution
set... | class Solution():
def calculate(self,lst):
c = 0
#print(lst)
for i in lst:
if i == 1:
c += 1
#print(c)
if c >= 2:
return 1
else:
return 0
if __name__ == "__main__":
t = int(input())
obj = Solu... | Python | zaydzuhri_stack_edu_python |
function _handle_mentions self
begin
comment TODO: only handle a certain number of mentions at a time?
for mention in iterate state at string mention_queue
begin
set prefix = call get_mention_prefix mention
call on_mention mention prefix
remove state at string mention_queue mention
if config at string autofav_mentions
... | def _handle_mentions(self):
# TODO: only handle a certain number of mentions at a time?
for mention in iter(self.state['mention_queue']):
prefix = self.get_mention_prefix(mention)
self.on_mention(mention, prefix)
self.state['mention_queue'].remove(mention)
... | Python | nomic_cornstack_python_v1 |
for z in range t
begin
set tuple n k = map int split input
set s = 0
for i in range 1 n + 1
begin
set s = s + i
end
print string initial sum s
if s >= k
begin
print s - k
continue
end
set initial = s
if s < k
begin
while s < k
begin
set s = s + initial
print string s after add s
if s >= k
begin
print s - k
break
end
el... | for z in range(t):
n,k = map(int,input().split())
s = 0
for i in range(1,n+1):
s+=i
print("initial sum",s)
if(s>=k):
print(s-k)
continue
initial = s
if(s<k):
while(s<k):
s+=initial
print("s after add",s)
... | Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
import pandas as pd
from apyori import apriori
set census2010_file = string census_2010_CLEAN.csv
function openFile filename
begin
comment Creation of pandas dataframe
set myData = read csv filename sep=string , encoding=string latin1
return myData
end function
comment reorganize our dataframe into a list of lists (to ... | import pandas as pd
from apyori import apriori
census2010_file = 'census_2010_CLEAN.csv'
def openFile(filename):
# Creation of pandas dataframe
myData = pd.read_csv(filename, sep=',', encoding='latin1')
return myData
#reorganize our dataframe into a list of lists (to use with apriori algorithm)
def prep... | Python | zaydzuhri_stack_edu_python |
function test_find_nearest_storms self
begin
set this_wind_to_storm_table = call _find_nearest_storms storm_object_table=STORM_OBJECT_TABLE event_table=WIND_TABLE max_time_before_storm_start_sec=MAX_EXTRAPOLATION_TIME_SEC max_time_after_storm_end_sec=MAX_EXTRAPOLATION_TIME_SEC max_link_distance_metres=MAX_LINK_DISTANCE... | def test_find_nearest_storms(self):
this_wind_to_storm_table = linkage._find_nearest_storms(
storm_object_table=STORM_OBJECT_TABLE,
event_table=WIND_TABLE,
max_time_before_storm_start_sec=MAX_EXTRAPOLATION_TIME_SEC,
max_time_after_storm_end_sec=MAX_EXTRAPOLATION_... | Python | nomic_cornstack_python_v1 |
string Engine.py is an search engine that allow different configuration of the search to be created and completed by 'AI'
class SearchEngine
begin
function __init__ self strategy=string random
begin
set strategy = strategy
end function
function set_strategy self strategy
begin
set strategy = strategy
end function
funct... | """
Engine.py is an search engine that allow different configuration of the search to be
created and completed by 'AI'
"""
class SearchEngine:
def __init__(self, strategy='random'):
self.strategy = strategy
def set_strategy(self, strategy):
self.strategy = strategy
def get_strategy(self... | Python | zaydzuhri_stack_edu_python |
import requests
import re
import datetime
import csv
print string connecting...
try
begin
set r = get requests string https://www.premierleague.com/tables?co=1&se=274&ha=-1
set f = open string last string w
set teamlist = find all string <span class="long">(.+)</span> text
set teamlist = teamlist at slice : 20 :
set ... | import requests
import re
import datetime
import csv
print('connecting...')
try:
r=requests.get('https://www.premierleague.com/tables?co=1&se=274&ha=-1')
f=open('last','w')
teamlist = re.findall(r'<span class="long">(.+)</span>',r.text)
teamlist = teamlist[:20]
teampts = re.findall(r'<td class="po... | Python | zaydzuhri_stack_edu_python |
function _populate_data self
begin
string Assing some probe's raw meta data from API response to instance properties
if id is none
begin
set id = get meta_data string id
end
set is_anchor = get meta_data string is_anchor
set country_code = get meta_data string country_code
set description = get meta_data string descrip... | def _populate_data(self):
"""Assing some probe's raw meta data from API response to instance properties"""
if self.id is None:
self.id = self.meta_data.get("id")
self.is_anchor = self.meta_data.get("is_anchor")
self.country_code = self.meta_data.get("country_code")
se... | Python | jtatman_500k |
comment _*_ coding: utf-8 _*_
from random import choice
from random import normalvariate
set nombres = list string Pepe string Diana string Maria string Pablo string Jorge
set apellidos = list string Escobar string Gutierrez string Guzman string Lopez
function persona_fake
begin
set nombre = random choice nombres
set a... | # _*_ coding: utf-8 _*_
from random import choice
from random import normalvariate
nombres = ["Pepe", "Diana", "Maria", "Pablo", "Jorge"]
apellidos = ["Escobar", "Gutierrez", "Guzman", "Lopez"]
def persona_fake():
nombre = choice(nombres)
apellido_paterno = choice(apellidos)
apellido_materno = choice(apellidos)
... | Python | zaydzuhri_stack_edu_python |
function validate self layer
begin
set features = call get_features layer
set errors = call __validate_function features attributes=__attributes allowed_values=__allowed_values islike=__islike
return errors
end function | def validate(self, layer):
features = self.get_features(layer)
errors = self.__validate_function(features,
attributes=self.__attributes,
allowed_values=self.__allowed_values,
i... | Python | nomic_cornstack_python_v1 |
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
import math
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tetris.tetris_advanced import *
comment set up matplotlib
set is_ipython = string... | import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
import math
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tetris.tetris_advanced import *
# set up matplotlib
is_ipython = 'inline' in m... | Python | zaydzuhri_stack_edu_python |
string In this tutorial, we'll be writing a program which, given a source body of text, can perform operations to answer questions such as: What is the least/most frequent word(s)? How many different words are used? What is the average (mean/median/mode) frequency of words in the text?
string A histogram() function whi... | ''' In this tutorial, we'll be writing a program which, given a source body of text, can perform operations to answer questions such as:
What is the least/most frequent word(s)?
How many different words are used?
What is the average (mean/median/mode) frequency of words in the text?'''
''' A histogram() function whi... | Python | zaydzuhri_stack_edu_python |
function mod_pow n k
begin
set ans = 1
while k > 0
begin
set ans = ans * n % mod
set k = k - 1
end
return ans
end function
if n % 2 == 0
begin
sort a
for i in range n // 2
begin
if a at 2 * i != a at 2 * i + 1 or a at 2 * i != 2 * i + 1
begin
print 0
exit
end
end
end
else
begin
sort a
if a at 0 != 0
begin
print 0
exit
... | def mod_pow(n, k):
ans = 1
while k > 0:
ans = ans * n % mod
k -= 1
return ans
if n % 2 == 0:
a.sort()
for i in range(n//2):
if a[2 * i] != a[2 * i + 1] or a[2 * i] != 2 * i + 1:
print(0)
exit()
else:
a.sort()
if a[0] != 0:
print(0)
... | Python | zaydzuhri_stack_edu_python |
function ask self
begin
set keyword = input foretext
set input_asked = true
if keyword in keywords
begin
set retrieved_input = keyword
if keyword in functions
begin
set tuple function args kwargs = functions at keyword
return call function *args keyword kwargs
end
else
begin
return keyword
end
end
else
begin
return cal... | def ask(self):
keyword = input(self.foretext)
self.input_asked = True
if keyword in self.keywords:
self.retrieved_input = keyword
if keyword in self.functions:
function, args, kwargs = self.functions[keyword]
return function(*args, **kwar... | Python | nomic_cornstack_python_v1 |
function _get_speed_ports
begin
set ports = list
set ports_list = list
if string ports in IXNET_CONF
begin
set ports = list comprehension tuple x for x in IXNET_CONF at string ports
end
if string port_list in IXNET_CONF
begin
set ports = list comprehension tuple x at 0 for x in IXNET_CONF at string port_list
set port... | def _get_speed_ports():
ports = []
ports_list = []
if 'ports' in IXNET_CONF:
ports = [tuple(x) for x in IXNET_CONF["ports"]]
if "port_list" in IXNET_CONF:
ports = [tuple(x[0]) for x in IXNET_CONF["port_list"]]
ports_list = [[tuple(x[0]), x[1]] for x in IXNET_CONF["port_list"]]
... | Python | nomic_cornstack_python_v1 |
comment This file extracts features, we give it one folder containing pictures and this code will count features for each picture of that folder.
import pandas as pd
from wndcharm.FeatureSpace import *
from os.path import isdir
from os import system
from sys import argv
set input_dir = string data_reduced
set output = ... | #This file extracts features, we give it one folder containing pictures and this code will count features for each picture of that folder.
import pandas as pd
from wndcharm.FeatureSpace import *
from os.path import isdir
from os import system
from sys import argv
input_dir = 'data_reduced'
output = 'data.csv'
if len(... | Python | zaydzuhri_stack_edu_python |
function get resource_name id opts=none metadata=none project=none
begin
set opts = merge opts call ResourceOptions id=id
set __props__ = call __new__ _ProjectMetadataState
set __dict__ at string metadata = metadata
set __dict__ at string project = project
return call ProjectMetadata resource_name opts=opts __props__=_... | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
metadata: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
project: Optional[pulumi.Input[str]] = None) -> 'ProjectMetadata':
opts = pulumi.ResourceOpt... | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , jsonify , g
from model import DBManager
from utils import str_to_datetime
from flask_cors import CORS
set DATABASE = string worktime.db
set app = call Flask __name__
call CORS app
function get_db
begin
if string db not in g
begin
set db = call DBManager DATABASE
end
return db
end fun... | from flask import Flask, request, jsonify, g
from model import DBManager
from utils import str_to_datetime
from flask_cors import CORS
DATABASE = 'worktime.db'
app = Flask(__name__)
CORS(app)
def get_db():
if 'db' not in g:
g.db = DBManager(DATABASE)
return g.db
def valid_form_params(request):
i... | Python | zaydzuhri_stack_edu_python |
function test_duplicate_users self
begin
set auag = call UsersAndGroups
comment create a duplicate with default flag to raise an error.
call add_user call User name=string user1
with assert raises Exception
begin
call add_user call User name=string user1
end
comment create with overwrite.
call add_user call User name=s... | def test_duplicate_users(self):
auag = UsersAndGroups()
# create a duplicate with default flag to raise an error.
auag.add_user(User(name="user1"))
with self.assertRaises(Exception):
auag.add_user(User(name="user1"))
# create with overwrite.
auag.add_user(
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.