id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
43337 | import tensorflow as tf
if __name__ == "__main__":
with tf.Session() as sess:
game_dir = "Gobang"
model_dir = "model2_10_10_5"
batch = "11000"
# 初始化变量
sess.run(tf.global_variables_initializer())
# 获取最新的checkpoint,其实就是解析了checkpoint文件
latest_ckpt = tf.train.... | StarcoderdataPython |
3373577 | <filename>src/generator.py
import torch
import torch.nn as nn
import torch.nn.functional as F
# Base Class for Generator CNN
class Generator(nn.Module):
def __init__(self, z_size, conv_dim):
super(Generator, self).__init__()
self.conv_dim = conv_dim
self.t_conv1 = nn.ConvTransp... | StarcoderdataPython |
109062 | # Generated by Django 3.0.6 on 2020-05-23 10:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('photos', '0002_auto_20200523_1317'),
]
operations = [
migrations.AlterModelOptions(
name='image',
options={},
),
... | StarcoderdataPython |
1774946 | <reponame>yarenty/mindsdb
import gunicorn.app.base
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key,... | StarcoderdataPython |
1669836 | from random import randint
vitorias = 0
print("Vamos jogar um jogo!")
while True:
while True:
jogador = int(input("Escolha um número: ").strip())
if jogador in range(0, 11):
break
computador = randint(0, 10)
while True:
escolha = str(input("Você quer par (P) ou ímpar (I)?... | StarcoderdataPython |
183480 | """Script that finds faces and blurs using FaceDetection and blurring APIs."""
import argparse
import cv2
import numpy as np
import torch
import kornia as K
from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint
def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -... | StarcoderdataPython |
1645272 | <reponame>jarret/prototype
#!/usr/bin/env python3
# Copyright (c) 2020 <NAME>
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php
import os
import sys
import time
import json
import argparse
import logging
from configparser import Conf... | StarcoderdataPython |
1626150 | from utils import *
from utils import DatasetFolderV12 as DatasetFolder
import numpy as np
from fastprogress import master_bar,progress_bar
import time
import h5py
import os
import argparse
def write_data(data, filename):
f = h5py.File(filename, 'w', libver='latest')
dset = f.create_dataset('array', shape=(... | StarcoderdataPython |
1692177 | # Generated by Django 2.2.6 on 2019-10-10 10:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project_core', '0028_person_physical_person_person_position_small_changes'),
]
operations = [
migrations.Al... | StarcoderdataPython |
4802487 | <filename>tests/bgp_commands_input/bgp_network_test_vector.py
bgp_v4_network = \
"""
BGP table version is 6405, local router ID is 10.1.0.32, vrf id 0
Default local pref 100, local AS 65100
Status codes: s suppressed, d damped, h history, * valid, > best, = multipath,
i internal, r RIB-failure, S Stale,... | StarcoderdataPython |
1651129 | import networkx as nx
def remove(network):
nodes_isolated = []
for node in nx.nodes_iter(network): # find the ndoes without edges
try:
nx.dijkstra_path_length(network, node, 'newcomer')
except:
nodes_isolated.append(node)
network.remove_nodes_from(nodes_isolated) | StarcoderdataPython |
1608819 | <reponame>parasj/contracode<filename>representjs/pretrain_horovod.py
import os
import random
import time
import fire
import numpy as np
import sentencepiece as spm
import torch
import torch.nn.functional as F
import tqdm
import wandb
from loguru import logger
import torch.distributed as dist
import torch.multiprocessi... | StarcoderdataPython |
59587 | import pytest
from os.path import join
from EPPs.common import StepEPP
from tests.test_common import TestCommon, TestEPP, NamedMock
from unittest.mock import Mock, patch, PropertyMock
from scripts.convert_and_dispatch_genotypes import GenotypeConversion, UploadVcfToSamples
class TestGenotypeConversion(TestCommon):
... | StarcoderdataPython |
1696014 | <reponame>likeanaxon/django-polymorphic
from django.contrib import admin
from pexp.models import *
from polymorphic.admin import (
PolymorphicChildModelAdmin,
PolymorphicChildModelFilter,
PolymorphicParentModelAdmin,
)
class ProjectAdmin(PolymorphicParentModelAdmin):
base_model = Project # Can be se... | StarcoderdataPython |
3303588 | from tensorflow.core.framework.attr_value_pb2 import AttrValue
import pytest
@pytest.fixture(scope='session')
def int_list():
return AttrValue.ListValue(i=[1, 2, 3])
@pytest.fixture(scope='session')
def bool_list():
return AttrValue.ListValue(b=[True, False])
| StarcoderdataPython |
3226673 | <gh_stars>1-10
"""
Plugin for Czech TV (Ceska televize).
Following channels are working:
* CT1 - http://www.ceskatelevize.cz/ct1/zive/
* CT2 - http://www.ceskatelevize.cz/ct2/zive/
* CT24 - http://www.ceskatelevize.cz/ct24/
* CT sport - http://www.ceskatelevize.cz/sport/zive-vysilani/
* CT Decko - ... | StarcoderdataPython |
156090 | <reponame>jamesbrobb/dj-stripe
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^djstripe/', include('djstrip... | StarcoderdataPython |
3272429 |
import unittest
from mock import patch
from foundations_core_rest_api_components.v1.controllers.projects_controller import ProjectsController
class TestProjectsController(unittest.TestCase):
@patch('foundations_core_rest_api_components.v1.models.project.Project.all')
def test_index_returns_all_projects(self... | StarcoderdataPython |
282 | <reponame>djaodjin/djaodjin-survey
# Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,... | StarcoderdataPython |
3216457 | <reponame>BerenLuthien/ReAgent<gh_stars>1000+
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from typing import List
from reagent.core.dataclasses import dataclass, field
from reagent.core.parameters import NormalizationData, param_hash
from reagent.models.base import M... | StarcoderdataPython |
3231942 | from enum import Enum
from .follow_trajectory_controller import FollowTrajectoryController
from .manoeuvre_controller import DevelopLaneChangeController
class ActController:
class Mode(Enum):
IDLE = 0
FOLLOW_TRAJECTORY = 1
CHANGE_LANE = 2
def __init__(self):
self.car = Non... | StarcoderdataPython |
3342995 | #!/usr/bin/env python
# coding: utf-8
from xumm.resource import XummResource
class XrplTxResource(XummResource):
@classmethod
def get_url(cls, tx_hash: str) -> str:
"""
Gets the GET url of this XrplTxResource
:param tx_hash: A string contain transaction hash.
:type: str
... | StarcoderdataPython |
1785122 | """
Moodstocks API Client
---------------------
- Copyright (C) 2014 by Moodstocks SAS.
- Licensed under MIT/X11
- See https://moodstocks.com/ for more information.
"""
DEFAULT_EP = "http://api.moodstocks.com/v2"
from requests.auth import HTTPDigestAuth
import requests
import json
import os
import base64
version =... | StarcoderdataPython |
1659516 | # -*- coding: utf-8 -*-
"""
Description: Reads the "metadata.json" file and downloads the subtitle for each title, given a language of preference.
"""
import hashlib
import json
import os
import requests
class SubtitleFinder:
def __init__(
self,
directory=None,
metadata_filename="metada... | StarcoderdataPython |
109276 | import pickle
import operator
import numpy as np
import csv
import os.path
with open ('y_test', 'rb') as f:
y_test=pickle.load(f)
dicvocab={}
f=open("data/vocab.csv")
vocab=csv.reader(f)
for word in vocab:
if word[0]!='':
dicvocab[int(word[0])-1]=word[1]
f.close()
label_size=y_test.shape[1]
topics=["/A... | StarcoderdataPython |
138499 | <reponame>rohit04saluja/genielibs
# Python
import time
import logging
# Unicon
from unicon import Connection
from unicon.eal.dialogs import Dialog, Statement
from unicon.core.errors import (
SubCommandFailure,
StateMachineError,
TimeoutError,
ConnectionError,
)
# Logger
log = logging.getLogger(__name_... | StarcoderdataPython |
1618193 | # RUN: %PYTHON %s | iree-dialects-opt -split-input-file | FileCheck --enable-var-scope --dump-input-filter=all %s
from typing import List
from iree.compiler.dialects.iree_pydm.importer import *
from iree.compiler.dialects.iree_pydm.importer.test_util import *
from iree.compiler.dialects import iree_pydm as d
from ire... | StarcoderdataPython |
1643424 | # User-defined data types can be defined through classes.
class Student:
def __init__(self, name, major, gpa):
self.name = name # Name of the "Student" object is going to be equal to the "name" variable.
self.major = major # Major of the "Student" object is going to be equal to the "major" variabl... | StarcoderdataPython |
1693683 | <reponame>rsdoherty/azure-sdk-for-python
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsof... | StarcoderdataPython |
135011 | def calc_posession(df):
df['Wposs'] = df.apply(lambda row: row.WFGA + 0.475 * row.WFTA + row.WTO - row.WOR, axis=1)
df['Lposs'] = df.apply(lambda row: row.LFGA + 0.475 * row.LFTA + row.LTO - row.LOR, axis=1)
| StarcoderdataPython |
3272356 | import unittest
import pyast as ast
class BaseASTTestCase(unittest.TestCase):
def test_basic_template(self):
class Entity(ast.Node):
_debug = True
id = ast.field(str)
value = ast.field(str)
_template = '<%(id)s %(value)s>'
e = Entity('foo'... | StarcoderdataPython |
1684662 | import jinja2
import os
class SilentUndefined(jinja2.Undefined):
def _fail_with_undefined_error(self, *args, **kwargs):
return None
class Jinja2(object):
def __init__(self, app, **config):
self.app = app
self.root_dir = config.get('root_dir')
self.env = jinja2.Environment(
... | StarcoderdataPython |
3355027 | <filename>clam/config.py
import yaml
# NOTE: This is not a config file
# This is only a helper class for the actual
# config file
class DebugMode:
def __init__(self, mode):
if type(mode) is not int:
raise TypeError("Debug mode must be an int.")
if not 0 <= mode <= 2:
rai... | StarcoderdataPython |
3209607 | <reponame>UWSEDS/homework-2-python-functions-and-modules-czarakas<gh_stars>0
### HW2
### <NAME>
import ReadInData
thisurl = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD'
columnNames_true = ['Date','Fremont Bridge East Sidewalk','Fremont Bridge West Sidewalk']
df = ReadInData.create_datafr... | StarcoderdataPython |
3235266 | """
Implements a network visualization in PyTorch.
WARNING: you SHOULD NOT use ".to()" or ".cuda()" in each implementation block.
"""
# import os
import torch
# import torchvision
# import torchvision.transforms as T
# import random
# import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from a4_hel... | StarcoderdataPython |
99191 | <reponame>sevyharris/autoscience_workflow
# Functions for running a thermo job using this workflow
import pandas as pd
import os
import sys
import glob
import datetime
import time
import subprocess
import job_manager
try:
DFT_DIR = os.environ['DFT_DIR']
except KeyError:
DFT_DIR = '/work/westgroup/harris.se/au... | StarcoderdataPython |
1772484 | from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.forms import ModelForm
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length = 155, unique = ... | StarcoderdataPython |
3231878 | from Student import Student
## std can now be store here
## student object represent below
student1 = Student("Michel", "Computer", 4.5, False)
print(student1.is_on_probation)
| StarcoderdataPython |
1762610 | import re
from w3af.plugins.attack.payloads.base_payload import Payload
from w3af.core.ui.console.tables import table
class ssh_version(Payload):
"""
This payload shows the current SSH Server Version
"""
def api_read(self):
result = {}
result['ssh_version'] = ''
def parse_bina... | StarcoderdataPython |
13391 | <gh_stars>0
from .backend import Backend
from .thread import HttpPool
| StarcoderdataPython |
59087 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/1 13:23
# @Author : Dengsc
# @Site :
# @File : quickstart.py
# @Software: PyCharm
from scrapy import cmdline
cmdline.execute('scrapy crawl lagou'.split())
| StarcoderdataPython |
3234933 | <gh_stars>1-10
"""Default HTTP client selection proxy"""
import os
from .http_common import (
StreamDecodeIteratorSync,
addr_t, auth_t, cookies_t, headers_t, params_t, reqdata_sync_t, timeout_t,
workarounds_t,
)
__all__ = (
"addr_t", "auth_t", "cookies_t", "headers_t", "params_t", "reqdata_sync_t",
"timeout_t"... | StarcoderdataPython |
3250397 | #!/usr/bin/env python
# https://oj.leetcode.com/problems/palindrome-partitioning-ii/
class Solution:
# @param s, a string
# @return an integer
def minCut(self, s):
slen = len(s)
subPalindrome = [[False for i in range(slen)] for j in range(slen)]
cuts = [0] * slen
for i in r... | StarcoderdataPython |
158698 | VALID_TASK_TYPES = {"transcription", "find", "fix", "verify"}
class TaskProfile:
def __init__(self, project=str, task_name=str, task_type=str, priority,
segment_size):
self.project = project
self.task_name = task_name
self.task_type = task_type
self.segment_size = ... | StarcoderdataPython |
4802688 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | StarcoderdataPython |
1704399 | <reponame>amplify-nation/django-ajax<filename>tests/example/tests.py
from django.test import TestCase
from django.contrib.auth.models import User
import json
from .models import Widget
from .endpoints import WidgetEndpoint
class BaseTest(TestCase):
fixtures = ['users.json', 'categories.json', 'widgets.json']
... | StarcoderdataPython |
84471 | <filename>epikjjh/baekjoon/15927.py
import sys
input = lambda: sys.stdin.readline().rstrip()
stream = input()
reverse = stream[::-1]
ans = len(stream) if stream != reverse else (len(stream)-1 if stream[1:]!=reverse[:-1] else -1)
print(ans) | StarcoderdataPython |
117507 | <filename>P3/app/model.py
from pickleshare import *
db=PickleShareDB('miBD')
def checkUser(user):
return user in db
def getUser(user):
if checkUser(user):
return db[user]
return none
def addUser(user,data):
if not checkUser(user):
db[user]=data
def delUser(user):
del db[user]
| StarcoderdataPython |
109560 | <reponame>east301/wsgiuseragentmobile-python3
# -*- coding: utf-8 -*-
from pkg_resources import resource_string
from IPy import IP
from uamobile.cidrdata import crawler, docomo, ezweb, softbank, willcom
__all__ = ['IP', 'get_ip_addrs', 'get_ip']
def get_ip_addrs(carrier):
carrier = carrier.lower()
if carrier... | StarcoderdataPython |
105983 | <filename>code/set-app-package.py
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
#import com.android.provider.Settings
import time, sys
refFile = './logs/passedScreens/ServiceScreen/serviceScreen'
ref_x=0
ref_y=20
ref_w=240
ref_h=380
ACCEPTANCE = 1.0
device = MonkeyRunner.waitForConnection... | StarcoderdataPython |
3222557 | from optimizer import optimizer_SGD, AdaGrad, NormGrad, SGD
import numpy as np
from functions import sigmoid, sigmoid_back, clip_grads
class Loss:
def __init__(self):
self.Loss = None
self.dout = None
def forward(self, out, t):
self.Loss = 1/2 * np.sum((out - t)**2)
... | StarcoderdataPython |
125326 | from flask import request
from flask_restx import Resource, fields, Namespace
import jwt
import datetime
import functools
from models import Users, Admins
import subprocess
import os
from os.path import join, dirname
from dotenv import load_dotenv
from conf import const
load_dotenv(verbose=True)
dotenv_path = join(dir... | StarcoderdataPython |
1773627 | #!/usr/bin/env python
# coding: utf-8
# In[77]:
import pandas as pd
import numpy as np
import requests
from datetime import datetime
from urllib.request import urlopen
from lxml import etree
import io
from alphacast import Alphacast
from dotenv import dotenv_values
API_KEY = dotenv_values(".env").get("API_KEY")
alp... | StarcoderdataPython |
3213389 | <filename>senpy/neyer.py
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import minimize, brute, fmin
from .confidence import (parametric_bootstrap, nonparametric_bootstrap,
delta, contour_walk, increase_bounds,
HomogeneousResult)
from .plotting import plo... | StarcoderdataPython |
1657729 | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2014, Digital Reasoning
#
# 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 require... | StarcoderdataPython |
3310313 | <filename>stable_baselines3/common/maskable/callbacks.py
import os
import numpy as np
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common.vec_env import sync_envs_normalization
from stable_baselines3.common.maskable.evaluation import evaluate_policy
class MaskableEvalCallback(E... | StarcoderdataPython |
137632 | # -*- test-case-name: vumi.transports.smpp.tests.test_smpp -*-
from datetime import datetime
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi import log
from vumi.utils import get_operator_number
from vumi.transports.base import Transport
from vumi.transp... | StarcoderdataPython |
3282856 | <filename>secret.py
# those are imported from secrets.py
clientId = '<KEY>'
clientSecret = 'ba32982d56ad4398834210941df54ccc'
| StarcoderdataPython |
3308665 | <filename>Projects/2/Classes/iotJumpWay.py
############################################################################################
#
# Project: Peter Moss COVID-19 AI Research Project
# Repository: AI-Classification
# Repo Project: COVID-19 Tensorflow DenseNet Classifier
#
# Author: <NAME> (<EMAIL... | StarcoderdataPython |
70338 | <filename>agents/archivist/archivist.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Zoe archivist
# https://github.com/rmed/zoe-archivist
#
# Copyright (c) 2015 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files ... | StarcoderdataPython |
3328184 | <gh_stars>1-10
from .base import Interface
class Betriebsstellen(Interface):
"""Wrapper for Deutsche Bahn's Betriebsstellen API.
Documentation at:
https://developer.deutschebahn.com/store/apis/info?name=BahnPark&version=v1&provider=DBOpenData
"""
def __init__(self, token=None, key=None, sec... | StarcoderdataPython |
78763 | <gh_stars>10-100
import treeano.nodes as tn
from treeano.sandbox.nodes import unbiased_nesterov_momentum as unm
def test_unbiased_nesterov_momentum_node_serialization():
tn.check_serialization(
unm.UnbiasedNesterovMomentumNode("a", tn.IdentityNode("i")))
def test_unbiased_nesterov_momentum_node():
d... | StarcoderdataPython |
142260 | <gh_stars>1-10
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("--in-file")
args = parser.parse_args()
for claim in open(args.in_file):
print(json.loads(claim, encoding='utf8')["claim"])
| StarcoderdataPython |
150017 | <reponame>omnivector-solutions/license-manager
from fastapi import APIRouter
from lm_backend.api.booking import router as router_booking
from lm_backend.api.config import router as router_config
from lm_backend.api.license import router as router_license
api_v1 = APIRouter()
api_v1.include_router(router_license, pref... | StarcoderdataPython |
29950 | #!/usr/bin/env python
from __future__ import unicode_literals
import os
import sys
import tarfile
import shutil
import tempfile
from contextlib import contextmanager
from pymatgen.io.gaussian import GaussianInput, GaussianOutput
from tinydb import TinyDB
@contextmanager
def cd(run_path, cleanup=lambda: True):
... | StarcoderdataPython |
196836 | <reponame>mmore500/hstrat
import random
import unittest
from hstrat import hstrat
random.seed(1)
class TestStratumRetentionDripPlot(unittest.TestCase):
# tests can run independently
_multiprocess_can_split_ = True
def test(self):
for predicate in [
hstrat.StratumRetentionPredicateD... | StarcoderdataPython |
1755016 | <gh_stars>0
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import re
from google.appengine.ext import testbed
import webapp2
import webtest
from handlers import build_failure
from handlers im... | StarcoderdataPython |
146804 | from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import pymel.core as pm
import PySide2.QtCore as QtCore
import PySide2.QtUiTools as QtUiTools
import PySide2.QtWidgets as QtWidgets
class FlottiWindow(QtWidgets.QDialog):
window_title = "FlottiTools Window"
object_name = None
def __init__(se... | StarcoderdataPython |
129709 | <filename>yandex_checkout/domain/models/confirmation/confirmation_class_map.py
from yandex_checkout.domain.common.confirmation_type import ConfirmationType
from yandex_checkout.domain.common.data_context import DataContext
from yandex_checkout.domain.models.confirmation.request.confirmation_embedded import \
Confir... | StarcoderdataPython |
4826264 | <filename>CompetitiveProgramming/CodingBat/Python/WarmUp-1/monkey_trouble.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling.
We are in trouble if they are both smiling or if neither of them is smiling. Return True if ... | StarcoderdataPython |
1706398 | from collections import Counter
from consts import NodeRoles
from tests.base_test import BaseTest
class TestRoleSelection(BaseTest):
def test_automatic_role_assignment(self, api_client, nodes, cluster):
"""Let the system automatically assign all roles in a satisfying environment."""
cluster_id = ... | StarcoderdataPython |
191303 | """
Textko platform for notify component.
For more details about this platform, please refer to the documentation at
https://github.com/textko/hass-notify
"""
# Import dependencies.
import logging
import requests
import json
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassis... | StarcoderdataPython |
3282697 | <gh_stars>1-10
# model parameters
BATCH_SIZE = 32
EPOCHS = 30
TRAIN_SIZE = 0.70
IMAGE_SIZE = 32
| StarcoderdataPython |
3207336 | <reponame>ninanshoulewozaizhe/ShopAccount
from app.database.models import SalesVolumes
from app.database import db
from app.log import logger
def create_new_record(record):
with db.auto_commit_db():
new_sales = SalesVolumes(pid=record['pid'], sid=record['sid'], pname=record['pname'], date=record['date'], s... | StarcoderdataPython |
70201 | import argparse
import torch as t
import torch.nn as nn
import torchvision.transforms as transforms
# from tensorboardX import SummaryWriter
from torch.autograd import Variable
from torch.optim import Adam
from torchvision import datasets
from models import *
if __name__ == "__main__":
parser = argparse.Argumen... | StarcoderdataPython |
4813942 | <reponame>longwangjhu/LeetCode
# https://leetcode.com/problems/kth-smallest-instructions/
# Bob is standing at cell (0, 0), and he wants to reach destination: (row,
# column). He can only travel right and down. You are going to help Bob by
# providing instructions for him to reach destination.
# The instructions are ... | StarcoderdataPython |
1639296 | <filename>gazer/ensembler.py
from __future__ import print_function
import os, sys, time, copy, glob, random, warnings
from operator import itemgetter
import numpy as np
from sklearn.externals import joblib
from tqdm import tqdm_notebook as tqdm
from .metrics import get_scorer
from .sampling import Loguniform
from .c... | StarcoderdataPython |
1660454 | <reponame>lanfis/Spider
#!/usr/bin/env python
# license removed for brevity
import requests
from bs4 import BeautifulSoup
import sys
import os
current_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_folder)
import time
from modules.Facebook_Finder import Facebook_Finder
ff ... | StarcoderdataPython |
18007 | '''
Leetcode problem No 862 Shortest Subarray with Sum at Least K
Solution written by <NAME> on 1 July, 2018
'''
import collections
class Solution(object):
def shortestSubarray(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
n = len(A)
B = [0]... | StarcoderdataPython |
4837416 | import os
import imageio
import numpy as np
import tensorflow as tf
from PIL import Image
from ..utils import facenet
from ..utils import detect_face
# Set allow_pickle=True
np_load_old = np.load
np.load = lambda *a, **k: np_load_old(*a, allow_pickle=True, **k)
class AlignImgDB:
def __init__(self, datadir, outpu... | StarcoderdataPython |
71085 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
class BaseEmitter(object):
'''Base for emitters of the *data-migrator*.
Attributes:
manager (BaseManager): reference to the manager that is calling this
emitter to export objects from that manager
model_class (Model): reference to the ... | StarcoderdataPython |
198791 | from background_task import background
from .models import Post
@background(schedule=10)
def reset_post_upvotes():
posts = Post.objects.all()
for post in posts:
post.amount_of_upvotes = 0
post.save()
| StarcoderdataPython |
3203818 | import numpy as np
class LinearRegressionPy:
pass
class LinearRegressionNp:
def __init__(self, solver="normal_eq"):
self.solver = solver
self.theta = None
self.intercept_ = None
self.coef_ = None
def fit(self, X, y):
if self.solver == "normal_eq":
... | StarcoderdataPython |
124494 | from re import S
from numpy.core.numeric import NaN
import streamlit as st
import pandas as pd
import numpy as np
st.title('world gdp')
@st.cache
def load_data(path):
data = pd.read_csv(path)
data.columns = data.columns.str.lower()
return data
data = load_data("data/gdp.csv")
if st.checkbox('show raw dat... | StarcoderdataPython |
3384826 | <filename>source/utils.py
import os
import copy
import sys
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
import yaml
from source.models impor... | StarcoderdataPython |
115516 | # minqlx - Extends Quake Live's dedicated server with extra functionality and scripting.
# Copyright (C) 2015 Mino <<EMAIL>>
# This file is part of minqlx.
# minqlx is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... | StarcoderdataPython |
103619 | from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.contrib.auth import authenticate, login, logout
from django.conf import settings
from django.db.models import Count,Ma... | StarcoderdataPython |
3210189 | <reponame>vfxetc/sgcache
#from shotgun_api3_registry import connect
#sg = connect()
import os
if False:
from shotgun_api3_registry import connect
sg = connect(use_cache=False)
else:
from tests import Shotgun
url = 'http://127.0.0.1:8010'
sg = Shotgun(url,
os.environ.get('SGCACHE_SHOTGUN_SC... | StarcoderdataPython |
3385040 | <filename>ascension/testrun/anim.py
from ascension.game import Ascension
from ascension.window import MainWindowManager
from ascension.ascsprite import SpriteManager, Sprite, UNIT_GROUP
from math import ceil, floor
from ascension.settings import AscensionConf as conf
BUFFER = (20, 20)
class RepeatCallback(object):
... | StarcoderdataPython |
146641 | <gh_stars>0
import numpy as np
import pandas as pd
import sys
import os
def readcsv(filepath):
if os.name == 'nt':
print (os.getcwd()+ "\\" + filepath)
csvFrame = pd.read_csv(os.getcwd()+ "\\" + filepath)
else:
csvFrame = pd.read_csv(filepath)
print(csvFrame)
print("Success")
if __name__... | StarcoderdataPython |
1798508 | from PyQt5.QtCore import QObject
from PyQt5.QtCore import QByteArray
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtNetwork import QTcpSocket
from PyQt5.QtNetwork import QAbstractSocket
from settings.netSettings import NetSettings
class _OutcomingConnection:
def __init__(self):
self.socketDescriptor = 0
... | StarcoderdataPython |
1672591 | <reponame>TobiasPrt/Smartphoniker-shop<filename>project/tests/conftest.py
# -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import logging
from project.server.config import TestingConfig
import pytest
from webtest import TestApp
from project.server import create_app
from project.server... | StarcoderdataPython |
340 | import FWCore.ParameterSet.Config as cms
#
# module to make the MaxSumPtWMass jet combination
#
findTtSemiLepJetCombMaxSumPtWMass = cms.EDProducer("TtSemiLepJetCombMaxSumPtWMass",
## jet input
jets = cms.InputTag("selectedPatJets"),
## lepton input
leps = cms.InputTag("selectedPatMuons"),
## ma... | StarcoderdataPython |
123584 | <reponame>mkm99/TeamProject_StatsCalculator
# Generate a list of N random numbers with a seed and between a range of numbers - Both Integer and Decimal
from numpy.random import seed
import random
class RandomList():
@staticmethod
def list_Of_Ints(num1, num2, length, theSeed):
if isinstance(num1, float... | StarcoderdataPython |
3373887 | <filename>lucene-experiment/output.py
def output(topic, result, run_id, output_file):
for rank, (docid, score) in enumerate(result.most_common()):
print(topic.num, 0, docid, rank, score, run_id, sep='\t', file=output_file)
| StarcoderdataPython |
3378063 | import bs4
import ClientConstants as CC
import ClientData
import ClientDefaults
import ClientGUICommon
import ClientGUIDialogs
import ClientGUIMenus
import ClientGUIControls
import ClientGUIListBoxes
import ClientGUIListCtrl
import ClientGUIScrolledPanels
import ClientGUISerialisable
import ClientGUITopLevelWindows
imp... | StarcoderdataPython |
4817586 | import random
import datetime
import time
import fcntl
from ip.IPSocket import *
from tcp.TCPPacket import *
def get_ip(ifname='eth0'):
"""
Get ip address of the source, only works for linux machine
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = struct.pack('256s', ifname[:15].enc... | StarcoderdataPython |
3251916 | #!/usr/bin/env python -W ignore
from absl import flags
from absl import app
import pandas as pd
import numpy as np
import sys
from sodapy import Socrata
from os.path import abspath
from os.path import exists
from os import mkdir
FLAGS = flags.FLAGS
# delcare flags
flags.DEFINE_string("token", None, "SPARCS Socrates ... | StarcoderdataPython |
46771 | <reponame>laurabondeholst/Mapping_high_dimensional_data<gh_stars>0
import pandas as pd
import plotly.graph_objects as go
import numpy as np
UMAP_TSNE_FOLDER = "reports_from_tobias/reports/fashion_natural_umap_tsne/"
TSNE_FOLDER = "reports/Noiselevel_experiment_pca_tsne/Fashion/"
TRIMAP_FOLDER = "reports_from_pranjal... | StarcoderdataPython |
3396746 | n1 = int(input('Digite um número qualquer: '))
print(f'A tabuada do número {n1}, é: ')
print('''
{0} * 1 = {1}
{0} * 2 = {2}
{0} * 3 = {3}
{0} * 4 = {4}
{0} * 5 = {5}
{0} * 6 = {6}
{0} * 7 = {7}
{0} * 8 = {8}
{0} * 9 = {9}
'''.format(n1, n1 * 1, n1 * 2, n1 * 3, n1 * 4, n1 * 5, n1 * 6, n1 * 7, n1 * 8, n1 * 9))
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.