code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function split_at_char token list_char begin set new_str = string for char in token begin set new_str = new_str + char comment return after adding ':' if char in list_char begin return new_str end end return token end function
def split_at_char(token, list_char): new_str = '' for char in token: new_str += char if char in list_char: return new_str # return after adding ':' return token
Python
nomic_cornstack_python_v1
function softplus x begin return call logaddexp x 0 end function
def softplus(x): return T.logaddexp(x, 0)
Python
nomic_cornstack_python_v1
function plot_distances embeddings_matrix begin import matplotlib.pyplot as plt set distances = list for tuple row1 row2 in call combinations embeddings_matrix 2 begin set distance = square root sum call power row1 - row2 2 append distances distance end histogram distances bins=length distances / 50 x label string Dis...
def plot_distances(embeddings_matrix): import matplotlib.pyplot as plt distances = [] for row1, row2 in it.combinations(embeddings_matrix, 2): distance = np.sqrt(np.sum(np.power(row1-row2, 2))) distances.append(distance) plt.hist(distances, bins = len(distances)/50) plt.xlabel("Dist...
Python
nomic_cornstack_python_v1
set c = input string 今天溫度(攝氏): set f = decimal c * 9 / 5 + 32 print string 華氏溫度為: f
c = input('今天溫度(攝氏): ') f = float(c) * (9/5) + 32 print('華氏溫度為: ', f)
Python
zaydzuhri_stack_edu_python
string Lab 8.1 - Tính chiều cao của cây Giới thiệu bài toán Cây được sử dụng để thao tác với dữ liệu phân cấp chẳng hạn như hệ thống phân cấp các danh mục của một nhà bán lẻ hoặc cấu trúc thư mục trên máy tính của bạn. Chúng cũng được sử dụng trong phân tích dữ liệu và học máy cho cả phân cụm thứ bậc và xây dựng các mô...
""" Lab 8.1 - Tính chiều cao của cây Giới thiệu bài toán Cây được sử dụng để thao tác với dữ liệu phân cấp chẳng hạn như hệ thống phân cấp các danh mục của một nhà bán lẻ hoặc cấu trúc thư mục trên máy tính của bạn. Chúng cũng được sử dụng trong phân tích dữ liệu và học máy cho cả phân cụm thứ bậc và xây dựng các mô h...
Python
zaydzuhri_stack_edu_python
function get_interface_for_device self device_id interface_id begin set url = string ipam/instances/%s/interfaces/%s % tuple device_id interface_id set res = loads get self url return res at string interface end function
def get_interface_for_device(self, device_id, interface_id): url = 'ipam/instances/%s/interfaces/%s' % (device_id, interface_id) res = json.loads(self.get(url)) return res['interface']
Python
nomic_cornstack_python_v1
function get_all_tags begin set path = string https://dev.lunchmoney.app/v1/tags set response = get session path return json response end function
def get_all_tags() -> dict: path = 'https://dev.lunchmoney.app/v1/tags' response = session.get(path) return response.json()
Python
nomic_cornstack_python_v1
string Задание # 5 Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа в...
''' Задание # 5 Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вво...
Python
zaydzuhri_stack_edu_python
import time import json comment python3 urllib 和 urllib2 合并为urllib import urllib from urllib import request from conf import settings class ClientHandle extends object begin function __init__ self begin set monitored_services = dict end function function load_latest_config self begin string load the latest monitor con...
import time import json #python3 urllib 和 urllib2 合并为urllib import urllib from urllib import request from conf import settings class ClientHandle(object): def __init__(self): self.monitored_services = {} def load_latest_config(self): ''' load the latest monitor configs from monitor ...
Python
zaydzuhri_stack_edu_python
import unittest from pprint import pprint from auro.c.includes import * class TestIncludes extends TestCase begin comment def test_some_stuff(self): comment include = Include(); comment include.name = 'bla' comment print("█ include:") function test_find_includes self begin set buff = list string #include <iostream> str...
import unittest from pprint import pprint from auro.c.includes import * class TestIncludes(unittest.TestCase): # def test_some_stuff(self): # include = Include(); # include.name = 'bla' # print("█ include:") def test_find_includes(self): buff = ['#include <iostrea...
Python
zaydzuhri_stack_edu_python
set nums = list 1 2 3 4 5 set even_nums = filter lambda e -> e % 2 == 0 nums print *even_nums set even_nums = list filter lambda e -> e % 2 == 0 nums print even_nums
nums = [1, 2, 3, 4, 5] even_nums = filter(lambda e: e % 2 ==0, nums ) print(*even_nums) even_nums = list(filter(lambda e: e % 2 ==0, nums )) print(even_nums)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Oct 19 20:47:05 2016 @author: ZJun import pandas as pd import numpy as np from datetime import datetime from datetime import timedelta import matplotlib.pyplot as plt from sklearn.decomposition import PCA set path1 = string ./Data/WIFITAPTag_Mean_All.csv set path2 = s...
# -*- coding: utf-8 -*- """ Created on Wed Oct 19 20:47:05 2016 @author: ZJun """ import pandas as pd import numpy as np from datetime import datetime from datetime import timedelta import matplotlib.pyplot as plt from sklearn.decomposition import PCA path1 = './Data/WIFITAPTag_Mean_All.csv' path2 = './Data/sch...
Python
zaydzuhri_stack_edu_python
for i in range 1 N + 1 begin set n = n * i set n = n % 10 ^ 9 + 7 end print n
for i in range(1, N + 1): n *= i n %= (10**9 + 7) print(n)
Python
zaydzuhri_stack_edu_python
function create_dataset begin import random set r = 50 set f = open string venky.txt string w for _ in range r begin set current = random choice a write f current + string end close f end function call create_dataset
def create_dataset(): import random r=50 f=open("venky.txt","w") for _ in range(r): current=random.choice(a) f.write(current+"\n") f.close() create_dataset()
Python
zaydzuhri_stack_edu_python
comment To add a new cell, type '# %%' comment To add a new markdown cell, type '# %% [markdown]' comment %% import speech_recognition as sr import pandas as pd import csv from bs4 import BeautifulSoup import urllib.parse import urllib.request import re from gtts import gTTS import vlc import time comment How can Sacha...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import speech_recognition as sr import pandas as pd import csv from bs4 import BeautifulSoup import urllib.parse import urllib.request import re from gtts import gTTS import vlc import time def recognize_system(audio_stt): ...
Python
zaydzuhri_stack_edu_python
function toDict datastorage_obj recursive=true begin string convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too comment if not a DataStorage, convert to it first if string items not in directory datastorage_obj begin set datastorage_obj = call DataStorage datastorage_o...
def toDict(datastorage_obj, recursive=True): """ convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too """ # if not a DataStorage, convert to it first if "items" not in dir(datastorage_obj): datastorage_obj = DataStorage(datastorage_obj) return _toDi...
Python
jtatman_500k
string Program: lottery.py Anthor: Li Chan Project: Lottery Quick Pick This program generates 5 random numbers between 1 and 50. By clicking the Quick Pick button,the computer randomly selects the numbers for you. from tkinter import * import random comment This function generates 5 random numbers between 1 and 50. fun...
""" Program: lottery.py Anthor: Li Chan Project: Lottery Quick Pick This program generates 5 random numbers between 1 and 50. By clicking the Quick Pick button,the computer randomly selects the numbers for you. """ from tkinter import * import random # This function generates 5 random numbers between 1 an...
Python
zaydzuhri_stack_edu_python
function ques_to_bboxes_per_image self obj_color_keywords_to_bboxes begin set all_ques_to_bboxes_per_image = dictionary for tuple keywords bboxes in items obj_color_keywords_to_bboxes begin comment split the objects name and color name set tuple obj_name color_name = call rsplit string 1 set prefix = random choice pre...
def ques_to_bboxes_per_image(self, obj_color_keywords_to_bboxes): all_ques_to_bboxes_per_image = dict() for keywords, bboxes in obj_color_keywords_to_bboxes.items(): # split the objects name and color name obj_name, color_name = keywords.rsplit(" ", 1) prefix = random...
Python
nomic_cornstack_python_v1
function _plot_stand_ser_corr_coff self ax begin comment get the raw residuals set res = fit _model set resid = array resid set resid = call expand_dims resid axis=0 comment expand the residuals and time values into matrices set resid_matrix = call tile resid tuple integer nobs 1 set time_matrix = call tile index tuple...
def _plot_stand_ser_corr_coff(self, ax): # get the raw residuals res = self._model.fit() resid = np.array(res.resid) resid = np.expand_dims(resid, axis=0) # expand the residuals and time values into matrices resid_matrix = np.tile(res.resid, (int(res.nobs), 1)) ...
Python
nomic_cornstack_python_v1
function _topk_attention self Q K V clusters counts topk topk_values A_bottomk softmax_temp query_lengths begin comment Extract some indices set tuple N H L E = shape set tuple _ _ S _ = shape set tuple _ _ C k = shape comment We need to pass the output tensor to initialize to 0 set QK = call clustered_sparse_dot_produ...
def _topk_attention(self, Q, K, V, clusters, counts, topk, topk_values, A_bottomk, softmax_temp, query_lengths): # Extract some indices N, H, L, E = Q.shape _, _, S, _ = K.shape _, _, C, k = t...
Python
nomic_cornstack_python_v1
string user_info={'first_name':'','last_name':''} first_name= input('введите имя') user_info['first_name']= first_name last_name= input('введите фамилию') user_info['last_name']= last_name print(user_info) function get_summ one two begin set get_summ1 = upper one + two return get_summ1 end function print call get_summ ...
'''user_info={'first_name':'','last_name':''} first_name= input('введите имя') user_info['first_name']= first_name last_name= input('введите фамилию') user_info['last_name']= last_name print(user_info)''' def get_summ(one, two): get_summ1= (one + two).upper() return get_summ1 print (get_summ('helo', 'world'))
Python
zaydzuhri_stack_edu_python
function to_dict self begin set result = dict for tuple attr _ in call iteritems openapi_types begin set value = get attribute self attr if is instance value list begin set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value end else if has attribute value ...
def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Python
nomic_cornstack_python_v1
function hist_plot self df_group feature plotname=string hist_plot.png bin_count=36 begin comment plot the given data frequency count (i.e. feature column) histogram df_group at feature bins=list range bin_count comment plt.hist(df_group[feature], bins=range(0,150)) comment Add title and axis names title plt string His...
def hist_plot(self, df_group, feature, plotname="hist_plot.png", bin_count=36): ## plot the given data frequency count (i.e. feature column) plt.hist(df_group[feature], bins=list(range(bin_count))) #plt.hist(df_group[feature], bins=range(0,150)) # Add title and axis names ...
Python
nomic_cornstack_python_v1
set a = integer input string enter first number : set b = integer input string enter second number : while b != 0 begin set t = b set b = a % b set a = t end print a
a=int(input("enter first number :")) b=int(input("enter second number :")) while(b!=0): t=b b=a%b a= t print(a)
Python
zaydzuhri_stack_edu_python
class Hangman begin function __init__ self word begin set word = word set attempts = 10 end function function get_attempts self begin return attempts end function function get_word self begin return word end function function encrypt_word self begin set wList = list set eList = list set output = string for letter in...
class Hangman(): def __init__(self, word): self.word = word self.attempts = 10 def get_attempts(self): return self.attempts def get_word(self): return self.word def encrypt_word(self): self.wList = [] self.eList = [] output = "" for letter in self.word: self.wList.append(letter) self.eLis...
Python
zaydzuhri_stack_edu_python
function format_case self range begin if range at 0 == range at 1 begin comment self.formatter.get_unicode_char_name(range[0]) return string range at 0 end else begin return string range at 0 + string to + string range at 1 end end function comment "{minv} To {maxv}".format( comment minv = self.formatter.get_unicode_ch...
def format_case(self, range): if range[0] == range[1]: return str(range[0])#self.formatter.get_unicode_char_name(range[0]) else: return str(range[0]) + " to " + str(range[1]) #"{minv} To {maxv}".format( #minv = self.formatter.get_unicode_char_nam...
Python
nomic_cornstack_python_v1
function TestFlush numbers suits begin if length set suits == 1 begin set highCardsInOrder = list for i in range length numberCards - 1 - 1 - 1 begin if numberCards at i in numbers begin append highCardsInOrder numberCards at i end end return tuple true highCardsInOrder end return tuple false list end function functi...
def TestFlush(numbers,suits): if len(set(suits)) == 1: highCardsInOrder=[] for i in range(len(numberCards)-1,-1,-1): if numberCards[i] in numbers: highCardsInOrder.append(numberCards[i]) return (True,highCardsInOrder) return (False,[]) def TestStraight(numbers...
Python
zaydzuhri_stack_edu_python
string En este script Exploracion realizamos una exploracion basica pero efectiva de los datos que nos permitira tomar decisiones sobre el tratamiento de los mismos para el reto Altamira Stock Prediction del Datathon Cajamar UniversityHack 2021, realizado por sus miembros: Manuel Bueno Gómez, Pablo Santos Ortiz y Jaime...
'''En este script Exploracion realizamos una exploracion basica pero efectiva de los datos que nos permitira tomar decisiones sobre el tratamiento de los mismos para el reto Altamira Stock Prediction del Datathon Cajamar UniversityHack 2021, realizado por sus miembros: Manuel Bueno Gómez, Pablo Santos Ortiz y Jai...
Python
zaydzuhri_stack_edu_python
from datetime import date , time , datetime , timedelta function trabalhando_com_date begin set data_atual = today print string format time data_atual string %d/%m/%Y print string format time data_atual string %A %B %Y end function function trabalhando_com_time begin set horario = time hour=15 minute=18 second=30 set h...
from datetime import date, time, datetime, timedelta def trabalhando_com_date(): data_atual = date.today() print(data_atual.strftime('%d/%m/%Y')) print(data_atual.strftime('%A %B %Y')) def trabalhando_com_time(): horario = time(hour=15,minute=18,second=30) horario_str = horario.strftime('%H:%M:%S'...
Python
zaydzuhri_stack_edu_python
function posterior_distr self y **args begin raise NotImplementedError end function
def posterior_distr(self, y, **args): raise NotImplementedError
Python
nomic_cornstack_python_v1
function eval_model self begin if not modeled begin raise call RuntimeError string Run a regression method first! end comment As inputs are centered, we must add the intercept manually. return X_test - mean np X_train axis=0 @ beta + mean np z_train end function
def eval_model(self): if not self.modeled: raise RuntimeError("Run a regression method first!") # As inputs are centered, we must add the intercept manually. return ((self.X_test - np.mean(self.X_train, axis=0)) @ self.beta) + np.mean( self.z_train )
Python
nomic_cornstack_python_v1
comment Different ways to handle numbers in python comment python always makes input a string set num1 = input string Enter a number: comment need to convert into numbers set num2 = input string Enter another number: comment will print as first and second appended set result = num1 + num2 print result comment python al...
# Different ways to handle numbers in python num1 = input("Enter a number: ") # python always makes input a string num2 = input("Enter another number: ") # need to convert into numbers result = num1 + num2 # will print as first and second appended print(result) num1 = input("Enter a number: ") # python always makes inp...
Python
zaydzuhri_stack_edu_python
comment , date, shares function enter_short self symbol begin set short_open at symbol = true return self end function
def enter_short(self, symbol): #, date, shares self.short_open[symbol] = True return self
Python
nomic_cornstack_python_v1
function state self begin return _state end function
def state(self): return self._state
Python
nomic_cornstack_python_v1
function validate schedule schedule_name value_name begin if schedule is not none begin if not is instance schedule tuple list tuple or length schedule < 2 begin raise call ValueError string Invalid ` { schedule_name } ` ( { schedule } ) specified! Must be a list of at least 2 tuples, each of the form (`timestep`, ` { ...
def validate( schedule: Optional[List[Tuple[int, float]]], schedule_name: str, value_name: str, ) -> None: if schedule is not None: if not isinstance(schedule, (list, tuple)) or (len(schedule) < 2): raise ValueError( f"Invalid `{schedul...
Python
nomic_cornstack_python_v1
function test_page_getattr_should_not_exist test_page begin call navigate with raises AttributeError begin assert call foobar end end function
def test_page_getattr_should_not_exist(test_page): test_page.navigate() with pytest.raises(AttributeError): assert test_page.foobar()
Python
nomic_cornstack_python_v1
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd set currentDirectory = get current directory set days_margin = 18 comment Leemos el archivo csv con los casos set confirmed_df = read csv currentDirectory + string \data_world\time_series_19-covid-Confirmed.csv comment deaths_df = pd.read_...
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd currentDirectory = os.getcwd() days_margin = 18 # Leemos el archivo csv con los casos confirmed_df = pd.read_csv(currentDirectory + "\\data_world\\time_series_19-covid-Confirmed.csv") # deaths_df = pd.read_csv(currentDirectory + "\\da...
Python
zaydzuhri_stack_edu_python
from import db from datetime import datetime from werkzeug.security import check_password_hash , generate_password_hash from flask_login import UserMixin class User extends UserMixin Model begin set id = call Column Integer primary_key=true set name = call Column call String 80 unique=true nullable=false set password ...
from . import db from datetime import datetime from werkzeug.security import check_password_hash, generate_password_hash from flask_login import UserMixin class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True, nullable=False) password = d...
Python
zaydzuhri_stack_edu_python
import sys , json set f = open argv at 1 string r set input = load json f for card in range length input begin print string " + input at card at string front + string " + string + string " + input at card at string back + string " end
import sys, json f = open(sys.argv[1],'r') input=json.load(f) for card in range(len(input)): print('"' + input[card]['front'] + '"' +'\t' + '"' + input[card]['back'] + '"')
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string @Time : 2019/3/13 22:50 @File : 5-longestPalindrome.py @Author : ZZShi @Difficulty :middle @Question : 最长回文子串 @Describe : 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 import doctest class Solution begin function longestPalindrome self s begin string :type s: str :rtype: str >>> Solu...
# -*- coding: utf-8 -*- """ @Time : 2019/3/13 22:50 @File : 5-longestPalindrome.py @Author : ZZShi @Difficulty :middle @Question : 最长回文子串 @Describe : 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 """ import doctest class Solution: def longestPalindrome(self, s): """ :type s: str...
Python
zaydzuhri_stack_edu_python
for tuple i j in enumerate array begin if i < m begin append newArr j end end for i in reversed newArr begin print i end=string end
for i, j in enumerate(array): if(i < m): newArr.append(j) for i in reversed(newArr): print(i, end = " ")
Python
zaydzuhri_stack_edu_python
import numpy as np set theta = call matrix string 0.9 0.2; 0.1 0.8 set phi = call matrix string 0.1 0.3; 0.2 0.0; 0.4 0.3; 0.0 0.3; 0.3 0.1 set x_0 = call matrix string 0.6 0.4 set T = 5 set y = list 3 3 0 4 2 comment y = [0, 0, 0, 0, 0] comment y = [4] function hmm theta phi x_0 y T begin comment Hidden Markov Model f...
import numpy as np theta = np.matrix("0.9 0.2; 0.1 0.8") phi = np.matrix("0.1 0.3; 0.2 0.0; 0.4 0.3; 0.0 0.3; 0.3 0.1") x_0 = np.matrix("0.6 0.4") T = 5 y = [3, 3, 0, 4, 2] #y = [0, 0, 0, 0, 0] #y = [4] def hmm(theta, phi, x_0, y, T): # Hidden Markov Model function # Theta is the transition probability table...
Python
zaydzuhri_stack_edu_python
function GetLineAtIndex self Index=defaultNamedNotOptArg begin return call _ApplyTypes_ 12 1 tuple 12 0 tuple tuple 3 1 string GetLineAtIndex none Index end function
def GetLineAtIndex(self, Index=defaultNamedNotOptArg): return self._ApplyTypes_(12, 1, (12, 0), ((3, 1),), u'GetLineAtIndex', None,Index )
Python
nomic_cornstack_python_v1
class A begin function fun1 self begin print string Hello end function function fun2 self begin print string Welcome end function end class comment Single level Inheritance class B extends A begin function fun3 self begin print string Function 3 is working end function function fun4 self begin print string Function 4 i...
class A: def fun1(self): print("Hello") def fun2(self): print("Welcome") class B(A):#Single level Inheritance def fun3(self): print("Function 3 is working") def fun4(self): print("Function 4 is working") class C: def fun5(self): print("Thankyou") class D(B,C):#Multiple Inheritance def fun...
Python
zaydzuhri_stack_edu_python
comment Ross van der Heyde VHYROS001 comment Assignment 3 question 4 comment Finds palidromic primes between 2 entered integers comment Determines if a number is a prime or not function isPrime x begin set prime = true for i in range 2 x begin if x % i == 0 begin set prime = false break end end return prime end functio...
#Ross van der Heyde VHYROS001 #Assignment 3 question 4 # Finds palidromic primes between 2 entered integers def isPrime(x): # Determines if a number is a prime or not prime = True for i in range(2,x): if x % i==0: prime= False break return prime def isPalin(...
Python
zaydzuhri_stack_edu_python
function invitation_code self begin return get pulumi self string invitation_code end function
def invitation_code(self) -> str: return pulumi.get(self, "invitation_code")
Python
nomic_cornstack_python_v1
function test_install_status_release_serialization self begin comment Construct a json representation of a InstallStatusRelease model set install_status_release_model_json = dict set install_status_release_model_json at string deployments = list dict set install_status_release_model_json at string replicasets = list ...
def test_install_status_release_serialization(self): # Construct a json representation of a InstallStatusRelease model install_status_release_model_json = {} install_status_release_model_json['deployments'] = [{}] install_status_release_model_json['replicasets'] = [{}] install_s...
Python
nomic_cornstack_python_v1
import sys from collections import defaultdict , Counter import sys import os from io import BytesIO , IOBase comment Fast IO Region set BUFSIZE = 8192 class FastIO extends IOBase begin set newlines = 0 function __init__ self file begin set _fd = call fileno set buffer = call BytesIO set writable = string x in mode or ...
import sys from collections import defaultdict, Counter import sys import os from io import BytesIO, IOBase #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r...
Python
jtatman_500k
function add_attempts self attempts begin string stub if attempts is none begin raise call NullArgument string attempts cannot be None end if not call _is_valid_integer attempts call get_attempts_metadata begin raise call InvalidArgument string attempts end set _my_map at string attempts = attempts end function
def add_attempts(self, attempts): """stub""" if attempts is None: raise NullArgument('attempts cannot be None') if not self.my_osid_object_form._is_valid_integer( attempts, self.get_attempts_metadata()): raise InvalidArgument('attempts') self.my_os...
Python
jtatman_500k
import json import requests class User begin function __init__ self access_token begin set access_token = access_token set headers_auth = dict string Content-Type string application/json ; string Authorization access_token end function function get_access_token self username password begin set headers = dict string Con...
import json import requests class User: def __init__(self, access_token): self.access_token = access_token self.headers_auth = { "Content-Type": "application/json", "Authorization": access_token } def get_access_token(self, username, password): hea...
Python
zaydzuhri_stack_edu_python
function test_find_best_model self begin set parameters = dictionary model=tuple string spherical string gaussian string exponential string matern set gs = grid search cv call VariogramEstimator n_lags=15 normalize=false parameters cv=3 set gs = fit gs c v comment Python 3.6 yields 'exponential', comment while 3.7, 3.8...
def test_find_best_model(self): parameters = dict( model=('spherical', 'gaussian', 'exponential', 'matern') ) gs = GridSearchCV( VariogramEstimator(n_lags=15, normalize=False), parameters, cv=3 ) gs = gs.fit(self.c, self.v) ...
Python
nomic_cornstack_python_v1
function memo_generator entry output_path begin try begin with open output_path string a+ encoding=string utf-8 as fp begin write fp entry close fp end end except Exception as e begin error format string Invalid output path. Error: {} e end end function
def memo_generator(entry, output_path): try: with open(output_path, 'a+', encoding='utf-8') as fp: fp.write(entry) fp.close() except Exception as e: logger.error("Invalid output path. Error: {}".format(e))
Python
nomic_cornstack_python_v1
function running name restart=false remote_addr=none cert=none key=none verify_cert=true begin set ret = dict string name name ; string restart restart ; string remote_addr remote_addr ; string cert cert ; string key key ; string verify_cert verify_cert ; string changes dict try begin set container = call name remote_...
def running( name, restart=False, remote_addr=None, cert=None, key=None, verify_cert=True ): ret = { "name": name, "restart": restart, "remote_addr": remote_addr, "cert": cert, "key": key, "verify_cert": verify_cert, "changes": {}, } try: ...
Python
nomic_cornstack_python_v1
function test_cds_invalid_coordinates self begin for i in tuple - 10 - 1 6 100 begin assert is none call cds_coordinate_to_chromosome i assert is none call cds_coordinate_to_transcript i end end function
def test_cds_invalid_coordinates(self): for i in (-10, -1, 6, 100): self.assertIsNone(self.t.cds_coordinate_to_chromosome(i)) self.assertIsNone(self.t.cds_coordinate_to_transcript(i))
Python
nomic_cornstack_python_v1
function coordinates self begin return _coordinates end function
def coordinates(self): return self._coordinates
Python
nomic_cornstack_python_v1
from math import floor function tax income begin if income < 10000.0 begin return 0 end else if income < 30000.0 begin return integer income - 10000.0 * 0.1 end else if income < 100000.0 begin return floor 19999 * 0.1 + income - 30000.0 * 0.25 end else begin return floor 19999 * 0.1 + 69999 * 0.25 + income - 100000.0 *...
from math import floor def tax(income): if income < 10e3: return 0 elif income < 30e3: return int((income - 10e3) * 0.1) elif income < 100e3: return floor(19999 * 0.1 + (income - 30e3) * 0.25) else: return floor(19999 * 0.1 + 69999 * 0.25 + (income - 100e3) * 0.4) ...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import linalg as la function omega_axis omega_prev_axis omega_tau time_delta begin set th = 1 / omega_tau set sig = square root 2 * th / 3 return omega_prev_axis - th * omega_prev_axis * time_delta + sig * square root time_delta * call normal end function function omega_new omega_prev omeg...
import numpy as np from numpy import linalg as la def omega_axis(omega_prev_axis, omega_tau, time_delta): th = 1 / omega_tau sig = np.sqrt(2 * th / 3) return omega_prev_axis - th * omega_prev_axis * time_delta + sig * np.sqrt(time_delta) * np.random.normal() def omega_new(omega_prev, omega_tau, time_de...
Python
zaydzuhri_stack_edu_python
import matplotlib import pandas as pd import matplotlib.pyplot as plt comment read the csv set data = string classification_importance.csv comment date reader set dateparse = lambda x -> string parse time x string %Y%m%d comment read data set df = read csv data parse_dates=list string Date date_parser=dateparse set dat...
import matplotlib import pandas as pd import matplotlib.pyplot as plt # read the csv data='classification_importance.csv' dateparse = lambda x: pd.datetime.strptime(x, '%Y%m%d') # date reader df=pd.read_csv(data, parse_dates=['Date'], date_parser=dateparse) # read data date=df['Date'] #openWater=df.iloc[:,1] #veg...
Python
zaydzuhri_stack_edu_python
function _create_optimizer self begin set model_params = parameters model set optimizer_name = get config string optimizer string adam info string optimizer: { optimizer_name } if optimizer_name == string adam begin set kwargs = call filter_dict config list string lr string betas string eps string weight_decay string a...
def _create_optimizer(self) -> optim.Optimizer: model_params = self.model.parameters() optimizer_name = self.config.get("optimizer", "adam") logger.info(f" optimizer: {optimizer_name}") if optimizer_name == "adam": kwargs = utils.filter_dict( self.config, [...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import argparse from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Random import get_random_bytes import binascii import logging import sys string Reverse the order of bits in a word that is bitwidth bits wide function bitflip data_block bitwidth=32 begin if bitwidth == 0...
#!/usr/bin/python3 import argparse from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Random import get_random_bytes import binascii import logging import sys """ Reverse the order of bits in a word that is bitwidth bits wide """ def bitflip(data_block, bitwidth=32): if bitwidth == 0: ...
Python
zaydzuhri_stack_edu_python
function compute_ap recall precision begin comment Append sentinel values to beginning and end set mrec = concatenate tuple list 0.0 recall list min recall at - 1 + 0.001 1.0 set mpre = concatenate tuple list 0.0 precision list 0.0 comment Compute the precision envelope set mpre = call flip accumulate call flip mpre co...
def compute_ap(recall, precision): # Append sentinel values to beginning and end mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)])) mpre = np.concatenate(([0.], precision, [0.])) # Compute the precision envelope mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) # Integrate...
Python
nomic_cornstack_python_v1
comment appending element of two arrays import numpy as np set x = input string enter array elemts of x set y = input string enter array element of y
#appending element of two arrays import numpy as np x=input("enter array elemts of x") y=input("enter array element of y")
Python
zaydzuhri_stack_edu_python
function euclidean_proj_simplex v s=1 begin assert s > 0 msg string Radius s must be strictly positive (%d <= 0) % s comment will raise ValueError if v is not 1-D set tuple n = shape comment check if we are already on the simplex if sum == s and call alltrue v >= 0 begin comment best projection: itself! return v end co...
def euclidean_proj_simplex(v, s=1): assert s > 0, "Radius s must be strictly positive (%d <= 0)" % s n, = v.shape # will raise ValueError if v is not 1-D # check if we are already on the simplex if v.sum() == s and np.alltrue(v >= 0): # best projection: itself! return v # get the ar...
Python
nomic_cornstack_python_v1
function generate_field_spec row begin string Generate a set of metadata for each field/column in the data. This is loosely based on jsontableschema. set names = set set fields = list for cell in row begin set name = call column_alias cell names set field = dict string name name ; string title column ; string type low...
def generate_field_spec(row): """ Generate a set of metadata for each field/column in the data. This is loosely based on jsontableschema. """ names = set() fields = [] for cell in row: name = column_alias(cell, names) field = { 'name': name, 'title': cell.colu...
Python
jtatman_500k
function include_http_headers self begin return get pulumi self string include_http_headers end function
def include_http_headers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: return pulumi.get(self, "include_http_headers")
Python
nomic_cornstack_python_v1
function is_valid_config self config update=true begin set is_valid_sample = true for footprint in footprints begin set is_valid_placement = true for region in regions begin if call can_hold permeability begin continue end comment We place this check second as it is vastly more computational expensive, albeit comment m...
def is_valid_config(self, config, update=True): is_valid_sample = True for footprint in config.footprints: is_valid_placement = True for region in self.regions: if config.robot.can_hold(region.permeability): continue # We place ...
Python
nomic_cornstack_python_v1
from pytube import YouTube import requests from bs4 import BeautifulSoup import time import pickle import os import moviepy.editor as mp class YoutubeDownloader begin function __init__ self begin pass end function function download_youtube self url path begin try begin set yt = call YouTube url set l = length if intege...
from pytube import YouTube import requests from bs4 import BeautifulSoup import time import pickle import os import moviepy.editor as mp class YoutubeDownloader: def __init__(self): pass def download_youtube(self, url, path): try: yt = YouTube(url) l = yt.length ...
Python
zaydzuhri_stack_edu_python
import boto3 import os import json import contextlib from moviepy.editor import * from moviepy import editor from contextlib import closing function writeAudio output_file stream begin set bytes = read stream end function
import boto3 import os import json import contextlib from moviepy.editor import * from moviepy import editor from contextlib import closing def writeAudio( output_file, stream ): bytes = stream.read()
Python
zaydzuhri_stack_edu_python
function edit_file metadata begin pass end function
def edit_file(metadata): pass
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd set credit_card = read csv string https://github.com/sophiarora/CreditCardFraud/raw/tryI/creditcard_viz.csv encoding=string utf-8 from bokeh.io import push_notebook , show , output_notebook from bokeh.layouts import row , widgetbox from bokeh.models import Select , ColumnDataSourc...
import numpy as np import pandas as pd credit_card = pd.read_csv('https://github.com/sophiarora/CreditCardFraud/raw/tryI/creditcard_viz.csv', encoding = 'utf-8') from bokeh.io import push_notebook, show, output_notebook from bokeh.layouts import row, widgetbox from bokeh.models import Select, ColumnDataSource from bo...
Python
zaydzuhri_stack_edu_python
function extract_timeseries input_file output_file begin set logger = call getLogger __name__ info string loading data set df = read csv input_file index_col=0 info format string data frame has {} rows before indexing length df info string indexing data frame... set nsw = df at call new_south_wales_index df info format...
def extract_timeseries(input_file, output_file): logger = logging.getLogger(__name__) logger.info('loading data') df = pd.read_csv(input_file, index_col=0) logger.info('data frame has {} rows before indexing'.format(len(df))) logger.info('indexing data frame...') nsw = df[new_south_wales_index(...
Python
nomic_cornstack_python_v1
function quad self y z=none method=string sptrapz begin return rsphere * dlam * sum call quad_meridional y z method end function
def quad(self, y, z=None, method="sptrapz"): return self.rsphere * self.dlam * np.sum(self.quad_meridional(y, z, method))
Python
nomic_cornstack_python_v1
function add_node_embedding graph embeddings begin for n in call nodes begin set embd = embeddings at nodes at n at string idx assert ndim == 1 msg string Embeddings are expected to be one-dimensional set nodes at n at string embedding = call tolist end return graph end function
def add_node_embedding(graph: nx.Graph, embeddings: Dict[Any, np.array]) -> nx.Graph: for n in graph.nodes(): embd = embeddings[graph.nodes[n]['idx']] assert embd.ndim == 1, "Embeddings are expected to be one-dimensional" graph.nodes[n]['embedding'] = embd.tolist() return graph
Python
nomic_cornstack_python_v1
import os set path = join path string ./inst_golden.txt set arr = list with open path string r as f begin set arr = read lines f end for s in arr begin set h = hexadecimal integer right strip s string 2 print h end
import os path = os.path.join('./inst_golden.txt') arr = [] with open(path, 'r') as f: arr = f.readlines() for s in arr: h = hex(int(s.rstrip('\n'), 2)) print(h)
Python
zaydzuhri_stack_edu_python
import sys with open argv at 1 string r as test_cases begin for test in test_cases begin set string = upper right strip test string set unique = set string set start = 26 set counts = list for value in unique begin if is alpha value == true begin append counts count string value end end set sorted_nums = sorted counts...
import sys with open(sys.argv[1], 'r') as test_cases: for test in test_cases: string = test.rstrip('\n').upper() unique = set(string) start = 26 counts = [] for value in unique: if value.isalpha() == True: counts.append(string.count(value)) ...
Python
zaydzuhri_stack_edu_python
function _set_state self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=yc_state_openconfig_mpls_static__mpls_lsps_constrained_path_tunnels_tunnel_bandwidth_auto_bandwidth_underflow_state is_container=string container yang_name=string state...
def _set_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=yc_state_openconfig_mpls_static__mpls_lsps_constrained_path_tunnels_tunnel_bandwidth_auto_bandwidth_underflow_state, is_container='container', yang_name="state", parent=self, path_helper=self._...
Python
nomic_cornstack_python_v1
function test_total_weight self begin set varieties = list comprehension call Coconut variety for variety in list string middle eastern string south asian string south asian string american string american string american set inventory = call Inventory for variety in varieties begin call add_coconut variety end assert ...
def test_total_weight(self): varieties = [Coconut(variety) for variety in ['middle eastern', 'south asian', 'south asian', 'american', ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Feb 13 11:54:18 2020 @author: Administrator import cv2 import numpy as np set img = call imread string chess_board.jpg comment 灰度图 set gray = call cvtColor img COLOR_BGR2GRAY set gray = call float32 gray comment 调用cornerHarris函数,最重要的是第三个参数,该参数限定了Sobel算子的中孔。 comment So...
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 11:54:18 2020 @author: Administrator """ import cv2 import numpy as np img = cv2.imread('chess_board.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度图 gray = np.float32(gray) # 调用cornerHarris函数,最重要的是第三个参数,该参数限定了Sobel算子的中孔。 # Sobel算子通过对图像行、列的变化检测来检测边缘,Sobel算子...
Python
zaydzuhri_stack_edu_python
function enrich_textrefs self db begin set tr_list = call select_all TextRef text_ref_id == id source == my_source call is_ none set file_list = call get_csv_as_dict string filelist.csv header=0 set pmcid_mid_dict = dictionary comprehension entry at string PMCID : entry at string MID for entry in file_list set pmid_mid...
def enrich_textrefs(self, db): tr_list = db.select_all(db.TextRef, db.TextContent.text_ref_id == db.TextRef.id, db.TextContent.source == self.my_source, db.TextRef.manuscript_id.is_(None)) file_list = self.ft...
Python
nomic_cornstack_python_v1
comment this is where we implement the state-of-the-art MNIST model that will be under attack import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets , transforms import numpy as np import time class Lenet5 extends Module begin function __init__ se...
# this is where we implement the state-of-the-art MNIST model that will be under attack import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import numpy as np import time class Lenet5(nn.Module): def __init__(self): ...
Python
zaydzuhri_stack_edu_python
from itertools import permutations from itertools import combinations from itertools import combinations_with_replacement set s = string 12edwdqq
from itertools import permutations from itertools import combinations from itertools import combinations_with_replacement s='12edwdqq'
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Attachments backends base classes from abc import abstractmethod class AntivirusBase extends object begin decorator abstractmethod function scan_file self filename begin string Scans file and return result tuple: - scan result: True -- infected, False -- not - antivirus report strin...
# -*- coding: utf-8 -*- """ Attachments backends base classes """ from abc import abstractmethod class AntivirusBase(object): @abstractmethod def scan_file(self, filename): """ Scans file and return result tuple: - scan result: True -- infected, False -- not - antivirus...
Python
zaydzuhri_stack_edu_python
comment 1,编写 储存数据 函数 function getnumber begin set numbers = list set n = input string 请输入要计算的数字: while integer n < 7 begin append numbers integer n set n = input string 请输入要计算的数字: end return numbers end function comment 2,编写 各计算函数 comment 计算平均值 function junzhi numbers begin set s = 0.0 for i in numbers begin set s = s...
#1,编写 储存数据 函数 def getnumber(): numbers=[] n=input("请输入要计算的数字: ") while int(n)<7: numbers.append(int(n)) n=input("请输入要计算的数字: ") return numbers #2,编写 各计算函数 #计算平均值 def junzhi(numbers): s=0.0 for i in numbers: s+=i j=s/len(numbers) return j #计算方差 ...
Python
zaydzuhri_stack_edu_python
comment cada 2m² precisa de 1l pra ser pintado set largura = decimal input string Qual a largura da parede? set altura = decimal input string Qual a altura da parede? set area = largura * altura set soma = area / 2 print string Sua parede tem a dimensão de: { area } m² print string Para pintar essa parede você precisar...
#cada 2m² precisa de 1l pra ser pintado largura = float(input('Qual a largura da parede?')) altura = float(input('Qual a altura da parede?')) area = largura * altura soma = area / 2 print(f'Sua parede tem a dimensão de: {area}m²') print(f'Para pintar essa parede você precisará de: {soma}l')
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import json from scipy.optimize import curve_fit comment Gewichtskraft set F = 0.7474 * 9.81 comment Meter set L = 0.45 comment Meter^4 set I = pi / 4 * 0.005 ^ 4 comment Funktion für Curve Fit: function D_Theorie x E begin return 0.7474 * 9.81 / 2 * E * pi / 4 * 0.005...
import matplotlib.pyplot as plt import numpy as np import json from scipy.optimize import curve_fit F = 0.7474 * 9.81 #Gewichtskraft L = 0.450 #Meter I= (np.pi/4) * 0.005**4 #Meter^4 # Funktion für Curve Fit: def D_Theorie(x,E): return (0.7474 * 9.81)/(2* E * ((np.pi/4) * 0.005**4))* x def D_fit(x...
Python
zaydzuhri_stack_edu_python
comment Hacer un programa en python que me muestre la lista de usuarios que hay en el ordenador comment with open('/etc/passwd','r') as archivo: comment lineas=archivo.readlines() set f = open string /etc/passwd string r set lineas = read lines f set UID = string input string Dime el UID de la cadena. set UIDi = false ...
#Hacer un programa en python que me muestre la lista de usuarios que hay en el ordenador #with open('/etc/passwd','r') as archivo: # lineas=archivo.readlines() f=open('/etc/passwd','r') lineas=f.readlines() UID=str(input("Dime el UID de la cadena. ")) UIDi=False for linea in lineas: datos=linea.split(':') if UID==da...
Python
zaydzuhri_stack_edu_python
import re from typing import Dict set input = open string day7-input.txt string r set rules = split read input string . comment Part 1 ### function count_in_layer rules bags master_list begin set parent_bags = list set cnt = 0 for rule in rules begin set tuple bag_outside inside = split rule string bags contain set ba...
import re from typing import Dict input = open("day7-input.txt", "r") rules = input.read().split(".\n") ### Part 1 ### def count_in_layer(rules: list, bags: set, master_list: set) -> Dict: parent_bags = [] cnt = 0 for rule in rules: bag_outside, inside = rule.split(" bags contain ") bags_i...
Python
zaydzuhri_stack_edu_python
function make_hash self task begin string Create a hash of the task inputs. This uses a serialization library borrowed from ipyparallel. If this fails here, then all ipp calls are also likely to fail due to failure at serialization. Args: - task (dict) : Task dictionary from dfk.tasks Returns: - hash (str) : A unique h...
def make_hash(self, task): """Create a hash of the task inputs. This uses a serialization library borrowed from ipyparallel. If this fails here, then all ipp calls are also likely to fail due to failure at serialization. Args: - task (dict) : Task dictionary from df...
Python
jtatman_500k
function test_combine_graphs_C_CO2 begin for nv in list 0 1 begin set g1 = call create_graph_CO2 num_global_nodes=nv set g2 = call create_graph_C num_global_nodes=nv if nv == 0 begin set global_map_number = list list list list end else if nv == 1 begin set global_map_number = list list 0 list 1 list 2 end else begin...
def test_combine_graphs_C_CO2(): for nv in [0, 1]: g1 = create_graph_CO2(num_global_nodes=nv) g2 = create_graph_C(num_global_nodes=nv) if nv == 0: global_map_number = [[], [], []] elif nv == 1: global_map_number = [[0], [1], [2]] else: ra...
Python
nomic_cornstack_python_v1
function event_m20_11_15040 begin string State 0,2: [Preset] Photoworm_Frog_SubState reacts to enemy and PC approach assert call event_m20_11_x117 z13=5 z14=4220 z15=20114610 z16=211000016 z17=16010 z18=211000081 z19=802 string State 1: Finish call EndMachine end function
def event_m20_11_15040(): """State 0,2: [Preset] Photoworm_Frog_SubState reacts to enemy and PC approach""" assert (event_m20_11_x117(z13=5, z14=4220, z15=20114610, z16=211000016, z17=16010, z18=211000081, z19=802)) """State 1: Finish""" EndMachine()
Python
nomic_cornstack_python_v1
for i in range n begin if i == 0 begin set cache at i at 0 = numList at i set cache at i at 1 = numList at i end else begin set cache at i at 0 = max cache at i - 1 at 1 cache at i - 1 at 0 set cache at i at 1 = max numList at i cache at i - 1 at 1 + numList at i end end print max cache at n - 1
for i in range(n): if i == 0: cache[i][0] = numList[i] cache[i][1] = numList[i] else: cache[i][0] = max(cache[i - 1][1], cache[i - 1][0]) cache[i][1] = max(numList[i], cache[i - 1][1] + numList[i]) print(max(cache[n - 1]))
Python
zaydzuhri_stack_edu_python
function cntPosSS ar begin set pos = 0 set neg = 0 for i in range length ar begin if ar at i < 0 begin set neg = neg + 1 end else if ar at i > 0 begin set pos = pos + 1 end end if neg == 0 begin return 2 ^ pos - 1 % 1000000007 end if pos == 0 begin return 2 ^ neg - 1 - 1 % 1000000007 end else begin set ps = 2 ^ pos - 1...
def cntPosSS(ar): pos = 0 neg = 0 for i in range(len(ar)): if ar[i] < 0: neg += 1 elif ar[i] > 0: pos += 1 if neg == 0: return (2 ** pos - 1) % 1000000007 if pos == 0: return (2 ** (neg - 1) - 1) % 1000000007 else: ps = 2 ** pos...
Python
zaydzuhri_stack_edu_python
function RSI df_ n begin set df = deep copy df_ set df at string delta = df at string adj_close - call shift 1 set df at string gain = where df at string delta >= 0 df at string delta 0 set df at string loss = where df at string delta < 0 absolute df at string delta 0 set avg_gain = list set avg_loss = list set gain ...
def RSI(df_, n): df = copy.deepcopy(df_) df['delta'] = df['adj_close'] - df['adj_close'].shift(1) df['gain'] = np.where(df['delta'] >= 0, df['delta'], 0) df['loss'] = np.where(df['delta'] < 0, abs(df['delta']), 0) avg_gain = [] avg_loss = [] gain = df['gain'].tolist() loss = df['loss']....
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Date : 2017-08-18 21:55:13 comment @Author : Jun Jiang (flametest@gmail.com) comment @Link : http://example.org comment @Version : $Id$ class Solution extends object begin function climbStairs self n begin string :type n: int :rtype: int if n == 0 begi...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-18 21:55:13 # @Author : Jun Jiang (flametest@gmail.com) # @Link : http://example.org # @Version : $Id$ class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 0: ...
Python
zaydzuhri_stack_edu_python
function kb_minus_generation self begin call change_force_size_cb none force_size - 1 end function
def kb_minus_generation(self): self.change_force_size_cb(None, self.force_size - 1)
Python
nomic_cornstack_python_v1
comment Different sorting methods comment 1. Sort a list by first alphabet comment l=['dhaval','mehta','united','FCBarca','spain'] comment s=[] comment count=65 comment while len(s)<len(l): comment for i in range(0,len(l)): comment if ord(l[i][:1])==count: comment s.append(l[i]) comment count+=1 comment count+=1 commen...
# Different sorting methods #1. Sort a list by first alphabet # l=['dhaval','mehta','united','FCBarca','spain'] # s=[] # count=65 # while len(s)<len(l): # for i in range(0,len(l)): # if ord(l[i][:1])==count: # s.append(l[i]) # count+=1 # count+=1 # print(s) # print(sorted(l)) # How to rev...
Python
zaydzuhri_stack_edu_python
function test_timestamp_to_datestring self timestamp with_time expectation begin assert equal call timestamp_to_datestring timestamp with_time expectation end function
def test_timestamp_to_datestring(self, timestamp, with_time, expectation): self.assertEqual( search.timestamp_to_datestring(timestamp, with_time), expectation)
Python
nomic_cornstack_python_v1
function update self ConnectedVia=none KeyType=none MkaLifeTime=none Multiplier=none Name=none RandomizeMemberIdentifier=none StackedLayers=none begin comment type: (List[str], str, int, int, str, bool, List[str]) -> Mka return call _update call _map_locals _SDM_ATT_MAP locals end function
def update(self, ConnectedVia=None, KeyType=None, MkaLifeTime=None, Multiplier=None, Name=None, RandomizeMemberIdentifier=None, StackedLayers=None): # type: (List[str], str, int, int, str, bool, List[str]) -> Mka return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
Python
nomic_cornstack_python_v1
import sqlite3 from datetime import datetime import json , urllib set GEOCODE_BASE_URL = string http://maps.googleapis.com/maps/api/geocode/json function geocode address sensor **geo_args begin update geo_args dict string address address ; string sensor sensor set url = GEOCODE_BASE_URL + string ? + url encode geo_args...
import sqlite3 from datetime import datetime import json, urllib GEOCODE_BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json' def geocode(address,sensor, **geo_args): geo_args.update({ 'address': address, 'sensor': sensor }) url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_a...
Python
zaydzuhri_stack_edu_python
from gbd_artifact_tool import * from gbd_mapping import covariates class BFP_ArtifactTool extends GBD_ArtifactTool begin function __init__ self path begin call __init__ path call _bfp_parse_paths set _country = loc at 0 set _gbd_location_id = integer location_id set covariates = call _bfp_covariates end function functi...
from gbd_artifact_tool import * from gbd_mapping import covariates class BFP_ArtifactTool(GBD_ArtifactTool): def __init__(self, path): super().__init__(path) self._bfp_parse_paths() self._country = self._hdf.get("/dimensions/full_space").location.loc[0] self._gbd_location_id = int(...
Python
zaydzuhri_stack_edu_python