code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function main begin set module = call AnsibleModule argument_spec=dictionary pn_cliusername=dictionary required=false type=string str pn_clipassword=dictionary required=false type=string str no_log=true pn_switch=dictionary required=true type=string str pn_vlan_data=dictionary required=false type=string str default=str...
def main(): module = AnsibleModule( argument_spec=dict( pn_cliusername=dict(required=False, type='str'), pn_clipassword=dict(required=False, type='str', no_log=True), pn_switch=dict(required=True, type='str'), pn_vlan_data=dict(required=False, type='str', defa...
Python
nomic_cornstack_python_v1
string # Phonix and Soundex Python implementation This is an implementation of the phonix phonetic search algorith [1,2]. This follows the perl[3] and [4] C implementations. Phonix (phonetic indexing) is a technique based on Soundex, but to which 'phonetic substitution' has been added as an integral part of both the en...
''' # Phonix and Soundex Python implementation This is an implementation of the phonix phonetic search algorith [1,2]. This follows the perl[3] and [4] C implementations. Phonix (phonetic indexing) is a technique based on Soundex, but to which 'phonetic substitution' has been added as an integral part of both the enco...
Python
zaydzuhri_stack_edu_python
class Solution begin function recursion self s begin set maxx = 0 set l = list if length s == 0 begin append l 0 return string 0 end comment empty hash set d = dict comment count set c = 0 comment maximum count set max_c = 0 for i in range length s begin if s at i in d begin set d = dict set c = 1 set d at s at i = ...
class Solution: def recursion(self,s): maxx = 0 l = [] if len(s) == 0: l.append(0) return '0' d = {} # empty hash c = 0 # count max_c = 0 # maximum count ...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.common.keys import Keys class PageObject begin function __init__ self begin set driver = call init_driver call maximize_window call implicitly_wait 10 get driver string http://localhost:3000/ end function function init_driver self begin set driver = call Chrome ret...
from selenium import webdriver from selenium.webdriver.common.keys import Keys class PageObject: def __init__(self): self.driver = self.init_driver() self.driver.maximize_window() self.driver.implicitly_wait(10) self.driver.get("http://localhost:3000/") def init_driver(self):...
Python
zaydzuhri_stack_edu_python
import sys from unittest import TestCase append path string ./ import Bankingchatbot class TestBankingChatbot extends TestCase begin function test_response self begin assert in call response string hi 1 list string Hello string Good to see you string Hi there, how can I help? assert in call response string hi there 1 l...
import sys from unittest import TestCase sys.path.append('./') import Bankingchatbot class TestBankingChatbot(TestCase): def test_response(self): self.assertIn(Bankingchatbot.response('hi',1),["Hello", "Good to see you", "Hi there, how can I help?"]) self.assertIn(Bankingchatbot.response('hi the...
Python
zaydzuhri_stack_edu_python
function update self measurement lane_id begin if lane_id == 1 begin set H_curr = H_lane_1 set R_curr = R at tuple slice : 2 : slice : 2 : end if lane_id == 2 begin set H_curr = H_lane_2 set R_curr = R at tuple slice 2 : 4 : slice 2 : 4 : end if lane_id == 3 begin set H_curr = H_lane_3 set R_curr = R at tuple sli...
def update(self, measurement, lane_id): if lane_id == 1: H_curr = self.H_lane_1 R_curr = self.R[:2, :2] if lane_id == 2: H_curr = self.H_lane_2 R_curr = self.R[2:4, 2:4] if lane_id == 3: H_curr = self.H_lane_3 R_curr = self....
Python
nomic_cornstack_python_v1
function populate_requirement_set requirement_set args options finder session name wheel_cache begin string Marshal cmd line args into a requirement set. for req in args begin call add_requirement call from_line req none isolated=isolated_mode wheel_cache=wheel_cache end for req in editables begin call add_requirement ...
def populate_requirement_set(requirement_set, args, options, finder, session, name, wheel_cache): """ Marshal cmd line args into a requirement set. """ for req in args: requirement_set.add_requirement( InstallRequirement.from_l...
Python
jtatman_500k
from random import randint class Die begin function __init__ self begin set sides = 6 end function function setlength self length begin set sides = length end function function roll_die self begin set a = random integer 1 sides print string 在1和你设置的长度之间的一个随机数为: + string a end function end class set die = call Die for b ...
from random import randint class Die(): def __init__(self): self.sides=6 def setlength(self,length): self.sides=length def roll_die(self): a=randint(1,self.sides) print('在1和你设置的长度之间的一个随机数为:'+str(a)) die=Die() for b in range(1,11): die.roll_die...
Python
zaydzuhri_stack_edu_python
function test_naivedictltm begin call _test_ltm call NaiveDictLTM activation_cls=FrequencyActivation end function
def test_naivedictltm(): _test_ltm(NaiveDictLTM(activation_cls=FrequencyActivation))
Python
nomic_cornstack_python_v1
function _is_google_env begin set tf_config = loads get environ _TF_CONFIG_ENV or string {} if not tf_config begin warn string TF_CONFIG should not be empty in distributed environment. end return get tf_config _ENVIRONMENT_KEY == _ENVIRONMENT_GOOGLE_VALUE end function
def _is_google_env(): tf_config = json.loads(os.environ.get(_TF_CONFIG_ENV) or '{}') if not tf_config: logging.warn('TF_CONFIG should not be empty in distributed environment.') return tf_config.get(_ENVIRONMENT_KEY) == _ENVIRONMENT_GOOGLE_VALUE
Python
nomic_cornstack_python_v1
string Rich Terminal Text Installation: $ pip3 install rich Verify $ python3 -m rich References: https://github.com/willmcgugan/rich https://rich.readthedocs.io/en/latest/index.html https://www.youtube.com/watch?v=4zbehnz-8QU https://pypi.org/project/rich/ Examples/Demos: $ python3 -m rich #Test output, shows in genera...
""" Rich Terminal Text Installation: $ pip3 install rich Verify $ python3 -m rich References: https://github.com/willmcgugan/rich https://rich.readthedocs.io/en/latest/index.html https://www.youtube.com/watch?v=4zbehnz-8QU https://pypi.org/project/rich/ Examples/Demos: $ python3 -m ri...
Python
zaydzuhri_stack_edu_python
comment Import socket module import socket import sys comment Create a socket object set s = call socket comment Define the port on which you want to connect set port = 4444 comment connect to the server on local computer call connect tuple string 10.0.0.175 port print string You are now connected to your classroom ser...
# Import socket module import socket import sys # Create a socket object s = socket.socket() # Define the port on which you want to connect port = 4444 # connect to the server on local computer s.connect(('10.0.0.175', port)) print("You are now connected to your classroom server. Just type yes or no into your input...
Python
zaydzuhri_stack_edu_python
string DMOJ CCC 2004 S1 - Fix https://dmoj.ca/problem/ccc04s1 Jerry Cheng import sys set input = readline set N = integer strip input set words = list for i in range N begin append words list for j in range 3 begin append words at i string strip input end sort words at i key=len end for i in range N begin set fixfree ...
''' DMOJ CCC 2004 S1 - Fix https://dmoj.ca/problem/ccc04s1 Jerry Cheng ''' import sys input = sys.stdin.readline N = int(input().strip()) words = [] for i in range(N): words.append([]) for j in range(3): words[i].append(str(input().strip())) words[i].sort(key=len) for i in range(N): fixfree ...
Python
zaydzuhri_stack_edu_python
import tkinter as tk import random import time from PIL import Image , ImageTk comment 60Hz - Refresh rate set CLOCK_SPEED = 33 set BOUNCE_STRENGTH = 20 set MOVE_INCREMENT = 15 class Graphics extends Canvas begin function __init__ self begin call __init__ width=600 height=620 highlightthickness=0 set ball_position = tu...
import tkinter as tk import random import time from PIL import Image, ImageTk CLOCK_SPEED = 33 #60Hz - Refresh rate BOUNCE_STRENGTH = 20 MOVE_INCREMENT = 15 class Graphics(tk.Canvas): def __init__(self): super().__init__(width=600, height=620, highlightthickness=0) self.ball_position = (300, 500)...
Python
zaydzuhri_stack_edu_python
function template self begin string Create a rules file in iptables-restore format set s = call Template _IPTABLES_TEMPLATE return call substitute filtertable=join string filters rawtable=join string raw mangletable=join string mangle nattable=join string nat date=today end function
def template(self): """ Create a rules file in iptables-restore format """ s = Template(self._IPTABLES_TEMPLATE) return s.substitute(filtertable='\n'.join(self.filters), rawtable='\n'.join(self.raw), mangletable='\n'.join(self.mangle), nattable='\n'.join(self.nat), date=datetime.today(...
Python
jtatman_500k
function download_packs_from_gcp storage_bucket gcp_path destination_path circle_build branch_name begin set zipped_packs = list with call ThreadPoolExecutor max_workers=MAX_THREADS as executor begin comment Get all the pack names for pack in call scandir PACKS_FULL_PATH begin if name in IGNORED_FILES begin continue e...
def download_packs_from_gcp(storage_bucket, gcp_path, destination_path, circle_build, branch_name): zipped_packs = [] with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: for pack in os.scandir(PACKS_FULL_PATH): # Get all the pack names if pack.name in IGNORED_FILES: ...
Python
nomic_cornstack_python_v1
function sort_by_length words begin return sorted words key=len end function
def sort_by_length(words): return sorted(words, key=len)
Python
flytech_python_25k
function get_iat_rva_with_size self begin set rva = 0 set size = 0 for entry in DATA_DIRECTORY begin if name == string IMAGE_DIRECTORY_ENTRY_IAT begin set rva = VirtualAddress set size = Size end end return tuple rva size end function
def get_iat_rva_with_size(self): rva = 0 size = 0 for entry in self.PE.OPTIONAL_HEADER.DATA_DIRECTORY: if entry.name == 'IMAGE_DIRECTORY_ENTRY_IAT': rva = entry.VirtualAddress size = entry.Size return rva, size
Python
nomic_cornstack_python_v1
comment !/bin/python3 import sys set t = integer strip input for a0 in range t begin set n = integer strip input if n <= 1 begin print 0 end else begin set result = 0 set f = 0 set s = 1 set temp = 0 while temp <= n begin set temp = f + s set tuple f s = tuple s temp if temp % 2 == 0 and temp <= n begin set result = re...
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n = int(input().strip()) if n<= 1: print(0) else: result = 0 f= 0 s= 1 temp = 0 while temp<=n: temp = f+s f,s = s,temp if temp%2 == 0 and temp <=n: ...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment In[1]: set x = 5 + 4 print x comment In[3]: print string hello,world! comment In[4]: set x = 4 print x * x comment In[7]: set x = string hello print x * 2 comment In[9]: set tuple a b = tuple 1 2 set tuple a b = tuple b a print a a + b comment In[11]: set tuple a b = tuple 2 6 set tuple a ...
# coding: utf-8 # In[1]: x = 5 + 4 print(x) # In[3]: print ('hello,world!') # In[4]: x =4 print(x*x) # In[7]: x = 'hello' print(x*2) # In[9]: a,b = 1,2 a,b = b,a print(a) a+b # In[11]: a,b = 2,6 a,b = b,a+2 print(a,b) # In[14]: x = ''' this is multiline string the''' print (x) # In[17]: def squ...
Python
zaydzuhri_stack_edu_python
from pygame.locals import * from game import * comment initialize pygame call init comment creation et definition des paramètres de la fenetre set window = call set_mode tuple 640 480 comment on defini et colle le fond set background = call convert set game = call Game set slown = 1 set timer = call Clock comment boucl...
from pygame.locals import * from game import * pygame.init() #initialize pygame window = pygame.display.set_mode((640, 480)) #creation et definition des paramètres de la fenetre background = pygame.image.load("domo.background.png").convert() #on defini et colle le fond game = Game() slown = 1 timer ...
Python
zaydzuhri_stack_edu_python
function modules self begin return set values functions end function
def modules(self): return set(self.functions.values())
Python
nomic_cornstack_python_v1
function zscore_normalization X begin set z_score = call zscore X axis=1 return z_score end function
def zscore_normalization(X): z_score = stats.zscore(X, axis=1) return z_score
Python
nomic_cornstack_python_v1
function process_fidelity self reference_unitary begin string Compute the quantum process fidelity of the estimated state with respect to a unitary process. For non-sparse reference_unitary, this implementation this will be expensive in higher dimensions. :param (qutip.Qobj|matrix-like) reference_unitary: A unitary ope...
def process_fidelity(self, reference_unitary): """ Compute the quantum process fidelity of the estimated state with respect to a unitary process. For non-sparse reference_unitary, this implementation this will be expensive in higher dimensions. :param (qutip.Qobj|matrix-like) re...
Python
jtatman_500k
comment !/usr/bin/env python3 import sys import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots set csv_file = argv at 1 print format string Reading {} csv_file set columns = list string date string temperature string humidity string pressure string gas resistance set df = read ...
#!/usr/bin/env python3 import sys import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots csv_file = sys.argv[1] print('Reading {}'.format(csv_file)) columns = ['date', 'temperature', 'humidity', 'pressure', 'gas resistance'] df = pd.read_csv(csv_file, names=columns); fig = m...
Python
zaydzuhri_stack_edu_python
function bulk_coordinates_download postcodes begin set api_url = string https://api.postcodes.io/postcodes set params = dict string postcodes[] postcodes comment Build url encoded data set data = url encode params true comment Convert string to byte set data = encode data string utf-8 comment Prepare the request set re...
def bulk_coordinates_download(postcodes: [str]) -> [object]: api_url = "https://api.postcodes.io/postcodes" params = {"postcodes[]": postcodes} # Build url encoded data data = urlencode(params, True) # Convert string to byte data = data.encode("utf-8") # Prepare the request req = re...
Python
nomic_cornstack_python_v1
function save self **kwargs begin if length words > 0 begin set words = right strip strip words end set word_count = call _calculate_word_count save keyword kwargs end function
def save(self, **kwargs): if len(self.words) > 0: self.words = self.words.strip().rstrip() self.word_count = self._calculate_word_count() super(Term, self).save(**kwargs)
Python
nomic_cornstack_python_v1
import requests import os set url = string http://ww3.sinaimg.cn/bmiddle/9150e4e5ly1fryaw710l9j20u00ttab5.jpg set root = string D://python// set path = root + split url string / at - 1 try begin if not exists path root begin make directory os root end if not exists path path begin set response = get requests url commen...
import requests import os url="http://ww3.sinaimg.cn/bmiddle/9150e4e5ly1fryaw710l9j20u00ttab5.jpg" root="D://python//" path=root+url.split('/')[-1] try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): response=requests.get(url) # print(response.content) w...
Python
zaydzuhri_stack_edu_python
comment openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem import socket import ssl import os comment change the following value to match your IP address comment windows: ipconfig comment mac/linux: ifconfig set HOST = string 152.20.244.151 set PORT = 40043 set CERTIFICATE = join p...
# openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem import socket import ssl import os # change the following value to match your IP address # windows: ipconfig # mac/linux: ifconfig HOST = '152.20.244.151' PORT = 40043 CERTIFICATE = os.path.join('secrets', 'certificate.pem') ...
Python
zaydzuhri_stack_edu_python
for i in range n begin set tuple a b c = map int split call raw_input end
for i in range(n): a, b, c = map( int, raw_input().split() )
Python
zaydzuhri_stack_edu_python
function GroupId self begin return call _get_attribute string groupId end function
def GroupId(self): return self._get_attribute('groupId')
Python
nomic_cornstack_python_v1
string Module for handling the interface of WKT2 for the geodetic coordinate reference system. from abc import abstractmethod from string import Template from typing import Dict from iwkt import IWKT class IGeodeticCRS extends IWKT begin string Interface for creating the WKT2 of the geodetic coordinate reference system...
"""Module for handling the interface of WKT2 for the geodetic coordinate reference system.""" from abc import abstractmethod from string import Template from typing import Dict from .iwkt import IWKT class IGeodeticCRS(IWKT): """Interface for creating the WKT2 of the geodetic coordinate reference system.""" ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import pandas as pd from mytools.met_tools import print_all function compute_cuo o3_mu o3_sigma gs_o3 gs_o3_sigma exp_hours exp_days **kwarg begin string Compute the ozone exposure using MC. Parameters: Daily ozone exposure mean, std (ppb). Hours of exposure per day. T...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from mytools.met_tools import print_all def compute_cuo(o3_mu, o3_sigma, gs_o3, gs_o3_sigma, exp_hours, exp_days, **kwarg): ''' Compute the ozone exposure using MC. Parameters: Daily ozone exposure mean, std (ppb). Hours of expo...
Python
zaydzuhri_stack_edu_python
function get_args begin comment setup the parser set parser = call ArgumentParser description=string Image Resizing: given a path to an image, resize it by a factor of 5 and save a copy. comment helper description set input_path_desc = string The path to the input file. set input_image_desc = string The name of the ima...
def get_args(): # setup the parser parser = argparse.ArgumentParser( description="Image Resizing: given a path to an image, resize it by a factor of 5 and save a copy." ) # helper description input_path_desc = "The path to the input file." input_image_desc = "The name of the image to o...
Python
nomic_cornstack_python_v1
function removeAllocation allocationID=list begin if type allocationID != list begin set allocationID = list string allocationID end if length allocationID == 0 begin return end if length allocationID == 1 begin set sqlStr = string DELETE FROM we_Allocation WHERE id="%s" % string allocationID at 0 end else begin set sq...
def removeAllocation(allocationID=[]): if(type(allocationID)!=list): allocationID=[str(allocationID)] if len(allocationID)==0: return if len(allocationID)==1: sqlStr="""DELETE FROM we_Allocation WHERE id="%s" """ %(str(allocationID[0])) else: sqlStr="""DELETE FROM we_Allocation W...
Python
nomic_cornstack_python_v1
import TTBoard as TTBoardSoln function main begin comment create an empty board comment this is the root of the tree set doPointAdj = true set doAlphaBeta = false set numboards = 0 set numsearched = 0 set bd = call TTBoard XMOVE pointAdj=doPointAdj comment create a board for every possible initial X move call createchi...
import TTBoard as TTBoardSoln def main(): # create an empty board # this is the root of the tree doPointAdj = True doAlphaBeta = False TTBoardSoln.TTBoard.numboards = 0 TTBoardSoln.TTBoard.numsearched = 0 bd = TTBoardSoln.TTBoard(TTBoardSoln.XMOVE, pointAdj=doPointAdj) # cre...
Python
zaydzuhri_stack_edu_python
function get_certificate_subject cert_file_path nameopt=string begin set args = list string openssl string x509 string -subject string -in cert_file_path string -noout if nameopt != string begin append args string -nameopt append args nameopt end set proc = popen args stdout=PIPE stderr=PIPE set tuple out err = commun...
def get_certificate_subject(cert_file_path, nameopt=''): args = [ 'openssl', 'x509', '-subject', '-in', cert_file_path, '-noout' ] if nameopt != '': args.append('-nameopt') args.append(nameopt) proc = Popen(args, stdout = PIPE, stderr = PIPE) (out, err) = proc.communicate() returncod...
Python
nomic_cornstack_python_v1
import sys import pygame from pygame.sprite import Group from settings import Settings from ship import Ship import game_functions as gf from alien import Alien from game_stats import GameStats from button import Button from scoreboard import ScoreBoard function run_game begin call init set ai_settings = call Settings ...
import sys import pygame from pygame.sprite import Group from settings import Settings from ship import Ship import game_functions as gf from alien import Alien from game_stats import GameStats from button import Button from scoreboard import ScoreBoard def run_game(): pygame.init() ai_settings = Settings()...
Python
zaydzuhri_stack_edu_python
comment 追加一条动态信息 write file string 拉开始,的放假了空间,反复塑料袋快放假啊加就 print string 写入了一条动态..... close file
#追加一条动态信息 file.write("拉开始,的放假了空间,反复塑料袋快放假啊加就\n") print("\n 写入了一条动态.....\n") file.close()
Python
zaydzuhri_stack_edu_python
comment v1 string a = input('enter a list separated by a space: ') a = a.split() r_list = [] n_list = [a[i:i + 2] for i in range(0, len(a), 2)] for s_list in n_list: s_list.reverse() r_list.extend(s_list) print(r_list) comment v2 set a = input string enter a list separated by a space: set a = split a set r_list = list ...
#v1 '''a = input('enter a list separated by a space: ') a = a.split() r_list = [] n_list = [a[i:i + 2] for i in range(0, len(a), 2)] for s_list in n_list: s_list.reverse() r_list.extend(s_list) print(r_list)''' #v2 a = input('enter a list separated by a space: ') a = a.split() r_list = [] n_list = [a[i:i + 2] f...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment ======================================================================================================================= function main begin set in_file = string data_file.csv set out_file = string no_0.0005_data_file.txt set fp_in = open in_file string r set fp_out = open out_file stri...
#!/usr/bin/python3 #======================================================================================================================= def main(): in_file = "data_file.csv" out_file = "no_0.0005_data_file.txt" fp_in = open(in_file, "r") fp_out = open(out_file, "w") for in_data in fp_in: in_data = ...
Python
zaydzuhri_stack_edu_python
function get_catalogitem_byname self name catalog=false begin if not catalog begin set catalog = call get_entitled_catalog_items end set result = list if name begin for i in catalog at string content begin set target = i at string catalogItem at string name if lower name in lower target begin set element = dict string...
def get_catalogitem_byname(self, name, catalog=False): if not catalog: catalog = self.get_entitled_catalog_items() result = [] if name: for i in catalog['content']: target = i['catalogItem']['name'] if name.lower() in target.lower(): ...
Python
nomic_cornstack_python_v1
function get self begin set auto = get request string auto comment [START gae_runtime] comment sample function to run in a background thread function change_val arg begin global val set val = arg end function if auto begin comment Start the new thread in one command call start_new_background_thread change_val list stri...
def get(self): auto = self.request.get("auto") # [START gae_runtime] # sample function to run in a background thread def change_val(arg): global val val = arg if auto: # Start the new thread in one command background_thread.start_...
Python
nomic_cornstack_python_v1
function object_id self begin return get pulumi self string object_id end function
def object_id(self) -> Optional[str]: return pulumi.get(self, "object_id")
Python
nomic_cornstack_python_v1
import math set year_type = input set bank_holidays = integer input set weekends_home = integer input set games_in_sofia = 48 - weekends_home / 4 * 3 set bank_holidays_games = bank_holidays / 3 * 2 set total_games = weekends_home + games_in_sofia + bank_holidays_games if year_type == string normal begin print floor tot...
import math year_type = input() bank_holidays = int(input()) weekends_home = int(input()) games_in_sofia = (48 - weekends_home) / 4 * 3 bank_holidays_games = bank_holidays / 3 * 2 total_games = weekends_home + games_in_sofia + bank_holidays_games if year_type == "normal": print(math.floor(total_games)) elif yea...
Python
zaydzuhri_stack_edu_python
string 实现文件夹下文件自动分类 import os import shutil get current directory list directory change directory string ../files for f in files begin set folder = split f string . at - 1 if not exists path folder begin make directory os folder move f folder end else begin move f folder end end
''' 实现文件夹下文件自动分类 ''' import os import shutil os.getcwd() os.listdir() os.chdir("../files") for f in files: folder = f.split('.')[-1] if not os.path.exists(folder): os.mkdir(folder) shutil.move(f, folder) else: shutil.move(f, folder)
Python
zaydzuhri_stack_edu_python
string Wrapper for Steam API. from itertools import cycle import json import time import sys import socket from urllib.request import urlopen from urllib.error import HTTPError , URLError import logging from typing import Dict , Any , Tuple comment limited to 100,000 calls to the Steam Web API per day comment 429: Too ...
""" Wrapper for Steam API. """ from itertools import cycle import json import time import sys import socket from urllib.request import urlopen from urllib.error import HTTPError, URLError import logging from typing import Dict, Any, Tuple # limited to 100,000 calls to the Steam Web API per day RATE_LIMIT_CODES = set(...
Python
zaydzuhri_stack_edu_python
function connect self address server_hostname=none begin string Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of s...
def connect( self: _IOStreamType, address: tuple, server_hostname: str = None ) -> "Future[_IOStreamType]": """Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is...
Python
jtatman_500k
from fpdf import FPDF comment P - Portrait comment L - Landscape set pdf = call FPDF string P string mm string A4 call add_page comment Antes de inserir um texto no pdf, devemos determinar a fonte a ser usada comment 1º argumento é a fonte, 2º argumento é o estilo (Bold, italic, sublimed) 3º argumento é o tamanho da fo...
from fpdf import FPDF #P - Portrait #L - Landscape # pdf = FPDF('P','mm', 'A4') pdf.add_page() #Antes de inserir um texto no pdf, devemos determinar a fonte a ser usada #1º argumento é a fonte, 2º argumento é o estilo (Bold, italic, sublimed) 3º argumento é o tamanho da fonte pdf.set_font('Arial','B', 16) #colocan...
Python
zaydzuhri_stack_edu_python
function init_notebook begin set STATIC_URL = string https://cdn.rawgit.com/napjon/krisk/master/krisk/static set ECHARTS_VERSION = string 3.2.1 set ECHARTS_URL = format string https://cdnjs.cloudflare.com/ajax/libs/echarts/{ECHARTS_VERSION}/echarts.min ECHARTS_VERSION=ECHARTS_VERSION from IPython.display import Javascr...
def init_notebook(): STATIC_URL = "https://cdn.rawgit.com/napjon/krisk/master/krisk/static" ECHARTS_VERSION = "3.2.1" ECHARTS_URL = ("https://cdnjs.cloudflare.com/ajax/libs/echarts/{ECHARTS_VERSION}/echarts.min" .format(ECHARTS_VERSION=ECHARTS_VERSION)) from IPython.display import Ja...
Python
nomic_cornstack_python_v1
function add_features self fbids begin if not fbids begin warn string No fbids provided. return false end set feats = call name_synonym_lookup fbids set proc_names = list comprehension call _asdict for f in values feats for d in proc_names begin set d at string synonyms = join string | d at string synonyms end set stat...
def add_features(self, fbids): if not fbids: warnings.warn("No fbids provided.") return False feats = self.name_synonym_lookup(fbids) proc_names = [f._asdict() for f in feats.values()] for d in proc_names: d['synonyms'] = '|'.join(d['synonyms']) ...
Python
nomic_cornstack_python_v1
function SetupTestRun begin set archive_path = join path _RESULTS_PATH string archive set current_path = join path _RESULTS_PATH string current set baseline_path = join path _RESULTS_PATH string baseline set config_dirname = conf comment Current date for archive folder names. set curdate = string format time time strin...
def SetupTestRun(): archive_path = os.path.join(_RESULTS_PATH, 'archive') current_path = os.path.join(_RESULTS_PATH, 'current') baseline_path = os.path.join(_RESULTS_PATH, 'baseline') config_dirname = options.conf # Current date for archive folder names. curdate = time.strftime("%Y%m%d%H%M%S") # Create ...
Python
nomic_cornstack_python_v1
import os import json from typing import List , Dict import util function scan_addon_directory path addon_list begin set found_files = list set found_dirs = list set path = replace path string \ string / set force_default_load_order = false comment Check for default_load_order: set module_info_path = join path path s...
import os import json from typing import List, Dict import util def scan_addon_directory(path: str, addon_list: list): found_files = [] found_dirs = [] path=path.replace('\\', "/") force_default_load_order = False # Check for default_load_order: module_info_path = os.path.join(path, "modul...
Python
zaydzuhri_stack_edu_python
function maxlike self nseeds=50 begin string Returns the best-fit parameters, choosing the best of multiple starting guesses :param nseeds: (optional) Number of starting guesses, uniformly distributed throughout allowed ranges. Default=50. :return: list of best-fit parameters: ``[mA,mB,age,feh,[distance,A_V]]``. Note t...
def maxlike(self,nseeds=50): """Returns the best-fit parameters, choosing the best of multiple starting guesses :param nseeds: (optional) Number of starting guesses, uniformly distributed throughout allowed ranges. Default=50. :return: list of best-fit para...
Python
jtatman_500k
string 模仿mnist hello world 二进制转成十进制数字 import tensorflow as tf import numpy as np import os set environ at string TF_CPP_MIN_LOG_LEVEL = string 2 set x = call placeholder float32 shape=tuple none 4 comment [10, 4]其实就是shape set W = call Variable zeros list 4 10 set b = call Variable zeros list 10 comment 激励函数可用 sigmoid s...
''' 模仿mnist hello world 二进制转成十进制数字 ''' import tensorflow as tf import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' x = tf.placeholder(tf.float32, shape=(None, 4) ) W = tf.Variable( tf.zeros([4, 10]) ) # [10, 4]其实就是shape b = tf.Variable( tf.zeros([10]) ) # 激励函数可用 sigmoid softmax #y = tf.matmul(x, W...
Python
zaydzuhri_stack_edu_python
function _rowPtrs self img c_type begin set ptrType = call POINTER c_type set rowPtrs = call *[row.ctypes.data_as(ptrType) for row in img] return rowPtrs end function
def _rowPtrs(self, img, c_type): ptrType = ctypes.POINTER(c_type) rowPtrs = (ptrType*len(img))(*[row.ctypes.data_as(ptrType) for row in img]) return rowPtrs
Python
nomic_cornstack_python_v1
function comparison self idx=1 hand_tagged=none auto_tagged=none begin if hand_tagged is none begin set hand_tagged = hand_tagged end if auto_tagged is none begin set auto_tagged = auto_tagged end if length hand_tagged == length auto_tagged begin set rl = list comprehension if expression hand_tagged at i == format stri...
def comparison(self, idx=1, hand_tagged=None, auto_tagged=None): if hand_tagged is None: hand_tagged = self.hand_tagged if auto_tagged is None: auto_tagged = self.auto_tagged if len(hand_tagged) == len(auto_tagged): rl = [1 if hand_tagged[i] == u'{}{}{}'.forma...
Python
nomic_cornstack_python_v1
function get_freq_score data begin set score = 0 if is instance data str begin set data = call fromstring data dtype=uint8 end for d in data begin set score = score + freqtable at d end return score end function
def get_freq_score(data): score = 0 if isinstance(data, str): data = numpy.fromstring(data, dtype=numpy.uint8) for d in data: score += freqtable[d] return score
Python
nomic_cornstack_python_v1
function showstars self verbose=true begin try begin import f2n end except ImportError begin print string Couldn't import f2n -- install it ! return end if verbose begin print string Writing png ... end set myimage = call fromfits filepath verbose=false comment myimage.rebin(int(myimage.xb/1000.0)) call setzscale strin...
def showstars(self, verbose=True): try: import f2n except ImportError: print("Couldn't import f2n -- install it !") return if verbose: print("Writing png ...") myimage = f2n.fromfits(self.filepath, verbose=False) # myimage.rebin(in...
Python
nomic_cornstack_python_v1
string Omnia config from __future__ import absolute_import from __future__ import unicode_literals import re from import util from import errors class Config extends object begin string Config stores registered database configurations set __metaclass__ = SingletonMeta set SUPPORTED_DRIVERS = tuple string postgresql s...
""" Omnia config """ from __future__ import absolute_import from __future__ import unicode_literals import re from . import util from .. import errors class Config(object): """ Config stores registered database configurations """ __metaclass__ = util.SingletonMeta SUPPORTED_DRIVERS = ( ...
Python
zaydzuhri_stack_edu_python
function do_testability self arg begin if active is not none begin if strip arg == string begin set fmtstr = string {0:<40s} | {1:^10.2f} | {2:^12.2f} | {3:^5.2f} | set headstr = string {0:<40s} | {1:^10s} | {2:^12s} | {3:^5s} | set dheader = format headstr *('Executable Identifier', 'Dep. Score', 'Param. Score', 'Tot...
def do_testability(self, arg): if self.active is not None: if arg.strip() == "": fmtstr = "{0:<40s} | {1:^10.2f} | {2:^12.2f} | {3:^5.2f} |" headstr = "{0:<40s} | {1:^10s} | {2:^12s} | {3:^5s} |" dheader = headstr.format(*("Executable Identifier", "Dep...
Python
nomic_cornstack_python_v1
function create_bucket self bucket_name make_public=false begin set _bucket = call create_bucket bucket_name if make_public begin call make_public recursive=true future=true end print format string Bucket {} created name end function
def create_bucket(self, bucket_name, make_public=False): self._bucket = self.storage_client.create_bucket(bucket_name) if make_public: self._bucket.make_public(recursive=True, future=True) print("Bucket {} created".format(self._bucket.name))
Python
nomic_cornstack_python_v1
import json import codecs function import_data input_path begin set data_format = split input_path string . at - 1 set data = list if data_format == string json begin set data = read open input_path string r encoding=string utf-8 set json_data = loads data return json_data at string shapes end return data end function
import json import codecs def import_data(input_path: str) -> list: data_format = input_path.split('.')[-1] data = [] if data_format == 'json': data = codecs.open( input_path, 'r', encoding='utf-8' ).read() json_data = json.loads(data) return json_data['shapes'...
Python
zaydzuhri_stack_edu_python
function active_qudits self flat=false begin if flat begin set active = dict for gates in _ticks begin update active active_qudits end end else begin set active = list for gates in _ticks begin append active active_qudits end end return active end function
def active_qudits(self, flat=False): if flat: active = {} for gates in self._ticks: active.update(gates.active_qudits) else: active = [] for gates in self._ticks: active.append(gates.active_qudits) return active
Python
nomic_cornstack_python_v1
function test_with_guess_description_auto_and_update self begin call _run_test args=list string --update string --guess-description=auto commit_message=dict string summary string This is the summary. ; string description string This is the multi-line description. expected_request_data=dict end function
def test_with_guess_description_auto_and_update(self): self._run_test( args=[ '--update', '--guess-description=auto', ], commit_message={ 'summary': 'This is the summary.', 'description': ( 'T...
Python
nomic_cornstack_python_v1
function _iter_frequencies q frange mismatch dur begin comment work out how many frequencies we need set tuple minf maxf = frange set fcum_mismatch = log maxf / minf * 2 + q ^ 2 ^ 1 / 2.0 / 2.0 set nfreq = integer max 1 ceil fcum_mismatch / call deltam_f mismatch set fstep = fcum_mismatch / nfreq set fstepmin = 1.0 / d...
def _iter_frequencies(q, frange, mismatch, dur): # work out how many frequencies we need minf, maxf = frange fcum_mismatch = log(maxf / minf) * (2 + q**2)**(1/2.) / 2. nfreq = int(max(1, ceil(fcum_mismatch / deltam_f(mismatch)))) fstep = fcum_mismatch / nfreq fstepmin = 1. / dur # for each f...
Python
nomic_cornstack_python_v1
comment EXPAND STOCK SYMBOL INPUT TO PERMIT MULTIPLE STOCK SELECTION import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input , Output , State comment import pandas_datareader.data as web # requires v0.6.0 or later from datetime import datetime import pandas...
# EXPAND STOCK SYMBOL INPUT TO PERMIT MULTIPLE STOCK SELECTION import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State #import pandas_datareader.data as web # requires v0.6.0 or later from datetime import datetime import pandas as pd import y...
Python
zaydzuhri_stack_edu_python
comment ################### socket客户端 ################### import socket set client = call socket comment 阻塞 call connect tuple string 127.0.0.1 8001 while true begin set content = input string >>> if upper content == string Q begin break end call sendall encode content string utf-8 end close client
# ################### socket客户端 ################### import socket client = socket.socket() # 阻塞 client.connect(('127.0.0.1', 8001)) while True: content = input(">>>") if content.upper() == 'Q': break client.sendall(content.encode('utf-8')) client.close()
Python
zaydzuhri_stack_edu_python
function testEditDistanceBoundaries self begin for profile1 in profiles begin for profile2 in profiles begin assert true call edit_distance profile2 <= 1.0 and call edit_distance profile2 >= 0 end end end function
def testEditDistanceBoundaries(self): for profile1 in self.profiles: for profile2 in self.profiles: self.assertTrue(profile1.edit_distance(profile2) <= 1.0 and profile1.edit_distance(profile2) >= 0)
Python
nomic_cornstack_python_v1
function save self begin with open path string w as f begin write f format config_template name=dumps self at string name root=dumps self at string root socketName=dumps self at string socketName preCmd=dumps self at string preCmd winPreCmd=dumps self at string winPreCmd tmuxCmd=dumps self at string tmuxCmd tmuxOpts=du...
def save(self): with open(self.path, 'w') as f: f.write(self.config_template.format( name=json.dumps(self['name']), root=json.dumps(self['root']), socketName=json.dumps(self['socketName']), preCmd=json.dumps(self['preCmd']), ...
Python
nomic_cornstack_python_v1
function add_md5 self change=string begin if not call check_zope_admin begin return string You must be a zope manager to run this script end from plone import api from imio.dms.mail.setuphandlers import list_templates from Products.CMFPlone.utils import base_hasattr set templates_list = list comprehension tuple tup at ...
def add_md5(self, change=''): if not check_zope_admin(): return "You must be a zope manager to run this script" from plone import api from imio.dms.mail.setuphandlers import list_templates from Products.CMFPlone.utils import base_hasattr templates_list = [(tup[1], tup[2]) for tup in list_tem...
Python
nomic_cornstack_python_v1
function serve_post self path postmap **params begin string Find a POST callback for the given HTTP path, call it and return the results. The callback is called with the path used to match it, a dict of vars from the POST body and params which include the BaseHTTPRequestHandler instance. The callback must return a tupl...
def serve_post(self, path, postmap, **params): """ Find a POST callback for the given HTTP path, call it and return the results. The callback is called with the path used to match it, a dict of vars from the POST body and params which include the BaseHTTPRequestHandler instance....
Python
jtatman_500k
from Day17_1_question_model import Question from Day17_1_data import question_data from Day17_1_quiz_brain import QuizBrain set question_bank = list for item in question_data at string results begin set question = call Question item at string question item at string correct_answer append question_bank question end set...
from Day17_1_question_model import Question from Day17_1_data import question_data from Day17_1_quiz_brain import QuizBrain question_bank = [] for item in question_data["results"]: question = Question(item["question"], item["correct_answer"]) question_bank.append(question) brain = QuizBrain(question_bank) w...
Python
zaydzuhri_stack_edu_python
function replaceResourceQuota self **kwargs begin set allParams = list string name string namespace string body set params = locals for tuple key val in call iteritems begin if key not in allParams begin raise call TypeError string Got an unexpected keyword argument '%s' to method replaceResourceQuota % key end set par...
def replaceResourceQuota(self, **kwargs): allParams = ['name', 'namespace', 'body'] params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s'" " ...
Python
nomic_cornstack_python_v1
string Shows a calendar January 1XX9 where the first of the month is a Thursday. The 26th is circled Clue: "he ain't the youngest, he is the second" Clue: "todo: buy flowers tomorrow" Title: "whom?" comment in what years 1**6 did January 26 fall on Monday? from datetime import date print string Dates from years 1**6, w...
""" Shows a calendar January 1XX9 where the first of the month is a Thursday. The 26th is circled Clue: "he ain't the youngest, he is the second" Clue: "todo: buy flowers tomorrow" Title: "whom?" """ # in what years 1**6 did January 26 fall on Monday? from datetime import date print("Dates from years 1**6, where Jan ...
Python
zaydzuhri_stack_edu_python
while your_answers != our_password and max_try != string Reached begin if no_max_of_try > no_of_try begin set your_answers = input string enter your password set no_of_try = no_of_try + 1 end else begin set max_try = string Reached end end if max_try != string Reached begin print string Account block end else begin pri...
while your_answers != our_password and max_try!="Reached": if no_max_of_try > no_of_try: your_answers =input("enter your password") no_of_try = no_of_try + 1 else:max_try="Reached" if max_try!="Reached": print("Account block") else:print("Access granted")
Python
zaydzuhri_stack_edu_python
function get_npc_classes_for_componentindex cluster_ind_results num_cluster_inds npc_hierarchy fraction_cutoff=0.2 begin comment 1. count the instances of each class in the componentindex (MF) set h_counters = dictionary comprehension h : default dictionary int for h in npc_hierarchy for cluster_ind_res in cluster_ind_...
def get_npc_classes_for_componentindex(cluster_ind_results: List[ Union[str, Dict[str, List[Tuple[Union[str, float]]]]]], num_cluster_inds: int, npc_hierarchy: List[str], fraction_cutoff: float = 0.2...
Python
nomic_cornstack_python_v1
import csv with open string data/flights.csv string r as infile begin set flights = dict reader infile delimiter=string , for flight in flights begin if integer flight at string MONTH == 10 begin print string found! break end end end
import csv with open("data/flights.csv", "r") as infile: flights = csv.DictReader(infile, delimiter=",") for flight in flights: if int(flight["MONTH"]) == 10: print("found!") break
Python
zaydzuhri_stack_edu_python
from math import sqrt class Vector begin function __init__ self x y begin set x = x set y = y end function function __getitem__ self index begin if index == 0 begin return x end return y end function function __setitem__ self index value begin if index == 0 begin set x = value end else begin set y = value end end funct...
from math import sqrt class Vector: def __init__(self, x, y): self.x = x self.y = y def __getitem__(self, index): if index == 0: return self.x return self.y def __setitem__(self, index, value): if index == 0: self.x = value else: ...
Python
zaydzuhri_stack_edu_python
import scrapy from scrapy.selector import Selector from scrapy.http import Request from podcrawler.items import TopCategoryItem , SubGenreItem class CategorySpider extends Spider begin set name = string categories set start_urls = list string https://itunes.apple.com/us/genre/podcasts/id26 set custom_settings = dict st...
import scrapy from scrapy.selector import Selector from scrapy.http import Request from podcrawler.items import TopCategoryItem, SubGenreItem class CategorySpider(scrapy.Spider): name = "categories" start_urls = ["https://itunes.apple.com/us/genre/podcasts/id26"] custom_settings = { 'ITEM_PIPELI...
Python
zaydzuhri_stack_edu_python
function model x_crop y_ reuse begin with call variable_scope string model reuse=reuse begin set net = call InputLayer x_crop name=string input set output1 = conv 2d net 64 tuple 5 5 tuple 1 1 act=relu padding=string SAME name=string cnn1 set net = call MaxPool2d output1 tuple 3 3 tuple 2 2 padding=string SAME name=str...
def model(x_crop, y_, reuse): with tf.variable_scope("model", reuse=reuse): net = tl.layers.InputLayer(x_crop, name='input') output1 = tl.layers.Conv2d(net, 64, (5, 5), (1, 1), act=tf.nn.relu, padding='SAME', name='cnn1') net = tl.layers.MaxPool2d(output1, (3, 3), (2, 2), pad...
Python
nomic_cornstack_python_v1
string Exercice 07 - Create a list For this exercise your goal is to create a list of numbers ranging from 5 to 15 using a basic python function. You should then print this list using the function print
""" Exercice 07 - Create a list For this exercise your goal is to create a list of numbers ranging from 5 to 15 using a basic python function. You should then print this list using the function print """
Python
zaydzuhri_stack_edu_python
function __init__ self input_dim=tuple 3 32 32 num_filters=32 filter_size=7 hidden_dim=100 num_classes=10 weight_scale=0.001 reg=0.0 dtype=float32 begin set params = dict set reg = reg set dtype = dtype comment TODO: Initialize weights and biases for the three-layer convolutional # comment network. Weights should be i...
def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): self.params = {} self.reg = reg self.dtype = dtype ##################################################...
Python
nomic_cornstack_python_v1
function test_clone_change_param self cosmo begin pass end function
def test_clone_change_param(self, cosmo): pass
Python
nomic_cornstack_python_v1
comment time: O(logn) comment space: O(1) function trailingZeroes self n begin set zero_count = 0 set temp = n while n > 0 begin set n = n // 5 set zero_count = zero_count + n end return zero_count end function
# time: O(logn) #space: O(1) def trailingZeroes(self, n: int) -> int: zero_count = 0 temp = n while n >0: n//=5 zero_count+=n return zero_count
Python
zaydzuhri_stack_edu_python
comment *** LAB 02: PYTHON PRACTICE *** comment OBJECTIVE 1: Get accustomed to Python syntax and formatting. comment OBJECTIVE 2: Review concepts of logic, strings, conditionals, and operators. comment NOTE #1: Return statements are used as placeholders below. Change them as necessary. comment NOTE #2: Look up formatti...
# *** LAB 02: PYTHON PRACTICE *** # OBJECTIVE 1: Get accustomed to Python syntax and formatting. # OBJECTIVE 2: Review concepts of logic, strings, conditionals, and operators. # NOTE #1: Return statements are used as placeholders below. Change them as necessary. # NOTE #2: Look up formatting/syntax if you are not sur...
Python
zaydzuhri_stack_edu_python
function domain self begin return call _get string domain string /domain/ DOMAIN_DATA end function
def domain(self): return self._get('domain', '/domain/', self.DOMAIN_DATA)
Python
nomic_cornstack_python_v1
from django.db import models from django.utils.dateformat import DateFormat from django.contrib.auth.models import User class Car extends Model begin set user = call ForeignKey User set label = call CharField max_length=250 set date_purchased = call DateField set initial_cost = call PositiveIntegerField default=0 set i...
from django.db import models from django.utils.dateformat import DateFormat from django.contrib.auth.models import User class Car(models.Model): user = models.ForeignKey(User) label = models.CharField(max_length=250) date_purchased = models.DateField() initial_cost = models.PositiveIntegerField(defaul...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution begin function maxDepth self root begin comment 2021.03.19 comment Max depth ~10^4, extreme unbalanced bi...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: # 2021.03.19 # Max depth ~10^4, extreme unbalanc...
Python
zaydzuhri_stack_edu_python
function remove_duplicates numbers begin set newlist = list for number in numbers begin if number not in newlist begin append newlist number end end return newlist end function
def remove_duplicates(numbers): newlist = [] for number in numbers: if number not in newlist: newlist.append(number) return newlist
Python
zaydzuhri_stack_edu_python
function showTraceInfo self traceName=none begin if traceName is not none begin if not traceName in traces begin call fail string Trace not found: %s % traceName end set traces = dict traceName traces at traceName end else begin set traces = traces end set arrayElementSizes = dict ByteArrayValue 1 ; ShortArrayValue 2 ;...
def showTraceInfo(self, traceName = None): if traceName is not None: if not traceName in self.analyzer.traces: self.analyzer.fail("Trace not found: %s" % traceName) traces = {traceName: self.analyzer.traces[traceName]} else: traces = self.analyzer.traces arrayElement...
Python
nomic_cornstack_python_v1
function parse_table japanese_rows character_map insert_key basic_class begin set max_len = length japanese_rows set row = 0 while row < max_len begin set ascii_row = row + 1 set japanese_cells = call getchildren set ascii_cells = call getchildren comment First column is sound files pop japanese_cells 0 pop ascii_cells...
def parse_table(japanese_rows, character_map, insert_key, basic_class): max_len = len(japanese_rows) row = 0 while row < max_len: ascii_row = row + 1 japanese_cells = japanese_rows[row].getchildren() ascii_cells = japanese_rows[ascii_row].getchildren() # First column is sou...
Python
nomic_cornstack_python_v1
function add_set_membership self values column_name begin string Append a set membership test, creating a query of the form 'WHERE name IN (?,?...?)'. :param values: A list of values, or a subclass of basestring. If this is non-None and non-empty this will add a set membership test to the state. If the supplied value i...
def add_set_membership(self, values, column_name): """ Append a set membership test, creating a query of the form 'WHERE name IN (?,?...?)'. :param values: A list of values, or a subclass of basestring. If this is non-None and non-empty this will add a set membership tes...
Python
jtatman_500k
comment Working with lists comment Helpful links: comment - https://docs.python.org/3/library/functions.html comment - https://docs.python.org/3/library/numeric.html set names_of_planets = list string Mercury string Venus string Earth string Mars string Saturn string Jupiter string Uranus string Neptune comment Write c...
# Working with lists # Helpful links: # - https://docs.python.org/3/library/functions.html # - https://docs.python.org/3/library/numeric.html names_of_planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Saturn', 'Jupiter', 'Uranus', 'Neptune'] # Write code that will display answers to the following questions: # -------...
Python
zaydzuhri_stack_edu_python
function test_instantiation self begin set tag = call blend string multilingual_tags.TagTranslation assert true pk end function
def test_instantiation(self): tag = mixer.blend('multilingual_tags.TagTranslation') self.assertTrue(tag.pk)
Python
nomic_cornstack_python_v1
function _get_random_article begin try begin set title = random 1 debug string Trying %s % title set article = call page title set sentence_list = call _smart_tokenize content set local = call Article title=call unicode title revision_id=revision_id sentence_list=sentence_list comment save only long articles if length ...
def _get_random_article(): try: title = wikipedia.random(1) logger.debug('Trying %s' % title) article = wikipedia.page(title) sentence_list = _smart_tokenize(article.content) local = Article(title = unicode(article.title), revision_id = artic...
Python
nomic_cornstack_python_v1
function ghchance x begin assert x % 100 == 0 return string %d%% % x // 100 end function
def ghchance(x: int) -> str: assert x % 100 == 0 return '%d%%' % (x // 100)
Python
nomic_cornstack_python_v1
function waveCorSlice1D_LC_CL dataSlc waveSlc waveGridProps=none sigSlices=false begin comment get spatial grid properties if not provided if waveGridProps is not none begin set minWave = decimal waveGridProps at 0 set maxWave = decimal waveGridProps at 1 set nWave = decimal waveGridProps at 2 end else begin set nWave ...
def waveCorSlice1D_LC_CL(dataSlc, waveSlc, waveGridProps=None,sigSlices=False): #get spatial grid properties if not provided if (waveGridProps is not None): minWave = float(waveGridProps[0]) maxWave = float(waveGridProps[1]) nWave = float(waveGridProps[2]) else: nWave = ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import random import pdb function display_list li begin comment clear the screen print string * 10 for value in li begin print string ** * value end comment pause untill the user hits enter input string **=>HIT enter end function function bubblesort li begin string sorts l in place and re...
# -*- coding: utf-8 -*- import random import pdb def display_list(li): #clear the screen print("\n"*10) for value in li: print("**"*value) #pause untill the user hits enter input("**=>HIT enter") def bubblesort(li): "sorts l in place and return it" for passesleft in range(len(li...
Python
zaydzuhri_stack_edu_python
import pandas set data = read csv string weather_data.csv comment print(type(data)) comment print(data) comment print(data['temp']) set data_dict = call to_dict comment print(data_dict) comment print('') set temp_list = call to_list comment print(temp_list) comment print(len(temp_list)) comment Average temp set total =...
import pandas data = pandas.read_csv('weather_data.csv') # print(type(data)) # print(data) # print(data['temp']) data_dict = data.to_dict() # print(data_dict) # print('') temp_list = data['temp'].to_list() # print(temp_list) # print(len(temp_list)) # Average temp total = 0 for deg in temp_list: total += deg av...
Python
zaydzuhri_stack_edu_python