code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function run self
begin
pass
end function | def run(self):
pass | Python | nomic_cornstack_python_v1 |
function _adjust_child_weights self child_results zones
begin
set weighted_hosts = list
for tuple zone_id result in child_results
begin
if not result
begin
continue
end
for zone_rec in zones
begin
if zone_rec at string id != zone_id
begin
continue
end
for item in result
begin
try
begin
set offset = zone_rec at string ... | def _adjust_child_weights(self, child_results, zones):
weighted_hosts = []
for zone_id, result in child_results:
if not result:
continue
for zone_rec in zones:
if zone_rec['id'] != zone_id:
continue
for item in ... | Python | nomic_cornstack_python_v1 |
function author_date self
begin
return run list string log string --pretty=format:%ai string -n string 1
end function | def author_date(self):
return self.run(['log', '--pretty=format:%ai', '-n', '1']) | Python | nomic_cornstack_python_v1 |
function fairness_min U t r
begin
set W = call _pick_window U t r
set A = length W
set sumalloc = sum
if sumalloc == 0
begin
return 0.0
end
return 1.0 * A * min / sumalloc
end function | def fairness_min(U, t, r):
W = _pick_window(U, t, r)
A = len(W)
sumalloc = _allocation_of_window(W).sum()
if sumalloc == 0:
return 0.0
return 1.0*A*_allocation_of_window(W).min()/sumalloc | Python | nomic_cornstack_python_v1 |
string Генератор паролей. Пользователь выбирает 1 из 3 вариантов: 1. Сгенерировать простой пароль (только буквы в нижнем регистре, 8 символов) 2. Сгенерировать средний пароль (любые буквы и цифры, 8 символов) 3. Сгенерировать сложный пароль (минимум 1 большая буква, 1 маленькая, 1 цифра и 1 спец-символ, длина от 8 до 1... | """
Генератор паролей.
Пользователь выбирает 1 из 3 вариантов:
1. Сгенерировать простой пароль (только буквы в нижнем регистре, 8 символов)
2. Сгенерировать средний пароль (любые буквы и цифры, 8 символов)
3. Сгенерировать сложный пароль (минимум 1 большая буква, 1 маленькая, 1 цифра и 1 спец-символ... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import psutil
from util import data_from_pipe , l_split
comment Implementations for Mac OS X system
function physmem
begin
return TOTAL_PHYMEM
end function
function swapinfo
begin
comment Return total and used swap
return tuple call total_virtmem call used_virtmem
end function
function meminfo
begi... | #coding=utf-8
import psutil
from util import data_from_pipe, l_split
# Implementations for Mac OS X system
def physmem():
return psutil.TOTAL_PHYMEM
def swapinfo():
return (psutil.total_virtmem(),psutil.used_virtmem(),) # Return total and used swap
def meminfo():
return (physmem(), psutil.avail_phymem(), psutil.... | Python | zaydzuhri_stack_edu_python |
function md_unsubscribe self _payload
begin
set data = dict string type string unsubscribe ; string payload _payload
call send_msg data
end function | def md_unsubscribe(self, _payload):
data = {'type': 'unsubscribe', 'payload': _payload}
self.send_msg(data) | Python | nomic_cornstack_python_v1 |
function remote_set location repo remote=string origin
begin
call ensure_dir location
with call cd location
begin
if call remote_exists location remote
begin
set cmd = format string /usr/bin/git remote rm {} remote
check call cmd shell=true
end
set cmd = format string /usr/bin/git remote add {} {} remote repo
check cal... | def remote_set(location, repo, remote='origin'):
ensure_dir(location)
with utils.cd(location):
if remote_exists(location, remote):
cmd = '/usr/bin/git remote rm {}'.format(remote)
subprocess.check_call(cmd, shell=True)
cmd = '/usr/bin/git remote add {} {}'.format(remote,... | Python | nomic_cornstack_python_v1 |
function available self
begin
return _available
end function | def available(self):
return self._available | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment RootHash Password Manager
comment Back End Script : Functions
comment Started Date : 2019.11.8
comment Developed By Hirusha Fernando
string This script handles login and password operations in RootHash
comment For Colored Text In Terminal
from colorama import Fore , Style
comment For C... | # !/usr/bin/python3
# RootHash Password Manager
# Back End Script : Functions
# Started Date : 2019.11.8
# Developed By Hirusha Fernando
'''
This script handles login and password operations in RootHash
'''
from colorama import Fore,Style #For Colored Text In Terminal
from colorama import init #For ... | Python | zaydzuhri_stack_edu_python |
function Margin self
begin
set s = margin
assert s in range 1 6 msg string Margin score out of bounds.
if s == 1
begin
return string Poor
end
else
if s == 2
begin
return string Near Poor
end
else
if s == 3
begin
return string Medium
end
else
if s == 4
begin
return string Near Sharp
end
else
if s == 5
begin
return strin... | def Margin(self):
s = self.margin
assert s in range(1,6), "Margin score out of bounds."
if s == 1: return 'Poor'
elif s == 2: return 'Near Poor'
elif s == 3: return 'Medium'
elif s == 4: return 'Near Sharp'
elif s == 5: return 'Sharp' | Python | nomic_cornstack_python_v1 |
string Author: jtokarchuk https://github.com/jtokarchuk/MouseTab/blob/master/mousemacro.py click() -- calls left mouse click hold() -- presses and holds left mouse button release() -- releases left mouse button rightclick() -- calls right mouse click righthold() -- calls right mouse hold rightrelease() -- calls right m... | """
Author: jtokarchuk
https://github.com/jtokarchuk/MouseTab/blob/master/mousemacro.py
click() -- calls left mouse click
hold() -- presses and holds left mouse button
release() -- releases left mouse button
rightclick() -- calls right mouse click
righthold() -- calls right mouse hold
rightrelease() -- calls right mo... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
set s = call Series list 1 2 3 5 7 nan string hello
print s
print shape
print dtype | import pandas as pd
import numpy as np
s=pd.Series([1,2,3,5,7,np.nan,"hello"])
print(s)
print(s.shape)
print(s.dtype)
| Python | zaydzuhri_stack_edu_python |
function test_name item
begin
assert name == string Salmon
end function | def test_name(item):
assert item.name == 'Salmon' | Python | nomic_cornstack_python_v1 |
function eliminate values
begin
set all_data = string 123456789
set eliminate_dict = copy values
for s in values
begin
if values at s == all_data
begin
for p in peers at s
begin
if length values at p == 1
begin
set eliminate_dict at s = replace eliminate_dict at s values at p string
end
end
end
end
return eliminate_dic... | def eliminate(values):
all_data = '123456789'
eliminate_dict = values.copy()
for s in values:
if values[s] == all_data:
for p in ut.peers[s]:
if len(values[p]) == 1:
eliminate_dict[s] = eliminate_dict[s].replace(
values[p], '')... | Python | nomic_cornstack_python_v1 |
function save_new self form commit=true
begin
set save = partial save user=user
return call save_new form commit
end function | def save_new(self, form, commit=True):
form.save = partial(form.save, user=self.user)
return super(MTInlineFormSet, self).save_new(form, commit) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Sep 24 15:27:31 2018 @author: marcos
import silabas as si
import recortar as co
import os , itertools , shutil
import numpy as np
import matplotlib.pyplot as plt
from skimage.filters import threshold_otsu
comment Consigo todos los archivo... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 15:27:31 2018
@author: marcos
"""
import silabas as si
import recortar as co
import os, itertools, shutil
import numpy as np
import matplotlib.pyplot as plt
from skimage.filters import threshold_otsu
#Consigo todos los archivos
home = os.getcwd... | Python | zaydzuhri_stack_edu_python |
from cvxopt.modeling import variable , op
import time
set start = time
set x = call variable 25 string x
set c = list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
set z = c at 0 * x at 0 + c at 1 * x at 1 + c at 2 * x at 2 + c at 3 * x at 3 + c at 4 * x at 4 + c at 5 * x at 5 + c at 6 * x at 6 + c ... | from cvxopt.modeling import variable, op
import time
start = time.time()
x = variable(25, 'x')
c = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
z = ( c[0]* x[0]+ c[1]* x[1]+ c[2]* x[2]+ c[3]* x[3]+ c[4]* x[4]
+ c[5]* x[5]+ c[6]* x[6]+ c[7]* x[7]+ c[8]* x[8]+ c[9]* x[9]... | Python | zaydzuhri_stack_edu_python |
function describe vpc_id=none vpc_name=none region=none key=none keyid=none profile=none
begin
string Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-... | def describe(vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a VPC ID describe its properties.
Returns a dictionary of interesting properties.
.. versionchanged:: 2015.8.0
Added vpc_name argument
CLI Example:
.. code-block:: bash
... | Python | jtatman_500k |
from operator import itemgetter
from itertools import combinations , chain
class Arules
begin
function __init__ self
begin
set frequent_itemsets = list
set num_of_occurrences = dictionary
set num_of_transactions = 0
end function
function get_frequent_item_sets self transactions=none min_support=none
begin
set num_of_tr... | from operator import itemgetter
from itertools import combinations, chain
class Arules:
def __init__(self):
self.frequent_itemsets = list()
self.num_of_occurrences = dict()
self.num_of_transactions = 0
def get_frequent_item_sets(self, transactions=None, min_support=None):
self... | Python | zaydzuhri_stack_edu_python |
function Access_URL url
begin
set r = get requests url
set json = json r
return json
end function | def Access_URL(url):
r = requests.get(url)
json = r.json()
return json | Python | nomic_cornstack_python_v1 |
import math as m
import numpy as np
import matplotlib.pyplot as plt
string constante : m = masse g = 9.81 k = elsticité mu = coéfficient de friction N = normale E_tot = mv^2/2 + mgh + kx^2/2 + Iw^2/2 E_tot(d) = mv^2/2(d) + mgh(d) + kx^2/2 + Iw^2/2(d) - mu*cos(alpha)*mg*d
string Ces 3 valeurs peuvent etre changées au de... | import math as m
import numpy as np
import matplotlib.pyplot as plt
'''constante : m = masse
g = 9.81
k = elsticité
mu = coéfficient de friction
N = normale
E_tot = mv^2/2 + mgh + kx^2/2 + Iw^2/2
E_tot(d) = mv^2/2(d) + mgh(d) + kx^2/2 + Iw^2/2(d) - m... | Python | zaydzuhri_stack_edu_python |
import random
from django.core.management.base import BaseCommand
from django.contrib.admin.utils import flatten
from django_seed import Seed
from lists.models import List
from rooms.models import Room
from users.models import User
class Command extends BaseCommand
begin
set help = string This command creates many list... | import random
from django.core.management.base import BaseCommand
from django.contrib.admin.utils import flatten
from django_seed import Seed
from lists.models import List
from rooms.models import Room
from users.models import User
class Command(BaseCommand):
help = "This command creates many lists"
def add_... | Python | zaydzuhri_stack_edu_python |
function __call__ self input_tensor memory_bank src_pad_mask tgt_pad_mask layer_cache=none step=none future=false with_align=false return_type=none output=none
begin
comment dec_mask = None which is no mask
set dec_mask = none
set input_tensor = call try_convert input_tensor
set memory_bank = call try_convert memory_ba... | def __call__(self,
input_tensor: torch.Tensor,
memory_bank: torch.Tensor,
src_pad_mask: torch.Tensor,
tgt_pad_mask: torch.Tensor,
layer_cache: Optional[dict] = None,
step: Optional[int] = None,
future:... | Python | nomic_cornstack_python_v1 |
function canonical_ctrl_state ctrl_state num_qubits
begin
if not num_qubits
begin
return string
end
if is instance ctrl_state CtrlAll
begin
if ctrl_state == One
begin
return string 1 * num_qubits
end
return string 0 * num_qubits
end
if is instance ctrl_state int
begin
comment If the user inputs an integer, convert it ... | def canonical_ctrl_state(ctrl_state, num_qubits):
if not num_qubits:
return ''
if isinstance(ctrl_state, CtrlAll):
if ctrl_state == CtrlAll.One:
return '1' * num_qubits
return '0' * num_qubits
if isinstance(ctrl_state, int):
# If the user inputs an integer, conv... | Python | nomic_cornstack_python_v1 |
string Implementation of DriveCollection, DrivePriorityElement and DriveElement. A L{SPOSH.DriveCollection} contains several L{SPOSH.DrivePriorityElement}s that contains several L{SPOSH.DriveElement}s. Upon firing a drive collection, either the goal is satisfied, or either of the drive priority elements needs to be fir... | """Implementation of DriveCollection, DrivePriorityElement and DriveElement.
A L{SPOSH.DriveCollection} contains several L{SPOSH.DrivePriorityElement}s
that contains several L{SPOSH.DriveElement}s. Upon firing a drive
collection, either the goal is satisfied, or either of the drive
priority elements needs to be fired ... | Python | zaydzuhri_stack_edu_python |
function resolve_template_string self value scope_vars
begin
set result = string
for tuple literal reference _ _ in parse STRING_FORMATTER value
begin
if reference is not none
begin
set template_value = scope_vars
set template_params = split reference string #
for param in template_params
begin
set template_value = te... | def resolve_template_string(self, value, scope_vars):
result = ""
for literal, reference, _, _ in STRING_FORMATTER.parse(value):
if reference is not None:
template_value = scope_vars
template_params = reference.split("#")
for param in template_... | Python | nomic_cornstack_python_v1 |
function significant_time_frequency series times Tpre Tpost thresh expand=1.0 niter=1000 pval=0.05 method=string wav doplot=true normfun=none diff_fun=F_stat mass_fun=log_F_stat **kwargs
begin
if method == string wav
begin
set callback = continuous_wavelet
end
else
begin
set callback = spectrogram
end
set dT = Tpost - ... | def significant_time_frequency(series, times, Tpre, Tpost, thresh, expand=1.0, niter=1000, pval=0.05, method='wav', doplot=True, normfun=None, diff_fun=F_stat, mass_fun=log_F_stat, **kwargs):
if method == 'wav':
callback = tf.continuous_wavelet
else:
callback = tf.spectrogram
dT = Tpost - T... | Python | nomic_cornstack_python_v1 |
comment Description: The player object
comment Author: Jacob Maughan
comment Lib Imports
import pygame
comment Local Imports
from Enums import Direction
from Enums import PlayerState
from SpriteSheet import SpriteSheet
class Player
begin
function __init__ self playerFile window
begin
comment Init
set window = window
co... | # Description: The player object
# Author: Jacob Maughan
# Lib Imports
import pygame
# Local Imports
from Enums import Direction
from Enums import PlayerState
from SpriteSheet import SpriteSheet
class Player():
def __init__(self, playerFile, window):
# Init
self.window = window
# Persona... | Python | zaydzuhri_stack_edu_python |
function convertCHFToJPY montant reverse
begin
if not reverse
begin
set resultat = montant * 118.1
end
else
begin
set resultat = montant / 118.1
end
return resultat
end function | def convertCHFToJPY(montant, reverse):
if not reverse:
resultat = montant * 118.1
else:
resultat = montant / 118.1
return resultat | Python | nomic_cornstack_python_v1 |
function is_integer num
begin
set num = strip num
if length num == 0
begin
return false
end
if is digit num
begin
return true
end
if num at 0 in tuple string + string -
begin
return is digit num at slice 1 : :
end
return false
end function | def is_integer(num: str) -> bool:
num = num.strip()
if len(num) == 0:
return False
if num.isdigit():
return True
if num[0] in ('+', '-'):
return num[1:].isdigit()
return False | Python | nomic_cornstack_python_v1 |
function _build_fk_batch self model_class object_id_field sync_job_qset
begin
set queries = list
set object_ids = list call values_list string id flat=true
while object_ids
begin
set query = call build_base_query sync_job_qset
call open_bracket string AND
set batch = object_ids at slice : batch_size :
del object_ids... | def _build_fk_batch(
self, model_class, object_id_field, sync_job_qset):
queries = []
object_ids = list(model_class.objects.order_by(self.db_lookup_key)
.values_list('id', flat=True))
while object_ids:
query = self.build_base_query(sync_job_qse... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
set fh = stdin
set count = 0 | #!/usr/bin/env python
import sys
fh = sys.stdin
count = 0 | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from os.path import expanduser , isdir , exists , join , abspath , splitext , basename , dirname
from os import mkdir , makedirs , listdir
from errno import EEXIST
from subprocess import Popen , PIPE , STDOUT
from types import ListType
from shutil import copyfile
from json import dumps , lo... | #!/usr/bin/env python
from os.path import (expanduser, isdir, exists, join, abspath, splitext,
basename, dirname)
from os import mkdir, makedirs, listdir
from errno import EEXIST
from subprocess import Popen, PIPE, STDOUT
from types import ListType
from shutil import copyfile
from json import dumps, loads
def owneriz... | Python | zaydzuhri_stack_edu_python |
from element import Element
from aux_functions import load_json
import random
import math
class ManageElement
begin
function __init__ self
begin
pass
end function
string Finde element by it name param elemant_name : element name to be found param locator : locator return object element
function find_element self eleman... | from element import Element
from aux_functions import load_json
import random
import math
class ManageElement:
def __init__(self):
pass
"""
Finde element by it name
param elemant_name : element name to be found
param locator : locator
return object element
"""
... | Python | zaydzuhri_stack_edu_python |
function sample self batch_size
begin
if length memory < batch_size
begin
return none
end
else
begin
comment return [self.memory[idx] for idx in self.rg.choice(len(self.memory), batch_size)]
set batch = call Transition *zip(*random.sample(self.memory, batch_size))
set state = to call cat tuple tensor list state dtype=f... | def sample(self, batch_size):
if len(self.memory) < batch_size:
return None
else:
# return [self.memory[idx] for idx in self.rg.choice(len(self.memory), batch_size)]
batch = Transition(*zip(*random.sample(self.memory, batch_size)))
state = torch.cat(tuple(... | Python | nomic_cornstack_python_v1 |
function buildPalindrome st
begin
comment input string is a palindrome.
if st == st at slice : : - 1
begin
return st
end
comment Helper variable.
set stop = 0
comment Strings are immutable.
set listSt = list comprehension i for i in st
comment Remove from string until it becomes palindrome, then add removed character... | def buildPalindrome(st):
# input string is a palindrome.
if st == st[::-1]:
return st
# Helper variable.
stop = 0
# Strings are immutable.
listSt = [i for i in st]
# Remove from string until it becomes palindrome, then add removed characters reversed.
for i in range(len(st)):
listSt.rem... | Python | nomic_cornstack_python_v1 |
string 859. Buddy Strings Difficulty: Easy Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. Example 1: Input: A = "ab", B = "ba" Output: true Example 2: Input: A = "ab", B = "ab" Output: false Example 3: Input: A = "aa", B = "aa" Output... | '''
859. Buddy Strings
Difficulty: Easy
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A
so that the result equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
Example 2:
Input: A = "ab", B = "ab"
Output: false
Example 3:
Input: A = "aa", B = "aa"
Outpu... | Python | zaydzuhri_stack_edu_python |
function _handleReverseAction self
begin
comment Flip the flag that indicates that the musical ratios are reversed.
call setReversed not call isReversed
comment Refresh everything.
call refreshTextItems
call prepareGeometryChange
comment Emit that the PriceBarChart has changed so that the
comment dirty flag can be set.... | def _handleReverseAction(self):
# Flip the flag that indicates that the musical ratios are reversed.
self.artifact.setReversed(not self.artifact.isReversed())
# Refresh everything.
self.refreshTextItems()
self.prepareGeometryChange()
... | Python | nomic_cornstack_python_v1 |
function generate_gradient self color_list size=101
begin
string Create a gradient of size colors that passes through the colors give in the list (the resultant list may not be exactly size long). The gradient will be evenly distributed. colors should be in hex format eg '#FF00FF'
set list_length = length color_list
se... | def generate_gradient(self, color_list, size=101):
"""
Create a gradient of size colors that passes through the colors
give in the list (the resultant list may not be exactly size long).
The gradient will be evenly distributed.
colors should be in hex format eg '#FF00FF'
... | Python | jtatman_500k |
function delete self key=none transaction=none batch=none child=false
begin
if key
begin
delete key transaction batch child=child
end
else
begin
delete child=child
end
end function | def delete(self, key=None, transaction=None, batch=None, child=False):
if key:
self.queryset.delete(key, transaction, batch, child=child)
else:
self.queryset.filter(self._parent_key).delete(child=child) | Python | nomic_cornstack_python_v1 |
from os.path import dirname
from xlwt import Worksheet
import xlwt
from common import superuser_login
from urllib.parse import urljoin
import requests
from config import config
function mdms_call_tenant auth_token tenant_id module_name master_details
begin
set url = url join HOST string /egov-mdms-service/v1/_search
se... | from os.path import dirname
from xlwt import Worksheet
import xlwt
from common import superuser_login
from urllib.parse import urljoin
import requests
from config import config
def mdms_call_tenant(auth_token, tenant_id, module_name, master_details):
url = urljoin(config.HOST, '/egov-mdms-service/v1/_search')
... | Python | zaydzuhri_stack_edu_python |
function datagram_received self data addr
begin
call _on_datagram data
end function | def datagram_received(self, data: bytes, addr: Tuple[Any, Any]) -> None:
self._on_datagram(data) | Python | nomic_cornstack_python_v1 |
function slowpath_pps_meteradd datapath=none pps=0
begin
return call OFPMeterMod datapath=datapath command=OFPMC_ADD flags=OFPMF_PKTPS meter_id=OFPM_SLOWPATH bands=list call OFPMeterBandDrop rate=pps
end function | def slowpath_pps_meteradd(datapath=None, pps=0):
return parser.OFPMeterMod(
datapath=datapath,
command=ofp.OFPMC_ADD,
flags=ofp.OFPMF_PKTPS,
meter_id=ofp.OFPM_SLOWPATH,
bands=[parser.OFPMeterBandDrop(rate=pps)],
) | Python | nomic_cornstack_python_v1 |
function combine_sequence_values keylist
begin
from indexclass import Index
set sequence_key_dict = dict
set other_key_set = set
set returnlist = list
function all_numeric l
begin
for x in l
begin
if not call isnumeric
begin
return false
end
end
for else
begin
return true
end
end function
function all_float l
begin
f... | def combine_sequence_values (keylist):
from indexclass import Index
sequence_key_dict = {}
other_key_set = set()
returnlist = []
def all_numeric (l):
for x in l:
if not x.isnumeric():
return False
else:
return True
de... | Python | nomic_cornstack_python_v1 |
function __on_alarm self event_name data kwargs
begin
call run_in __delayed_announcement 40
end function | def __on_alarm(
self, event_name: str, data: dict, kwargs: dict) -> None:
self.run_in(self.__delayed_announcement, 40) | Python | nomic_cornstack_python_v1 |
function get test_url headless tab_concurrency browser_concurrency limit selector source_num geo bin_path chrome_args debug
begin
set chrome_args = split chrome_args string ,
set _args = list
for arg in chrome_args
begin
if length arg > 0
begin
if not starts with arg string --
begin
set arg = format string --{} arg
en... | def get(test_url, headless, tab_concurrency, browser_concurrency, limit, selector, source_num, geo, bin_path, chrome_args, debug):
chrome_args = chrome_args.split(',')
_args = []
for arg in chrome_args:
if len(arg) > 0:
if not arg.startswith('--'):
arg = '--{}'.format(arg... | Python | nomic_cornstack_python_v1 |
string Created on May 20, 2017 @author: zaremba
import unittest
from fuelpump.common.message import *
from fuelpump.common.messages_pb2 import *
import binascii | '''
Created on May 20, 2017
@author: zaremba
'''
import unittest
from fuelpump.common.message import *
from fuelpump.common.messages_pb2 import *
import binascii
| Python | zaydzuhri_stack_edu_python |
function from_magnitude st origin minmag=list - 999.0 3.5 5.5 highpass=list 0.5 0.3 0.1 lowpass=list 25.0 35.0 40.0
begin
set mag = magnitude
set max_idx = max where mag > array minmag at 0
set hp_select = highpass at max_idx
set lp_select = lowpass at max_idx
for tr in st
begin
call setParameter string corner_frequenc... | def from_magnitude(
st,
origin,
minmag=[-999.0, 3.5, 5.5],
highpass=[0.5, 0.3, 0.1],
lowpass=[25.0, 35.0, 40.0],
):
mag = origin.magnitude
max_idx = np.max(np.where(mag > np.array(minmag))[0])
hp_select = highpass[max_idx]
lp_select = lowpass[max_idx]
for tr in st:
tr.set... | Python | nomic_cornstack_python_v1 |
comment 引入函数
import random
comment 随机排序
shuffle random x
print string 随机排序 x
comment 逆向排序
reverse x
print string 逆向排序 x
comment sort 默认是按照大小排序
sort x
print string 正向排序 x
comment 按照字符串排序
sort x key=str
print string str排序 x
comment sort 和reverse是直接对原列表操作,原数据全部丢失
comment 随机排序
shuffle random x
comment sorted不改变原函数
set y = ... | import random#引入函数
random.shuffle(x)#随机排序
print('随机排序',x)
x.reverse()#逆向排序
print('逆向排序',x)
x.sort()#sort 默认是按照大小排序
print('正向排序',x)
x.sort(key=str)#按照字符串排序
print('str排序',x)
#sort 和reverse是直接对原列表操作,原数据全部丢失
random.shuffle(x)#随机排序
y=sorted(x)#sorted不改变原函数
print('新数列默认排序',y)
y=sorted(x,key=str)#字符排序
print('新函数... | Python | zaydzuhri_stack_edu_python |
function lifi_unwrap opts p reflect=false
begin
set IPv4_HDR = string !BBHHHBBH4s4s
set IPv4_HDR_SIZE = 20
try
begin
set packet = base64 decode p validate=true
end
except any
begin
set packet = p
end
if length packet != LIFI_V1_HDR_SIZE + mtu + 4
begin
call debug_print opts string short packet length packet
return none... | def lifi_unwrap(opts, p, reflect=False):
IPv4_HDR = '!BBHHHBBH4s4s'
IPv4_HDR_SIZE = 20
try:
packet = base64.b64decode(p, validate=True)
except:
packet = p
if len(packet) != LIFI_V1_HDR_SIZE + opts.mtu + 4:
debug_print(opts, 'short packet', len(packet))
return None
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Oct 8 14:20:05 2019 @author: Thanga
decorator print_me
function printme
begin
print string I am Printing
end function
set pme = call print_me printme | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 14:20:05 2019
@author: Thanga
"""
@print_me
def printme():
print('I am Printing')
pme = print_me(printme) | Python | zaydzuhri_stack_edu_python |
function rule self resultats attack_type
begin
set target = target_number - Hit_Mod
set rending = copy copy resultats at slice target - 1 : :
set resultats at slice target - 1 : : = 0
set sum_rending = integer sum rending
set temp = copy copy attack_type
set R = sum_rending
set AP = new_AP
return temp
end function | def rule(self, resultats, attack_type):
target = self.target_number - attack_type.Hit_Mod
rending = copy.copy(resultats[(target-1):])
resultats[(target-1):] = 0
sum_rending = int(numpy.sum(rending))
temp = copy.copy(attack_type)
temp.R = sum_rending
temp.AP... | Python | nomic_cornstack_python_v1 |
function write self row=none
begin
write fout format string {} dumps row cls=encoder
end function | def write(self, row: Optional[Any] = None):
self.fout.write('{}\n'.format(json.dumps(row, cls=self.encoder))) | Python | nomic_cornstack_python_v1 |
function finish_var self value ctx
begin
comment some traceback systems allow to skip frames. but allow
comment disabling that via -O to not make things slow
if __debug__
begin
set __traceback_hide__ = true
end
if value is none
begin
return string
end
else
if value is undefined_singleton
begin
return call unicode valu... | def finish_var(self, value, ctx):
# some traceback systems allow to skip frames. but allow
# disabling that via -O to not make things slow
if __debug__:
__traceback_hide__ = True
if value is None:
return u''
elif value is self.undefined_singleton:
... | Python | nomic_cornstack_python_v1 |
string Given an array of numbers, positive integers only, group them in-place into evens and odds Understand that grouping is just a special case of sorting. Aim for o(n) , in-place
function groupNumbers intArr
begin
string odd -odd j
set i = 0
set j = length intArr - 1
while i < j
begin
comment even-odd-for-i
set eoi ... | """
Given an array of numbers, positive integers only, group them in-place into evens and odds
Understand that grouping is just a special case of sorting.
Aim for o(n) , in-place
"""
def groupNumbers(intArr):
"""
odd -odd j
"""
i=0
j = len(intArr)-1
while i < j:
eoi =intArr[i] % 2 # eve... | Python | zaydzuhri_stack_edu_python |
for hour in range awake_time 23 3
begin
print string Час : hour
set calories = integer input string Введите сколько калорий получил Саша:
set total_calories = total_calories + calories
set count = count + 3
set water = water + 1
print string Саша накопил калорий: total_calories
print string Саша выил длитров воды: wate... | for hour in range(awake_time, 23, 3):
print('Час :', hour)
calories = int(input('Введите сколько калорий получил Саша: '))
total_calories += calories
count += 3
water += 1
print(' Саша накопил калорий: ', total_calories)
print('Саша выил длитров воды: ', water)
print()
print(' Саша пошел спа... | Python | zaydzuhri_stack_edu_python |
function __init__ self api database limit=10000
begin
set db = database
set tweet_count = 0
comment 10,000 by default
set TWEET_LIMIT = limit
comment call superclass's init
call __init__ api
end function | def __init__(self, api, database, limit=10000):
self.db = database
self.tweet_count = 0
self.TWEET_LIMIT = limit # 10,000 by default
super().__init__(api) # call superclass's init | Python | nomic_cornstack_python_v1 |
function getTileFromName self imageName nmbr
begin
set grid = call getImageGridByName imageName
if grid is not none
begin
return grid at integer nmbr / length grid at nmbr % length grid
end
else
begin
print string ERROR: Image grid tile not found
return none
end
end function | def getTileFromName(self, imageName, nmbr):
grid = self.getImageGridByName(imageName)
if grid is not None:
return grid[int(nmbr / len(grid))][nmbr % len(grid)]
else:
print("ERROR: Image grid tile not found")
return None | Python | nomic_cornstack_python_v1 |
import requests
import bs4
import time
import os
import json
from lxml import etree
from selenium.webdriver import Chrome , ChromeOptions
set header = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362
function ... | import requests
import bs4
import time
import os
import json
from lxml import etree
from selenium.webdriver import Chrome,ChromeOptions
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362"
}
de... | Python | zaydzuhri_stack_edu_python |
function _determine_namespaces self
begin
string Determine the names of all namespaces of the WBEM server, by communicating with it and enumerating the instances of a number of possible CIM classes that typically represent CIM namespaces. Their class names are defined in the :attr:`NAMESPACE_CLASSNAMES` class variable.... | def _determine_namespaces(self):
"""
Determine the names of all namespaces of the WBEM server, by
communicating with it and enumerating the instances of a number of
possible CIM classes that typically represent CIM namespaces. Their
class names are defined in the :attr:`NAMESPACE... | Python | jtatman_500k |
from mandelbrot_task import mandelbrot , mandelbrot_patch
import matplotlib as mpl
call use string Agg
import matplotlib.pyplot as plt
comment MPI_Init and MPI_Finalize automatically called
from mpi4py import MPI
import numpy as np
import sys
import time
comment some parameters
comment rank of manager
set MANAGER = 0
c... | from mandelbrot_task import mandelbrot, mandelbrot_patch
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from mpi4py import MPI # MPI_Init and MPI_Finalize automatically called
import numpy as np
import sys
import time
# some parameters
MANAGER = 0 # rank of manager
TAG_TASK = 1 # ta... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import jinja2
import os
import MySQLdb
set connection = call connect string localhost string test string password
set cursor = call cursor
comment execute SQL query using execute() method.
execute cursor string SELECT VERSION()
comment Fetch a single row using fetchone() method.
set data = cal... | #!/usr/bin/python3
import jinja2
import os
import MySQLdb
connection = MySQLdb.connect("localhost","test","password")
cursor = connection.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
cursor.close()
connec... | Python | zaydzuhri_stack_edu_python |
function get_side_nav_menu html_soup
begin
comment Container ul with all navigation menus
set menu_div = find html_soup string ul#suckertree1 first=true
comment list of divs containing menu title and link
set menu_items = find menu_div string li
set side_menus = list
for menu in menu_items
begin
set menu_a_tag = find ... | def get_side_nav_menu(html_soup):
# Container ul with all navigation menus
menu_div = html_soup.find("ul#suckertree1", first=True)
# list of divs containing menu title and link
menu_items = menu_div.find("li")
side_menus = []
for menu in menu_items:
menu_a_tag = menu.find("a", first=Tr... | Python | nomic_cornstack_python_v1 |
comment 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
comment 示例 1:
comment 输入:
comment [
comment [ 1, 2, 3 ],
comment [ 4, 5, 6 ],
comment [ 7, 8, 9 ]
comment ]
comment 输出: [1,2,3,6,9,8,7,4,5]
comment 示例 2:
comment 输入:
comment [
comment [1, 2, 3, 4],
comment [5, 6, 7, 8],
comment [9,10,11,12]
comment ]
comment ... | # 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
#
# 示例 1:
#
# 输入:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# 输出: [1,2,3,6,9,8,7,4,5]
#
#
# 示例 2:
#
# 输入:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
#
# Related Topics 数组
# dirs定义4个走向:水平向右、垂直向下、水平向左、垂直向上。... | Python | zaydzuhri_stack_edu_python |
string Contains all general settings for Alien Invasion
class Settings
begin
string Class representing settings for Alien Invasion
function __init__ self
begin
string Initialize's Alien Invasion's settings
comment Screen settings
set screen_width = 1200
set screen_height = 800
set big_color = tuple 240 240 240
comment ... | """Contains all general settings for Alien Invasion"""
class Settings:
"""Class representing settings for Alien Invasion"""
def __init__(self):
"""Initialize's Alien Invasion's settings"""
#Screen settings
self.screen_width = 1200
self.screen_height = 800
self.big_color =... | Python | zaydzuhri_stack_edu_python |
function report_success self out test example got
begin
pass
end function | def report_success(self, out, test, example, got):
pass | Python | nomic_cornstack_python_v1 |
function set_max_age self max_age
begin
if max_age is none
begin
call remove_attribute string Max-Age
end
else
begin
call add_attribute call CookieMaxAgeAttribute max_age
end
end function | def set_max_age(self, max_age):
if max_age is None:
self.remove_attribute("Max-Age")
else:
self.add_attribute(CookieMaxAgeAttribute(max_age)) | Python | nomic_cornstack_python_v1 |
function _fix_path path
begin
comment type: ignore
set path = call Path path
if call is_dir
begin
try
begin
comment type: ignore
set path = next glob path patterns=string @(*.yml|*yaml|!*unified*) flags=EXTGLOB ? NEGATE
end
except StopIteration
begin
raise call ContentInitializeError path path string Can't find yaml or... | def _fix_path(path: Union[Path, str]):
path = Path(path) # type: ignore
if path.is_dir():
try:
path = next(path.glob(patterns=r"@(*.yml|*yaml|!*unified*)", flags=EXTGLOB | NEGATE)) # type: ignore
except StopIteration:
raise exc.ContentInitializeE... | Python | nomic_cornstack_python_v1 |
from lista import *
set __all__ = list string pilha_vazia string pilha_push string pilha_pop
function pilha_vazia
begin
return call lst_vazia
end function
function pilha_push ele
begin
call lst_insFin ele
end function
function pilha_pop
begin
if not call pilha_vazia
begin
return call lst_retFin
end
return none
end func... | from lista import *
__all__ = ['pilha_vazia', 'pilha_push', 'pilha_pop']
def pilha_vazia():
return lst_vazia()
def pilha_push(ele):
lst_insFin(ele)
def pilha_pop():
if(not pilha_vazia()):
return lst_retFin()
return None
| Python | zaydzuhri_stack_edu_python |
from SourceFiles.Commons.WeatherForecastAPIAppCommon import DEBUG_MODE , COUNTRY_CODE_SEARCH_URL
from SourceFiles.Validations.WeatherForecastAPIValidations import is_city , is_country_code , is_city_id , is_lat_lon , is_zip_code
function showMessagesToUser msgsList
begin
string This function displays messages to the us... | from SourceFiles.Commons.WeatherForecastAPIAppCommon import DEBUG_MODE, COUNTRY_CODE_SEARCH_URL
from SourceFiles.Validations.WeatherForecastAPIValidations import is_city, is_country_code, is_city_id, is_lat_lon, is_zip_code
def showMessagesToUser(msgsList):
"""This function displays messages to the user
@:para... | Python | zaydzuhri_stack_edu_python |
import time
import sys
import mdtraj as md
import numpy as np
import math
from pysph.base.utils import get_particle_array
from pysph.base import utils
from pysph.base import nnps
from pyzoltan.core.carray import UIntArray
import argparse
from argparse import RawTextHelpFormatter
comment This is the dictionary of the po... | import time
import sys
import mdtraj as md
import numpy as np
import math
from pysph.base.utils import get_particle_array
from pysph.base import utils
from pysph.base import nnps
from pyzoltan.core.carray import UIntArray
import argparse
from argparse import RawTextHelpFormatter
#This is the dictionary of the potentia... | Python | zaydzuhri_stack_edu_python |
function validNotification cls idNotification
begin
for item in values call readAll
begin
if get item string idNotification == idNotification
begin
return true
end
end
return false
end function | def validNotification(cls, idNotification):
for item in cls.readAll().values():
if item.get('idNotification') == idNotification:
return True
return False | Python | nomic_cornstack_python_v1 |
import re
import numpy
import array
function wordbag SET linenum
begin
set file = open string ../output/training_ + string SET + string _w.txt
comment Read in the file once and build a list of line offsets
set line_offset = list
set offset = 0
for line in file
begin
append line_offset offset
set offset = offset + leng... | import re
import numpy
import array
def wordbag(SET, linenum):
file = open("../output/training_" + str(SET) + "_w.txt")
# Read in the file once and build a list of line offsets
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
file.seek(0)
# Now, to skip to ... | Python | zaydzuhri_stack_edu_python |
function _prim_pop self
begin
if length heap == 0
begin
raise call logoerror string #emptyheap
end
else
begin
if update_values
begin
if length heap == 1
begin
call update_label_value string pop
end
else
begin
call update_label_value string pop heap at - 2
end
end
return pop heap - 1
end
end function | def _prim_pop(self):
if len(self.tw.lc.heap) == 0:
raise logoerror("#emptyheap")
else:
if self.tw.lc.update_values:
if len(self.tw.lc.heap) == 1:
self.tw.lc.update_label_value('pop')
else:
self.tw.lc.update_l... | Python | nomic_cornstack_python_v1 |
function _format_basis basis dim=none
begin
set basis0 = basis
set basis = deep copy basis0
comment Guess dimension
if dim is none
begin
if is instance basis ndarray
begin
set dim = shape at - 1 - 1
end
else
begin
for outer_basis in basis
begin
if is instance outer_basis ndarray
begin
set dim = shape at 0 - 1
break
end... | def _format_basis(basis, dim=None):
basis0 = basis
basis = deepcopy(basis0)
# Guess dimension
if dim is None:
if isinstance(basis, np.ndarray):
dim = basis.shape[-1] - 1
else:
for outer_basis in basis:
if isinstance(outer_basis, np.ndarray):
... | Python | nomic_cornstack_python_v1 |
import matplotlib as mpl
call use string Agg
import matplotlib.pyplot as plt
set rcParams at string lines.linewidth = 4
set rcParams at string lines.markersize = 10
set rcParams at string axes.spines.top = false
set rcParams at string axes.spines.right = false
set rcParams at string axes.grid = true
set rcParams at str... | import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
mpl.rcParams['lines.linewidth'] = 4
mpl.rcParams['lines.markersize'] = 10
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.grid'] = True
mpl.rcParams['grid.alpha'] = 0.8
mpl.rcParams['legend.fra... | Python | zaydzuhri_stack_edu_python |
import ex45
import test_texts
comment print test_texts.central_corridor1
comment text = test_texts.central_corridor2
comment print text
comment lines = ex45.text_border(test_texts.central_corridor1, 40)
comment for line in lines:
comment print line
set output = call TextOutput central_corridor1 30 8 border_char=string ... | import ex45
import test_texts
# print test_texts.central_corridor1
# text = test_texts.central_corridor2
# print text
# lines = ex45.text_border(test_texts.central_corridor1, 40)
# for line in lines:
# print line
output = ex45.TextOutput(test_texts.central_corridor1, 30, 8, border_char='#')
#output.text_format(... | Python | zaydzuhri_stack_edu_python |
function test_permutation self
begin
set rng_R = call random_state_type
set tuple post_r out = call permutation rng_R size=tuple 9 n=6
end function | def test_permutation(self):
rng_R = random_state_type()
post_r, out = permutation(rng_R, size=(9,), n=6) | Python | nomic_cornstack_python_v1 |
function transaction_process self event
begin
set msg = call prepare_message
if msg_content_fmt
begin
set msg_content = body
end
while transaction and credit and msg_processed_cnt + current_batch < msg_total_cnt
begin
if msg_content_fmt
begin
set body = msg_content % msg_processed_cnt + current_batch
end
if duration !=... | def transaction_process(self, event):
msg = self.prepare_message()
if self.msg_content_fmt:
msg_content = msg.body
while event.transaction and self.sender.credit and (
self.msg_processed_cnt + self.current_batch) < self.msg_total_cnt:
if self.msg_content_f... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return string %s in %s % tuple call __repr__ call __repr__
end function | def __repr__(self):
return "%s in %s" % \
(self.lrepr().__repr__(), self.__coordsys.__repr__()) | Python | nomic_cornstack_python_v1 |
import cv2
import matplotlib.pyplot as plt
set img = call imread string image/3.jpg
set img_gray = call cvtColor img COLOR_BGR2GRAY
subplot 1 2 1
image show img cmap=string gray
title plt string Original
call xticks list
call yticks list
subplot 1 2 2
image show img_gray cmap=string gray
title plt string Gray
call xtic... | import cv2
import matplotlib.pyplot as plt
img = cv2.imread('image/3.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.xticks([])
plt.yticks([])
plt.subplot(1, 2, 2)
plt.imshow(img_gray, cmap='gray')
plt.title('Gray')
plt.xticks([])
plt... | Python | zaydzuhri_stack_edu_python |
function create self
begin
string Create an application context on the server
call before_create
call puts call green string Creating app context
set tdir = directory name path __file__
comment Ensure the app context user exists
call user_ensure user home=string /home/ + user
call dir_ensure string /home/%s/.ssh % user... | def create(self):
"""Create an application context on the server"""
self.before_create()
puts(green('Creating app context'))
tdir = os.path.dirname(__file__)
# Ensure the app context user exists
user_ensure(self.user, home='/home/' + self.user)
dir_ensure('/hom... | Python | jtatman_500k |
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
from decimal import *
function plot_eq f_name equation title col_1=string col_2=string flipped=false couple=false num_ticks=5
begin
set temp = call loadtxt f_name skiprows=4 delimiter=string ,
comment print(temp)
comment print(tem... | import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
from decimal import *
def plot_eq(f_name,equation,title,col_1="",col_2="",flipped=False,couple=False,num_ticks=5):
temp = np.loadtxt(f_name,skiprows=4,delimiter=',')
#print(temp)
#print(temp.shape)
in_signal = n... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import urllib.request as req
import urllib.parse as par
function show_me_the_graph df
begin
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
set g = call Graph
call add_edges_from df
set pr = call pagerank g
call _rebuild
set nsi... | from bs4 import BeautifulSoup
import urllib.request as req
import urllib.parse as par
def show_me_the_graph(df):
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
g = nx.Graph()
g.add_edges_from(df)
pr = nx.pagerank(g)
fm._reb... | Python | zaydzuhri_stack_edu_python |
async function async_cloudhook_generate_url hass entry
begin
if CONF_CLOUDHOOK_URL not in data
begin
set webhook_url = await call async_create_cloudhook hass data at CONF_WEBHOOK_ID
set data = dict none data ; CONF_CLOUDHOOK_URL webhook_url
call async_update_entry entry data=data
return webhook_url
end
return string da... | async def async_cloudhook_generate_url(hass: HomeAssistant, entry: ConfigEntry) -> str:
if CONF_CLOUDHOOK_URL not in entry.data:
webhook_url = await cloud.async_create_cloudhook(
hass, entry.data[CONF_WEBHOOK_ID]
)
data = {**entry.data, CONF_CLOUDHOOK_URL: webhook_url}
ha... | Python | nomic_cornstack_python_v1 |
function runLine self line
begin
set GOTO = string jmp
set SPLITTER = string
set VALUE_ADDER = string acc
if split line SPLITTER at 0 == VALUE_ADDER
begin
set val = val + call getInt split line SPLITTER at 1
curLine
return true
end
else
if split line SPLITTER at 0 == GOTO
begin
if starts with split line string at 1 st... | def runLine(self, line):
GOTO = "jmp";
SPLITTER = " ";
VALUE_ADDER = "acc";
if line.split(SPLITTER)[0] == VALUE_ADDER:
self.val += self.getInt(line.split(SPLITTER)[1])
self.curLine;
return True;
elif line.split(SPLITTER)[0] == GOTO:
if line.split(" ")[1].startswith("+"):
self.curLine += int... | Python | nomic_cornstack_python_v1 |
function check_directory directory
begin
set files = list directory directory
for single_file in files
begin
if ends with single_file string .fit or ends with single_file string .f
begin
return true
end
end
return false
end function | def check_directory(directory):
files = os.listdir(directory)
for single_file in files:
if single_file.endswith('.fit') or single_file.endswith('.f'):
return True
return False | Python | nomic_cornstack_python_v1 |
function byte_to_file iterable n fillvalue=none
begin
comment byte_to_file('ABCDEFG', 3, 'x') --> ABC DEF Gxx
set args = list iterate iterable * n
return call zip_longest *args fillvalue=fillvalue
end function | def byte_to_file(iterable, n, fillvalue=None):
# byte_to_file('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args) | Python | nomic_cornstack_python_v1 |
function testUploadFile_emptyRequest self
begin
with call test_client as client
begin
set response = post string /file/test.txt follow_redirects=true content_type=string multipart/form-data
assert equal 400 status_code
end
end function | def testUploadFile_emptyRequest(self):
with self.app.test_client() as client:
response = client.post(
'/file/test.txt',
follow_redirects=True,
content_type='multipart/form-data',
)
self.assertEqual(400, response.status_code) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function isUgly self num
begin
string :type num: int :rtype: bool
if num == 1
begin
return true
end
set j = 0
set ck = 1
while num not in list 2 3 5
begin
for i in list 2 3 5
begin
set k = num % i
if k == 0
begin
set j = i
end
set ck = ck * k
end
if ck != 0
begin
return false
end
set... | class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return True
j = 0
ck =1
while num not in [2,3,5]:
for i in [2,3,5]:
k = num % i
if k == 0:
... | Python | zaydzuhri_stack_edu_python |
function g1 self nx ny x_des
begin
comment :evaluating unscaled constraints at the initial point
set g_1_0 = call g1_unscaled nx ny 0.5 * ones 4 * nx + 5 * ny
comment :evaluating unscaled constraints:
set g_1 = call g1_unscaled nx ny x_des
comment :define the threshold "tow" to translate the scaled constraint
comment :... | def g1(self, nx, ny, x_des):
# :evaluating unscaled constraints at the initial point
g_1_0 = self.g1_unscaled(nx, ny, .5 * np.ones(4 * nx + 5 * ny))
# :evaluating unscaled constraints:
g_1 = self.g1_unscaled(nx, ny, x_des)
# :define the threshold "tow" to translate the scaled ... | Python | nomic_cornstack_python_v1 |
function load_ipython_extension ip
begin
comment this fails in both Firefox and Chrome for OS X.
comment I get the error: TypeError: IPython.CodeCell.config_defaults is undefined
comment js = "IPython.CodeCell.config_defaults.highlight_modes['magic_kql'] = {'reg':[/^%%kql/]};"
comment display_javascript(js, raw=True)
s... | def load_ipython_extension(ip):
# this fails in both Firefox and Chrome for OS X.
# I get the error: TypeError: IPython.CodeCell.config_defaults is undefined
# js = "IPython.CodeCell.config_defaults.highlight_modes['magic_kql'] = {'reg':[/^%%kql/]};"
# display_javascript(js, raw=True)
result = ip.... | Python | nomic_cornstack_python_v1 |
function validate
begin
set divcount = 0
set notDivcount = 0
for x in range 1500 2500
begin
if x % 5 == 0 and x % 7 == 0
begin
set divcount = divcount + 1
print x
end
else
begin
set notDivcount = notDivcount + 1
end
end
print string divcount, divcount
print string notDivcount, notDivcount
end function
call validate | def validate():
divcount = 0;
notDivcount =0;
for x in range(1500,2500):
if (x%5==0) and (x%7==0):
divcount = divcount + 1
print(x)
else:
notDivcount = notDivcount + 1
print("divcount,", divcount );
print("notDivcount,", notDivcount ); ... | Python | zaydzuhri_stack_edu_python |
function _tz_to_naive datetime_index
begin
if tzinfo is none
begin
return datetime_index
end
comment Calculate timezone offset relative to UTC
set timestamp = datetime_index at 0
set tz_offset = replace timestamp tzinfo=none - replace call tz_convert string UTC tzinfo=none
set tz_offset_td64 = call timedelta64 tz_offse... | def _tz_to_naive(datetime_index):
if datetime_index.tzinfo is None:
return datetime_index
# Calculate timezone offset relative to UTC
timestamp = datetime_index[0]
tz_offset = (timestamp.replace(tzinfo=None) -
timestamp.tz_convert('UTC').replace(tzinfo=None))
tz_offset_td6... | Python | nomic_cornstack_python_v1 |
async function _call_alo self ordinal args
begin
comment noinspection PyProtectedMember
return await call _call_by_ordinal ordinal args
end function | async def _call_alo(self, ordinal: int, args: bytes) -> bytes:
# noinspection PyProtectedMember
return await self._skel._call_by_ordinal(ordinal, args) | Python | nomic_cornstack_python_v1 |
function product x
begin
set t = 1
for i in x
begin
set t = t * i
end
return t
end function | def product(x):
t=1
for i in x:
t*=i
return t | Python | zaydzuhri_stack_edu_python |
function get_func_bytes *args
begin
return call get_func_bytes *args
end function | def get_func_bytes(*args):
return _idaapi.get_func_bytes(*args) | Python | nomic_cornstack_python_v1 |
function compogen g_s symbol
begin
if length g_s == 1
begin
return g_s at 0
end
set foo = call subs symbol g_s at 1
if length g_s == 2
begin
return foo
end
return call compogen list foo + g_s at slice 2 : : symbol
end function | def compogen(g_s, symbol):
if len(g_s) == 1:
return g_s[0]
foo = g_s[0].subs(symbol, g_s[1])
if len(g_s) == 2:
return foo
return compogen([foo] + g_s[2:], symbol) | Python | nomic_cornstack_python_v1 |
function run self *args **kwargs
begin
call self context *args keyword kwargs
end function | def run(self, *args, **kwargs) -> None:
self(self.context, *args, **kwargs) | 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.