id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3292635 | from smiler.instrumenting.apkil.insnnode import InsnNode
constructor_ins1 = InsnNode(r"invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V")
constructor_ins2 = InsnNode("return-void")
default_constructor_insns = [constructor_ins1, constructor_ins2]
ret_obj_ins1 = InsnNode(r"const/4 v0, 0x0")
ret_obj_ins2 = ... | StarcoderdataPython |
3319998 | <filename>dftd3/dftd3.py
#!/usr/bin/python
from __future__ import print_function, absolute_import
# THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT ... | StarcoderdataPython |
3317354 | import matplotlib.pyplot as plt
from pyutils import *
path = '/home/r/Downloads/interbank20.zip'
path2 = '/home/r/Downloads/intro-ml-project-main.zip'
path3 = '/home/r/Downloads/house-prices-advanced-regression-techniques'
read_data('/home/r/Downloads/house-prices-advanced-regression-techniques/train.csv')
csvs = [... | StarcoderdataPython |
118730 | from bolinette.core.models.model import Model, ModelMetadata, ModelProperty
from bolinette.core.models.attributes import Column, ColumnList, Backref, Reference, Relationship
| StarcoderdataPython |
2912 | from flask import Blueprint
from flask_restful import Api
# from restful import Api
from resources.Hello import CategoryResource
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
# Route
api.add_resource(CategoryResource, '/Hello') | StarcoderdataPython |
1747952 | <filename>credential_gen.py
import log
import random
# 447,856 words
log.info("Loading dictionary...")
dictionary_file = open('dictionary.txt', 'r')
dictionary = dictionary_file.read().split('\n')
log.good("Loaded!")
def gen_credentials():
username = f'{dictionary[random.randint(0, 447856)]}{random.randint(100, ... | StarcoderdataPython |
8073 | <reponame>rajeshkumargp/TextBlob
from __future__ import unicode_literals
import unittest
from nose.tools import * # PEP8 asserts
from nose.plugins.attrib import attr
from textblob.sentiments import PatternAnalyzer, NaiveBayesAnalyzer, DISCRETE, CONTINUOUS
class TestPatternSentiment(unittest.TestCase):
def setU... | StarcoderdataPython |
164978 | from openapi_schema_generator import OpenApiSchemaGenerator
from compare_objects import compare_objects
import json
import yaml
# **************** Globals ***************** #
base_path = "test/Examples"
def get_expected_and_gen(file_name, file_type='json'):
src_path = f"{base_path}/src/{file_name}.{file_type}"
... | StarcoderdataPython |
4350 | <reponame>hongsemy/InstagramWithDjango
from django.db import models
from djangostagram.users import models as user_model
# Create your models here.
# This class is used in other models as an inheritance.
# An often-used pattern
class TimeStamedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=T... | StarcoderdataPython |
67649 | # Copyright 2017 Mycroft AI 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | StarcoderdataPython |
3252239 | from __future__ import print_function
import argparse
import brain
import h5py
import math
import numpy
import sys
def compute_frames_per_block(cells_to_frames_ratio, report, block_values,
gids=None):
# The number of frames per block is fixed using the median number of
# compartm... | StarcoderdataPython |
1777147 | from django.conf.urls import url
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^$',views.index, name='index'),
url(r'^search/',views.search_results, name='search_results'),
url(r'^project/(?P<project_id>(\d+)) ',views.rateProject, name... | StarcoderdataPython |
3343478 |
from model_indexer import (TxtPreprocess,
KeyWordCountFrequency)
from database_agent import URLTable
from concurrent.futures import ThreadPoolExecutor
import pickle, collections, os
from tqdm import tqdm
import config
# trie tree as index and to storage for keyword
class TrieNodeDB:
def ... | StarcoderdataPython |
1667082 | <gh_stars>1-10
import argparse
import inspect
import struct
parser = argparse.ArgumentParser(description='Decompile ELF executable')
parser.add_argument('exe', help='ELF executable to decompile')
args = parser.parse_args()
def _get_field(fields, bytes, elf):
calling_method_name = inspect.stack()[2][3]
field ... | StarcoderdataPython |
3316674 | <reponame>francois2metz/Python-piwik<gh_stars>1-10
# -*- coding: utf-8 -*-
from django.template import Node, Library
from django.conf import settings
register = Library()
def piwik_json_tables(data, metadata = None):
"""
>>> settings.PIWIK_URL = 'http://example.com/'
>>> piwik_json_tables({}, [{'metrics':... | StarcoderdataPython |
181644 | import os
import sys
import importlib.util
import pdb
import time
import random
import re
from copy import deepcopy
import numpy as np
from functools import reduce
from collections import defaultdict
import arrow
import scipy
from scipy.cluster.vq import *
from scipy.cluster.hierarchy import linkage, dendrogram
import... | StarcoderdataPython |
1762737 | <reponame>MatejKastak/cemu<gh_stars>0
import os
PROGNAME = 'cemu'
AUTHOR = 'hugsy'
EMAIL = '<EMAIL>'
VERSION = '0.3'
URL = 'https://github.com/{}/{}'.format(AUTHOR, PROGNAME)
ISSUES = 'https://github.com/{}/{}/issues'.format(AUTHOR, PROGNA... | StarcoderdataPython |
76770 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# flake8: noqa
"""The KlustaSuite: automatic spike sorting up to 64 channels."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import logging
import os... | StarcoderdataPython |
1675833 | """
Helper Methods
Author: Austin Transportation Department, Data and Technology Services
Description: The purpose of this script is to provide any methods that
assist any script associated to this application.
"""
import sys
import glob
import csv
import io
import json
import re
import datetime
from dateutil import ... | StarcoderdataPython |
166219 | <filename>11-funcoes/11-funcoes.py
# Código utilizado no livro Aprenda Python Básico - Rápido e Fácil de entender, de <NAME>
# Mais informações sobre o livro: http://felipegalvao.com.br/livros
# Capítulo 11: Funções
# Definição de função sem parâmetros e sem valor de retorno
def print_ola_tres_vezes():
print("Ola P... | StarcoderdataPython |
1690240 | # -*- coding: utf-8 -*-
#
from datetime import datetime
import sys
import pathlib
import numpy as np
import math
from numpy.core.defchararray import center
# このソースのあるディレクトリの絶対パスを取得
current_dir = pathlib.Path(__file__).resolve().parent
# モジュールのあるパスを追加
sys.path.append(str(current_dir) + '/../')
sys.path.append(str(curren... | StarcoderdataPython |
81515 | <gh_stars>0
height = int(input())
for i in range(1, height + 1):
for j in range(1, height + 1):
if(i == 1 or i == height or j == 1 or j == height):
print(1,end=" ")
else:
print(0,end=" ")
print()
# Sample Input :- 5
# Output :-
# 1 1 1 1 1
# 1 0 0 0... | StarcoderdataPython |
3206272 | # Copyright (C) 2013 Sony Mobile Communications AB.
# All rights, including trade secret rights, reserved.
import os
import sys
import ave.cmd
from ave.workspace import Workspace
# show help and return non-zero when invoked without arguments
def t1(executable, sources):
pretty = '%s t1' % __file__
print(pre... | StarcoderdataPython |
1742972 | <filename>visual_dynamics/utils/iter_util.py<gh_stars>10-100
def flatten_tree(tree, base_type=str):
if isinstance(tree, base_type):
return [tree]
else:
return sum([flatten_tree(child, base_type=base_type) for child in tree], [])
def unflatten_tree(tree, flat_list, base_type=str, copy_list=Tr... | StarcoderdataPython |
74130 | <gh_stars>0
# -*- coding: utf-8 -*-
"""Python wrapper for command line
"""
import os
import subprocess
from biobb_common.tools import file_utils as fu
import typing
import logging
class CmdWrapper:
"""Command line wrapper using subprocess library
"""
def __init__(self, cmd: typing.Iterable[str], out_log:... | StarcoderdataPython |
3392622 | #!/usr/bin/env python3
"""
Error Analysis Module
"""
import numpy as np
def precision(confusion):
"""
Calculates the precision for each class in a confusion matrix
confusion is a confusion numpy.ndarray of shape (classes, classes) where
row indices represent the correct labels and column indices repr... | StarcoderdataPython |
1672874 | <filename>tables/file.py
"""Create PyTables files and the object tree.
This module support importing generic HDF5 files, on top of which
PyTables files are created, read or extended. If a file exists, an
object tree mirroring their hierarchical structure is created in memory.
File class offer methods to traverse the t... | StarcoderdataPython |
1635350 | <filename>downloaders/question_data/question_data_downloader.py
import requests
import pathlib
import json
import time
import sys
CURRENT_FILE_PATH = pathlib.Path(__file__).absolute()
# Adding parent directory to path in order to import from the added directories
sys.path.append(str(CURRENT_FILE_PATH.parent.parent))
... | StarcoderdataPython |
127248 | <filename>classes/results.py
from collections import defaultdict
from classes.color import Color
class Results(object):
def __init__(self):
self.width = None
self.color = Color()
self.results = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
# ^Category ^Plugin ... | StarcoderdataPython |
1656466 | <gh_stars>0
from stupendous_cow.importer.spreadsheets import *
import inspect
import os.path
import unittest
resource_dir = None
class WorkbookTests(unittest.TestCase):
def test_load_rworkbook(self):
workbook = Workbook(os.path.join(resource_dir, 'test_ss.ods'))
self.assertEqual(2, workbook.num_sh... | StarcoderdataPython |
1696540 | import json
from datetime import datetime
class ValidationError(Exception):
"""The message could not be validated"""
pass
class Message:
def __init__(self,
key: str,
data,
payloadType: str,
timestamp: datetime = datetime.utcnow(),
... | StarcoderdataPython |
130750 | <gh_stars>1-10
import datetime
import json
import vk
import operator
import matplotlib.pyplot as plt
import os
import gensim
import gensim.corpora as corpora
import pyLDAvis
import nltk
from nltk.corpus import stopwords
import pyLDAvis.gensim
import pymorphy2
from wordcloud import WordCloud
import numpy as np
import op... | StarcoderdataPython |
3379186 | <reponame>robotics-at-maryland/qubo<filename>src/autonomy/src/service_test.py<gh_stars>10-100
import ram_msgs.srv
import rospy
buoy_detect = rospy.ServiceProxy('buoy_detect', ram_msgs.srv.bool_bool)
print "here"
print buoy_detect(1)
| StarcoderdataPython |
126570 | <filename>Courses/Python_4_Everyone/Lesson_12/request-response.py
import socket
import re
url_name = input("Enter url: ")
if len(url_name) < 1 :
url_name = "http://data.pr4e.org/intro-short.txt"
host = re.findall('(?<=://)[\w-]+(?:\.[\w-]+)+', url_name)
opensock = socket.socket(socket.AF_INET, socket.SOCK_STREA... | StarcoderdataPython |
1606549 | <filename>collectionPointEvent.py
"""
Common event to send out about activity from this collection point
author: DaViD bEnGe
date: 6/9/2017
TODO: define this object better
"""
import datetime
class CollectionPointEvent():
def __init__(self, cpid, cptype, topic, extendedData={}, localOnly=False):
self._cp... | StarcoderdataPython |
170160 | <reponame>UtkarshPathrabe/Competitive-Coding
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummyHead = ListNode(float('-inf'), hea... | StarcoderdataPython |
154719 | """Non-core-specific tests for cachier."""
import os
from cachier.core import (
MAX_WORKERS_ENVAR_NAME,
DEFAULT_MAX_WORKERS,
_max_workers,
_set_max_workers,
_get_executor
)
def test_max_workers():
"""Just call this function for coverage."""
try:
del os.environ[MAX_WORKERS_ENVAR_N... | StarcoderdataPython |
3215610 | # Non-local block using embedded gaussian
# Code from
# https://github.com/AlexHex7/Non-local_pytorch/blob/master/Non-Local_pytorch_0.3.1/lib/non_local_embedded_gaussian.py
import torch
from torch import nn
from torch.nn import functional as F
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, int... | StarcoderdataPython |
110037 | import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# this list of stopwords is a merge of multiple lists found in the web
stops = set(['[closed]', '[duplicate]', 'i', 'me', 'sometime', 'been',
'mostly', 'don\'t', 'don', 'hasnt', 'couldn\'t', 'couldn', '\'t',
't', 'don', 'your'... | StarcoderdataPython |
1751515 | import gzip
import json
import base64
import logging
from datetime import datetime
import re
from typing import Any
import boto3
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ec2_resource = boto3.resource('ec2', region_name='us-west-2')
table = boto3.resource('dynamodb', region_... | StarcoderdataPython |
1695460 | import math
from sys import argv
from sqlalchemy import create_engine, Column, Integer, ARRAY, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Result(Base):
__tablename__ = 'result'
id = Column('id', Integer, primary_k... | StarcoderdataPython |
3250342 | from collections import deque
class Solution:
#Function to return list containing vertices in Topological order.
def topoSort(self, V, adj):
# Code here
Q=deque()
d={} # Dictionary to hold indegree of each node
res=[]
for i in range(V):
d[i]=0 #Initia... | StarcoderdataPython |
3326587 | <gh_stars>0
"""Python project setup."""
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with open(os.path.join(here, 'README.md')) as f:
long_description = f.read()
setup(
name='tttimer',
version=os.ge... | StarcoderdataPython |
1698063 | from . import reader, shared, writer # noqa
| StarcoderdataPython |
135625 | from pak.datasets.Dataset import Dataset
import numpy as np
import zipfile
import tarfile
import urllib.request
import shutil
from os import makedirs, listdir
from os.path import join, isfile, isdir, exists, splitext
from scipy.ndimage import imread
from scipy.misc import imresize
from scipy.io import loadmat
from skim... | StarcoderdataPython |
67134 | <filename>G4 Localizer/a2_Camera/cameraModel.py<gh_stars>0
class Camera:
def __init__(): #Need to have all information necessary to calibrate camera input into here as arguements
#Calibrate Camera - constant
#Locate Camera Relative to Centerpoint - constant
#Define GPIO pins for synchronizat... | StarcoderdataPython |
88061 | <reponame>leVirve/GooTool
import logging
from gootool.drive import *
logger = logging.getLogger('gootool')
logger.setLevel(logging.WARNING)
fh = logging.FileHandler('gootool.log', encoding='utf8')
ch = logging.StreamHandler()
fh.setLevel(logging.DEBUG)
ch.setLevel(logging.WARNING)
formatter = logging.Formatter('%(... | StarcoderdataPython |
51490 | import math
from pandas_util import values_of, subset_by_value
def entropy(samples, bins=None):
"""
Compute entropy of given set of sample data points
Parameters:
samples - Pandas DataFrame; last column is taken as the class labels
Keyword Args:
bins - Number of bins/quantiles to have for co... | StarcoderdataPython |
85982 | <reponame>microsoft/Dynamics365-CustomerInsights-Client-Libraries<gh_stars>0
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# ----... | StarcoderdataPython |
1615891 | # A string is a palindrome if it is identical forward and backward.
# For example “anna”, “civic”, “level” and “hannah” are all examples of palindromic words.
# Write a program that reads a string from the user and uses a loop to determines whether or not it is a
# palindrome. Display the result, including a meaningful... | StarcoderdataPython |
1613527 | <gh_stars>0
from dataclasses import dataclass
from dataclasses import field
@dataclass
class EventLookup:
lookup: dict = field(default_factory=dict)
@dataclass
class Manifest:
car: list[str]
state: list[str]
session: list[str]
@dataclass
class EventInfo:
name: str
description: field(init=Fa... | StarcoderdataPython |
59160 | <gh_stars>100-1000
# Generated by Django 2.2 on 2019-05-02 17:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('openbook_posts', '0030_post_is_closed'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
1714967 | <filename>sharing_is_caring/main_content/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import DetailView, CreateView, UpdateView, DeleteView
from core.mixins import BootstrapFormViewMixin
from sharing_is_caring.main_content.forms impor... | StarcoderdataPython |
1797515 | import math
from .searcher import Searcher
from pychemia import pcm_log
class ParticleSwarm(Searcher):
def __init__(self, population, params=None, generation_size=32, stabilization_limit=10):
"""
Implementation fo the Firefly algorithm for global minimization
This searcher uses a metric t... | StarcoderdataPython |
23005 | from .FictionBook2 import FictionBook2
from .Author import Author
from .TitleInfo import TitleInfo
from .DocumentInfo import DocumentInfo
| StarcoderdataPython |
102156 | # -*- coding: utf8 -*-
import json
import os
import requests
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
class FreeMobileSMS(object):
def __init__(self, config=None):
self._URL = "https://smsapi.free-mobile.fr/sendmsg?user={0}&pass={1}&msg={2}"
self._c... | StarcoderdataPython |
3246009 | <filename>facepad-test.py<gh_stars>1-10
# Copyright 2018
#
# <NAME>, <NAME>, <NAME>, Michigan State University
#
# All Rights Reserved.
#
# This research is based upon work supported by the Office of the Director of
# National Intelligence (ODNI), Intelligence Advanced Research Projects Activity
# (IARPA), via IARP... | StarcoderdataPython |
3344157 | import sqlite3
from tkinter import *
from tkinter import messagebox
newWindow = Tk()
newWindow.title("Inventory System")
newWindow.geometry("800x750")
B1=Button(newWindow,text="Clothing")
B2=Button(newWindow,text="Electronic Appliances")
newWindow.mainloop()
| StarcoderdataPython |
1723544 | import torch
import torch.nn as nn
import torch.nn.functional as F
def _neg_loss(outputs: torch.Tensor, targets: torch.Tensor):
"""
Modified focal loss. Exactly the same as CornerNet.
Runs faster and costs a little bit more memory
Arguments:
outputs (torch.Tensor): BATCH x C x H x W
... | StarcoderdataPython |
1792415 | <reponame>sowmyamanojna/BT3051-Data-Structures-and-Algorithms
def bubble_sort(a):
n = len(a)
for i in range(n-1):
sort = False
for j in range(n-i-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
sort = True
for k in a:
print(k, end = " ")
print ()
if not sort:
break
return a
def sele... | StarcoderdataPython |
3340265 | min = None
max = None
while True:
try:
num = input('Enter numbers: ')
if num == 'done':
break
else:
num1 = float(num)
if min is None or num1 < min:
min = num1
if max is None or num1 > max:
... | StarcoderdataPython |
3316659 | <gh_stars>0
from fastapi import APIRouter
router = APIRouter(prefix="/validators", tags=["validators"])
# Assign a license to a product
# Get all validators
# Update the validator
# Delete the validator if nothing assigned to it | StarcoderdataPython |
1638191 | <reponame>apurvnakade/2021-advent-of-code
import numpy as np
with open("./input.txt") as f:
raw_input = [line.strip().split(" -> ") for line in f.readlines()]
start_coordinates = [(0,0)] * len(raw_input)
end_coordinates = [(0, 0)] * len(raw_input)
directions = ['n'] * len(raw_input)
grid = np.zeros((1000, 1000))
c... | StarcoderdataPython |
19360 | <gh_stars>1-10
from lib_combination.aws_client.aws_client import get_session_for_profile, run_job, get_job, create_job
from lib_combination.aws_client.aws_client import upload_file_to_s3_bucket
from lib_combination.conf_utils.conf_utils import get_job_name, get_profile_name, get_bucket_name, get_database_name
from lib_... | StarcoderdataPython |
1678784 | <reponame>n3nc/wild-cli
from wb.api.wildebeest_api import WildebeestApi
| StarcoderdataPython |
163083 | '''
utilities for post test
'''
from django.test import TestCase
from django.contrib.auth.models import User
from ...organizations.models import Organization
from ..models import Post
'''
Utility classes for testing
'''
from django.test import TestCase
from django.contrib.auth.models import User
from ...posts.mo... | StarcoderdataPython |
3310400 | import praw
import pickle
import os
CLIENT_ID = ''
CLIENT_SECRET = ''
USERNAME = ''
PASSWORD = ''
USERAGENT = ''
class CmvRow:
def __init__(self):
self.id = None
self.title = None
self.url = None
self.view = None
self.num_comments = 0
self.num_counters = 0 # top le... | StarcoderdataPython |
3224775 | <filename>Bio/GA/Crossover/TwoPoint.py
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Perform two-point crossovers between the genomes of two organisms.
This module performs two-point crossove... | StarcoderdataPython |
51793 | # -*- coding: utf-8 -*-
import os, sys
from ..util.log import debug, print_tb
from ..util import filesystem
from ..util.string import decode_string
if sys.version_info < (3, 0):
from .bencode import BTFailure as BTError
from .bencode import bdecode, bencode
else:
from .bencodepy import BencodeDecodeError as BTErr... | StarcoderdataPython |
1715842 | <filename>weatherApp/weather/urls.py
from django.urls import path
from . import views
app_name = 'weather'
urlpatterns = [
path('weather', views.WeatherAppView.as_view()),
] | StarcoderdataPython |
1684099 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 17:03:45 2021
@author: shangfr
"""
from .simwords import search, anns
__all__ = (
search, anns
)
| StarcoderdataPython |
1791030 | """twitchvod __init__.py"""
from .client import Client
| StarcoderdataPython |
3291418 | <filename>tuw_dynamixel_controller/src/tuw_dynamixel_controller/exception/invalid_config_exception.py
#!/usr/bin/env python3
class InvalidConfigException(Exception):
pass
| StarcoderdataPython |
164829 | # 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | StarcoderdataPython |
3301707 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("restaurant", "0001_initial")]
operations = [
migrations.AlterField(
model_name="table", name="number", field=models.CharField(max_length=60)
)
]
| StarcoderdataPython |
183479 | import os
import sys
import ida_kernwin
import ida_diskio
import ida_bytes
import ida_segment
import ida_idaapi
import ida_nalt
import ida_idp
from PyQt5.QtWidgets import (QWidget, QApplication, QCheckBox, QLabel,
QComboBox, QSizePolicy, QVBoxLayout, QHBoxLayout)
from PyQt5.QtGui import (QPainter, QC... | StarcoderdataPython |
59792 | import lib1.mod1
def f(x):
return lib1.mod1.k(x)(42) | StarcoderdataPython |
3324033 | from django.db import models
class TimestampedModel(models.Model):
"""
This class abstracts the models for timestamps
The timestamps will be inherited in user model and profile model
"""
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
... | StarcoderdataPython |
1638427 | # To prepare his students for an upcoming game, the sports coach
# decides to try some new training drills. To begin with, he
# lines them up and starts with the following warm-up exercise:
# when the coach says 'L', he instructs the students to turn to
# the left. Alternatively, when he says 'R', they should turn to... | StarcoderdataPython |
3215861 | <reponame>Flax-Network/flax-light-wallet<gh_stars>1-10
from dataclasses import dataclass
from typing import Optional
from flaxlight.types.blockchain_format.sized_bytes import bytes32
from flaxlight.types.blockchain_format.program import Program
from flaxlight.util.ints import uint64
from flaxlight.util.streamable impo... | StarcoderdataPython |
1787157 | from flask import render_template
from flask.views import View
class GraphiQLView(View):
template_name = 'graphiql.html'
default_query = None
methods = ['GET']
def __init__(self, **kwargs):
super(GraphiQLView, self).__init__()
for key, value in kwargs.items():
if hasattr(s... | StarcoderdataPython |
1680700 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AntfortuneContentCommunityHoteventListQueryResponse(AlipayResponse):
def __init__(self):
super(AntfortuneContentCommunityHoteventListQueryResponse, self).__init... | StarcoderdataPython |
3288467 | <filename>articleparser/db.py
from typing import *
import pugsql
from datetime import datetime
from uuid import UUID
import json
def module(module_path):
return pugsql.module("queries")
def to_uuid(u: str = None, default=None) -> UUID:
if u is None:
return default
else:
return UUID(u)
... | StarcoderdataPython |
173756 | <filename>roiCLS/gen_fea_label.py
# -*- coding: utf-8 -*-
import os, sys
import argparse
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from scipy.io import savemat
from pydaily import format
from utils import load_fea_target, label2Onehot
def set_args():
parser = argparse.ArgumentParser(des... | StarcoderdataPython |
1735857 | <reponame>finnhaedicke/metaSMT<gh_stars>10-100
#!/usr/bin/python
import sys
import unittest
sys.path.insert( 0, sys.path[0] + '/..' )
from metasmt.core import *
from metasmt.operators import *
from metasmt.support import *
class SupportTest( object ):
def testOneHot( self ):
vars = new_variables( 10 )
... | StarcoderdataPython |
153526 | <gh_stars>0
from torrent9explorer import Torrent9Item, Utils
import re
class Regexer():
CACHE = {}
@staticmethod
def createItemFromHtml(html):
list = []
regex = r"\<tr\>[ \t\n]*\<td\>\<i\sclass=\"fa\sfa-(.*?)\"\sstyle=\".*?\"\>\<\/i\>[ \t\n]*\<a title=\".*?\"\shref=\"(.*?)\".*?\>(.*?)\<... | StarcoderdataPython |
3369722 | <gh_stars>0
from itertools import cycle, compress
from sklearn import preprocessing
from sklearn import neighbors
from metric_learn import LMNN
from multiprocessing import Pool
class geolearn:
def __init__(self, model):
self.model = model
def fit(self,feature,label):
model.fit(feature, labe... | StarcoderdataPython |
86663 | import gym
class MakespanRewardWrapper(gym.RewardWrapper):
"""
Return the time needed to complete all jobs.
"""
def __init__(self, env):
super().__init__(env)
self._settings = env._settings
def reward(self, reward):
return [-r['makespan'] for r in reward] | StarcoderdataPython |
1655143 | <filename>app/template_extensions.py
from app import app, user_manager
import app.utils as utils
from app.controllers import project_controller
from flask_user import current_user
@app.context_processor
def user_manager():
return dict(user_manager=user_manager)
@app.context_processor
def is_logged_in():
re... | StarcoderdataPython |
1605007 | <filename>qal/dal/tests/test_dal.py
"""
Created on May 20, 2010
@author: <NAME>
"""
import unittest
from qal.dal.types import DB_MYSQL, DB_POSTGRESQL, DB_ORACLE, DB_DB2, DB_SQLSERVER
from qal.dal.tests.framework import get_default_dal
def _connect_test(_db_type):
dal = get_default_dal(_db_type, "")
if dal:
... | StarcoderdataPython |
1687255 | import socket
from . import base
from wildfly.api.deployment import DEFAULT_SERVER_GROUP
class HostTest(base.BaseTestCase):
def test_list_hosts(self):
hosts = self.client.hosts()
self.assertIn(socket.gethostbyname(base.WILDFLY_CONTAINER_NAME), hosts)
def test_list_hosts_in_group(self):
... | StarcoderdataPython |
3386584 | # pylint: disable=useless-import-alias
from .exceptions import InvalidConfigError as InvalidConfigError
from .exceptions import MissingConfigError as MissingConfigError
from .exceptions import MissingSignerError as MissingSignerError
from .jwt import JWT as JWT
from .jwt import AuthData as AuthData
from .manager import... | StarcoderdataPython |
3218759 | <filename>test/unittest/datafinder_test/core/configuration/icons/icon_test.py
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#mod... | StarcoderdataPython |
3389385 | # -*- coding: utf-8 -*-
# from _typeshed import Self
from elasticsearch import Elasticsearch
import json
class ElasticsearchHandler:
def __init__(self, host='localhost', port=9200, index="hoge", doctype="fuga", setting=json, mapping=json):
self._setting = setting
self._mapping = mapping
self._index = ind... | StarcoderdataPython |
4817048 | #!/usr/bin/env python3
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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 License at
#
# ... | StarcoderdataPython |
99987 | <reponame>melzareix/jit-regex<filename>benchmark/scripts/scrape.py
from email.mime import base
import sys
import time
import requests
import base64
from textops import *
import re
import requests_cache
from typing import List
requests_cache.install_cache("demo_cache", backend="filesystem")
# if __name__ == "__main__"... | StarcoderdataPython |
3306366 | # Generated by Django 2.2.4 on 2019-08-19 18:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('evento', '0006_remove_agenda_arquivo'),
]
operations = [
migrations.AlterField(
model_name='agenda',
name='nome_pale... | StarcoderdataPython |
124921 | <filename>aws_controller/SetUpNewUser/lambda_function.py
import json
from DatabaseDAO import DatabaseDAO, dao
from JSONEncoder import JSONEncoder
count = -1
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy... | StarcoderdataPython |
1680504 | <reponame>rousik/pudl
"""Routines used for extracting the raw FERC 714 data."""
import logging
import pathlib
import zipfile
import pandas as pd
import pudl.constants as pc
logger = logging.getLogger(__name__)
TABLE_FNAME = {
"id_certification_ferc714": "Part 1 Schedule 1 - Identification Certification.csv",
... | StarcoderdataPython |
4833361 | from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
def send_email(request, details, token, subject):
current_site = get_current_site(request)
verification_l... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.