id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
6492974 | <filename>attack-defence-challenges/tastyriffs/service/greatest.py
#!/usr/bin/python
import sys
import json
import random
import subprocess
trigger = False
last_rockstar = None
class Rockstar:
def __init__(self, name, age, notes, rockstar_type, rockstar_file):
self.name = name
self.age = age
... | StarcoderdataPython |
125278 | from pathlib import Path
import traceback
from datetime import datetime
from time import time
import fnmatch
from typing import List, Dict
from abc import ABCMeta, abstractmethod
from maggma.core import Store
from maggma.core.drone import Drone, RecordIdentifier, Document
from maggma.utils import Timeout
class Direc... | StarcoderdataPython |
6688806 | <reponame>brongulus/MetaBiLSTM
from collections import defaultdict
import torch
import torch.nn as nn
from torch.nn.functional import dropout
from tqdm import tqdm
class WordPretrainedEmbbedings(nn.Module):
def __init__(self, embeddings):
super().__init__()
self.emb_layer = nn.Embedding.from_pret... | StarcoderdataPython |
3325108 | #!/usr/bin/env python3
import sys
import numpy as np
import os, shutil, zipfile
import pandas as pd
from sklearn import ensemble
from keras.models import Model, load_model
from dataset import PhysionetDatasetCNNInfer
VITALS_COLUMNS = ['HR', 'O2Sat', 'Temp', 'SBP', 'MAP', 'DBP', 'Resp', 'EtCO2']
LAB_COLUMNS = ['BaseEx... | StarcoderdataPython |
6479059 | <reponame>robertsj/poropy
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 ... | StarcoderdataPython |
8196249 | """
================
RAG Thresholding
================
This example constructs a Region Adjacency Graph (RAG) and merges regions
which are similar in color. We construct a RAG and define edges as the
difference in mean color. We then join regions with similar mean color.
"""
from skimage import data, io, segmentation... | StarcoderdataPython |
4802500 | # SPDX-License-Identifier: Apache-2.0
# Copyright 2021 Eotvos Lorand University, Budapest, Hungary
from utils.codegen import format_type, get_all_extern_call_infos
from utils.extern import extern_has_tuple_params
from compiler_common import generate_var_name
from more_itertools import unique_everseen
#[ #include "dpd... | StarcoderdataPython |
37014 | from unittest import TestCase
from parameterized import parameterized
from tests.test_utils import mock_request_handler
from web.web_auth_utils import remove_webpack_suffixes, is_allowed_during_login
class WebpackSuffixesTest(TestCase):
def test_remove_webpack_suffixes_when_css(self):
normalized = remov... | StarcoderdataPython |
3314013 | import importlib
import ctypes
import random
from .Message import Message
# Emmulates the main AUX steering board
class AuxSteering(Message):
def __init__(self, addr_CAN, addr_telem, emulator=None):
super().__init__(addr_CAN, addr_telem)
self.emulator = emulator
self.cplusOn = 0
self... | StarcoderdataPython |
13549 | <reponame>ZJULiHongxin/two-hand-pose-est
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import platform
import numpy as np
import time
import os
import torch
import torch.backends.cudnn as cudnn
import _init_paths
from config import cfg
fro... | StarcoderdataPython |
1925491 | <reponame>ccampo133/cachet-client<filename>tests/test_subscribers.py
import types
from unittest import mock
from base import CachetTestcase
import cachetclient
from fakeapi import FakeHttpClient
@mock.patch('cachetclient.client.HttpClient', new=FakeHttpClient)
class SubscriberTests(CachetTestcase):
def test_cre... | StarcoderdataPython |
11208959 | from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_max_inclusive_2_xsd.nistschema_sv_iv_atomic_integer_max_inclusive_2 import NistschemaSvIvAtomicIntegerMaxInclusive2
__all__ = [
"NistschemaSvIvAtomicIntegerMaxInclusive2",
]
| StarcoderdataPython |
1671273 | from hierarc.Likelihood.SneLikelihood.sne_likelihood import SneLikelihood
import pytest
import numpy as np
class TestSnePantheon(object):
def setup(self):
np.random.seed(42)
# define redshifts
num = 30 # number of Sne
zcmb = np.linspace(start=0.01, stop=0.8, num=num)
zhel... | StarcoderdataPython |
6477025 | default_app_config = "apps.api.network.apps.NetworkConfig"
| StarcoderdataPython |
209660 | <filename>scripts/custom.py
import numpy as np
import skfuzzy as fuzz
import skfuzzy.control as ctrl
import scipy.ndimage as img
def custom_process(height):
""" Custom function for experimental data analysis. """
return height
def fuzzy_custom(height, growth, canopy):
""" Perform fuzzy logic analysis o... | StarcoderdataPython |
5053679 | <filename>bigflow_python/python/bigflow/test/write_binary_test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Baidu, Inc. All Rights Reserved.
#
# 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... | StarcoderdataPython |
6430560 | # -*- coding: utf-8 -*-
"""
device.py
=========
Devices are connected to the computer. They control sensors and actuators. A device has to be able to set and read
values.
Setting complex devices such as a laser would require to define it as a device and its properties as sensors or
actuators res... | StarcoderdataPython |
121026 | <gh_stars>1-10
# proxy module
from __future__ import absolute_import
from codetools.blocks.ast_25.ast import *
| StarcoderdataPython |
1679304 | import random
import time
b = []
for x in range(0,100):
b.append(int(random.random()*10000))
maximum = len(b) - 1
for i in range(0,maximum):
start_time = time.time()
for j in range(0,maximum):
if b[j] > b[j + 1]:
temp = b[j]
b[j] = b[j + 1]
b[j + 1] = temp
maximum -= 1
print b
print ("---%s seconds--... | StarcoderdataPython |
6703357 | <reponame>dead-tech/pre-commit-cmake
from __future__ import annotations
import argparse
import os
import subprocess
from contextlib import contextmanager
from typing import Iterator
@contextmanager
def working_directory(path: str) -> Iterator[None]:
prev_cwd = os.getcwd()
os.chdir(path)
try:
yiel... | StarcoderdataPython |
3338255 | <filename>hw2_source_final.py
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
import re
from bs4.element import NavigableString, Tag
import datetime
import urllib
import requests
import scipy.stats as stats
import math
import matplotlib.pyplot as plt
# Function to scrape strings fr... | StarcoderdataPython |
1766854 | # Exercise 1: A Good First Program
print "Hello World!"
| StarcoderdataPython |
8049169 | from typing import Tuple, List, Union, Sequence, Dict, Callable, Any
from pathlib import Path
from spacy.vectors import Vectors
from spacy.strings import StringStore
from spacy.util import SimpleFrozenDict
import numpy
import srsly
from .util import registry, cosine_similarity
class Sense2Vec(object):
def __init... | StarcoderdataPython |
8089799 | import paho.mqtt.client as mqtt
import json
import time
import os
from random import *
# Host name of the local mosquitto broker is read from the environment variable MqttBrokerAddress
mosquitto_host = os.environ.get("MqttBrokerAddress", "localhost")
# Port of the mosquitto broker.
mosquitto_port = 1883
# Connect... | StarcoderdataPython |
6648657 | <reponame>thomson131/tiny_python_projects
#!/usr/bin/env python3
"""
Author : james <<EMAIL>>
Date : 2022-02-21
Purpose: Create a picnic list
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
... | StarcoderdataPython |
5010653 | from text_utils.pronunciation.main import eng_to_arpa, ger_to_ipa
result = ger_to_ipa(
eng_sentence="This is a test",
consider_annotations=False,
)
print(result)
| StarcoderdataPython |
6470386 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 08:16:36 2019
@author: john.onwuemeka; <NAME>
"""
import numpy as np
def get_good_snr_freq_range(snrthres,signal1,signal2,snr1,snr2,freqsignal1,freqsignal2,noise1,noise2):
"""
Function to determine useable frequency rang... | StarcoderdataPython |
5165014 | ipBadLapErr = -23000 # bad network configuration
ipBadCnfgErr = -23001 # bad IP configuration error
ipNoCnfgErr = -23002 # missing IP or LAP configuration error
ipLoadErr = -23003 # error in MacTCP load
ipBadAddr = -23004 # error in getting address
connectionClosing = -23005 # connectio... | StarcoderdataPython |
3263010 | <filename>day02/passwords.py
def validate(line):
split = line.split(':')
left, psswd = split[0].strip(), split[1].strip()
split = left.split()
bounds, letter = split[0].strip(), split[1].strip()
split = bounds.split('-')
lower, upper = int(split[0]), int(split[1])
return len(list(filter(... | StarcoderdataPython |
12836394 | from os import system , name
def Run(Input):
if name == "nt":
# Windows Machine
system('dir')
else:
# Linux/Unix Machine
system('ls') | StarcoderdataPython |
8097042 | <gh_stars>1-10
from gwk.records.excel import save_as_uigf
from gwk.records.models import migrate
def main(uid):
with open(f'./ggr_{uid}.json', 'r', encoding='UTF-8') as f:
old = migrate(f)
with open(f'./records_{uid}.json', 'w', encoding='UTF-8') as f:
old.dump(f)
save_as_uigf(old, f'./re... | StarcoderdataPython |
71927 | #!/usr/bin/env python
import os,sys
curdir = os.path.abspath(".")
for f in [f for f in os.listdir(curdir) if f.endswith(".cxd") and not f.endswith("_bg.cxd")]:
fout = f[:-4] + ".out"
cmd = "sbatch --output=%s/%s cxd_to_h5.sh %s/%s" % (curdir, fout, curdir, f)
for arg in sys.argv[1:]:
cmd += " " + ... | StarcoderdataPython |
4911437 | from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext_noop as _
# this is just here to mark some strings from settings for translation
# in a safer way.
# there is almost certainly a smarter way to do this.
_("Monitor Workers")
_("Inspect Data")
... | StarcoderdataPython |
3406569 | <reponame>Greeser/gate-decorator-pruning
"""
* Copyright (C) 2019 <NAME>
* If you are using this code in your research, please cite the paper:
* Gate Decorator: Global Filter Pruning Method for Accelerating Deep Convolutional Neural Networks, in NeurIPS 2019.
"""
import torch
import torchvision
from torchvision imp... | StarcoderdataPython |
1956850 | <gh_stars>1-10
def aumentar(x):
s = x + 1
#print(f'Alguém te deu uma moeda, de {x} suas moedas aumentaram para {s}')
return s
def diminuir(x):
s = x - 1
#print(f'Você doou uma moeda, de {x} suas moedas diminuiram para {s}')
return s
def dobro(x):
s = x * 2
#print(f'Você ganhou um so... | StarcoderdataPython |
8176042 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 09:58:28 2020
@author: TheBeast
"""
# =============================================================================
# Clear Variables
# =============================================================================
# Clear variables before runn... | StarcoderdataPython |
3241213 | from sys import argv
import json
import os
import requests
from base64 import b64encode
ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'
def get_food_name(b64_text: bytes) -> str:
api_key = os.environ['VISION_API']
img_requests = []
text = b64_text
img_requests.append({
'... | StarcoderdataPython |
1837815 | '''
Created on 9.11.2016
@author: <NAME>
'''
import numpy as np
import xevacam.xevadll as xdll
from contextlib import contextmanager
import threading
import queue
import sys
import time
import struct
import xevacam.utils as utils
from xevacam.utils import kbinterrupt_decorate
'''
class ExceptionThread(threading.Thre... | StarcoderdataPython |
12836694 | <filename>language/python/string_handle.py
import json
def basic():
len('aaaa')
str(1)
try:
a = 'aaa' + 2
except TypeError as e:
print('Type Error: {0}'.format(e))
def dict_to_str():
print('dict to str')
d1 = {'a': 1, 'b': 'string'}
d1_str = str(d1)
print(d1_str)
... | StarcoderdataPython |
3300816 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.task.task... | StarcoderdataPython |
204714 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom Logging IO
"""
from logIO.setupLogging import *
| StarcoderdataPython |
3285539 | """
Utility functions for the backends
"""
from datetime import datetime, timedelta
import logging
import pytz
from django.core.exceptions import ObjectDoesNotExist
from requests.exceptions import HTTPError
from social_django.utils import load_strategy
from backends.exceptions import InvalidCredentialStored
from back... | StarcoderdataPython |
5141187 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 15:21:26 2018
@author: <NAME>
"""
import numpy as np
import time
from threading import Thread
from traits.api import HasTraits, Float, Enum, Array, Instance, Int, String, Bool, Button, List, Tuple, Dict, Directory, HTML
from traitsui.api import ... | StarcoderdataPython |
9721761 | <filename>deepspeed/runtime/bf16_optimizer.py
import torch
import torch.distributed as dist
from deepspeed.runtime.constants import PIPE_REPLICATED
from deepspeed.ops.op_builder import UtilsBuilder
from packaging import version as pkg_version
from deepspeed.git_version_info import version
from deepspeed.runtime.utils ... | StarcoderdataPython |
3258416 | import logging
from bentoml.utils.log import configure_logging
def test_configure_logging_default():
configure_logging()
bentoml_logger = logging.getLogger("bentoml")
assert bentoml_logger.level == logging.INFO
assert bentoml_logger.propagate is False
assert len(bentoml_logger.handlers) == 2
... | StarcoderdataPython |
11323150 | <filename>setup.py
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="housie",
version="0.1.0",
author="<NAME>",
author_email="<EMAIL>",
description="All the core logic for playing/simulating the popular game 'Housie' "
"(a... | StarcoderdataPython |
9660931 | <filename>Wettbewerbe/migrations/0014_auto_20170827_1229.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-08-27 12:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
(... | StarcoderdataPython |
5023061 | from fancy_python_library import get_fancy
print('- This is so very fancy!')
print('- {}!'.format(get_fancy()))
| StarcoderdataPython |
4959103 | <reponame>wis-software/office-manager
from django.db import models
from django.utils.translation import ugettext_lazy as _
__all__ = [
'Publisher'
]
class Publisher(models.Model):
title = models.CharField(_('name'), max_length=1024)
description = models.TextField(_('description'), default='', blank=True)... | StarcoderdataPython |
9643039 | from pyradox.datatype import Color, Time, Tree
from pyradox.filetype import csv, json, table, txt, yml
from pyradox.filetype.txt import parse, parse_file, parse_dir, parse_merge
from pyradox.filetype.yml import get_localisation
from pyradox.config import get_language, get_game_from_path, get_game_directory
from ... | StarcoderdataPython |
1682031 | <reponame>shivachoudhary/demo1
# !usr/bin/python
# Ussage :: creating modules and use as many time
def nseries(a):
sum=0
for value in range(1,a+1):
sum=sum+value
return sum
def sub(a,b):
if(a>b):
return a-b
else:
return b-a
if __name__=='__main__':
b=int(raw_input("enter a value ::"))
print "heyyy u... | StarcoderdataPython |
163383 | <filename>darkarmour.py
#!/usr/bin/env python3
import os
import sys
import random
import string
import argparse
from lib import banner
from lib import compile
from lib import auxiliary
from lib import encryption
class DarkArmour(object):
def __init__(self):
super(DarkArmour, self).__init__()
self... | StarcoderdataPython |
5049513 | from collections import namedtuple
import time
import logging
import numpy as np
import pickle
from es_distributed import tf_util
from es_distributed.policies import policies
from es_distributed.config import Result
from .common import SharedNoiseTable, RunningStat
from . import algo
log = logging.getLogger(__name... | StarcoderdataPython |
1803055 | <reponame>iahsanujunda/federated
# Copyright 2019, The TensorFlow Federated Authors.
#
# 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
#
# Un... | StarcoderdataPython |
6608080 | """Module for Financial Transactions
"""
import datetime
class Transaction:
def __init__(
self,
ID,
amount: float,
inflow: bool,
time: datetime.datetime,
description: str = '',
currency_code: str = 'USD',
) -> None:
self.ID = ID
self... | StarcoderdataPython |
1684925 | import numpy as np
import math
import random
from network.convolution.ConvolutionWrapper import ConvolutionWrapper
class LSTMWrapper(ConvolutionWrapper):
def __init__(self, agent, history_size=10):
super(LSTMWrapper, self).__init__(agent)
self.history_size = history_size
def request_action(sel... | StarcoderdataPython |
297679 | <reponame>Barroso03/iteracion
`Punto 1´
def mcd_euclides(x,y):
while y != 0:
xux = y
y = x%y
x = xux
return x
`Punto 2´
def mcd_sumas_y_restas(x,y):
while y != 0:
xux = y
y -= xux
x = xux
return x
#Creamos una función para iniciar ambos pasos
def inicio():
1numero = 2
2numero = ... | StarcoderdataPython |
3588248 | import code.book_plots as bp
import code.gh_internal as gh
import matplotlib.pyplot as plt
import numpy as np;
import time
from pylab import *
from drawnow import drawnow, figure
from filterpy.discrete_bayes import normalize
from filterpy.discrete_bayes import predict
from filterpy.discrete_bayes import update
from sc... | StarcoderdataPython |
1607760 | import base64
import copy
import inspect
import json
import logging
import os
import re
import warnings
from collections import OrderedDict
from typing import Optional
from urllib.parse import urlparse
try:
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
except... | StarcoderdataPython |
5005154 | <gh_stars>1-10
import newrelic.api.external_trace
def instrument(module):
def url_query(graph_obj, method, path, *args, **kwargs):
return '/'.join([graph_obj.url, path])
newrelic.api.external_trace.wrap_external_trace(
module, 'GraphAPI._query', 'facepy', url_query)
#def url_method(g... | StarcoderdataPython |
11364455 | <gh_stars>1-10
# Environment is not present in original assistive_gym library at https://github.com/Healthcare-Robotics/assistive-gym
from gym import spaces
import numpy as np
import pybullet as p
from .env import AssistiveEnv
from gym.utils import seeding
from collections import OrderedDict
import os
import time
rea... | StarcoderdataPython |
161467 | """
Routines for Fourier transform.
"""
from __future__ import division
from ..datatable.wrapping import wrap
from ..datatable import column
from . import waveforms, specfunc
import numpy as np
import numpy.fft as fft
def truncate_len_pow2(trace, truncate_power=None):
"""
Truncate trace length to t... | StarcoderdataPython |
11257989 | <gh_stars>0
from .models import Profile,Business
from django import forms
from django.forms import ModelForm
class NewProfileForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['user']
class NewbusinessForm(forms.ModelForm):
class Meta:
model = Business
exclude = ['use... | StarcoderdataPython |
196170 | from app import api
from app.controller.soal import Soal
from app.controller.soal import Jawab
api.add_resource(Soal,'/soal')
api.add_resource(Jawab,'/soal/jawab') | StarcoderdataPython |
11279058 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
import urllib2
from threathunter_common.metrics.influxdbproxy import _extract_metrics_params, get_metrics
from threathunter_common.metrics.metricsagent import MetricsAgent
from threathunter_common.metrics.redismetrics import RedisMetrics
__author__ ... | StarcoderdataPython |
1726500 | from math import log2
def differentRightmostBit(n, m):
return 2**log2((n^m)&-(n^m))
if __name__ == '__main__':
input0 = [11, 7, 1, 64, 1073741823, 42]
input1 = [13, 23, 0, 65, 1071513599, 22]
expectedOutput = [2, 16, 1, 1, 131072, 4]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}... | StarcoderdataPython |
9611451 | <gh_stars>1-10
import matplotlib.pyplot as plt
import shapefile as shp
import EFD
coeffList = []
# use a fixed no of harmonics
MaxHarmonic = 17
sf = shp.Reader('/home/sgrieve/Hollow_Processing_Files/Mid_Hollows.shp')
# below here is the real processing of the shapes, above is data i/o
# loop over individual polyg... | StarcoderdataPython |
3321526 | <filename>test.py<gh_stars>1-10
import logging
import sys
from huawei_connector import HuaweiTelnet
import yaml
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
with open('test_model.yaml') as stream:
model = yaml.unsafe_load(stream)
huawei_telnet = HuaweiTelnet(host=model['host'],
... | StarcoderdataPython |
5053534 | # Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# 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... | StarcoderdataPython |
338474 | <filename>gp_lib/kernels.py
import numpy as np
import scipy as sp
import scipy.spatial
from functools import reduce
class Kernel(object):
def __call__(self, x, y):
"""
Returns
-------
kernel: m x n array
"""
raise NotImplementedError
def trace_x_x(self, x):
... | StarcoderdataPython |
1885901 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | StarcoderdataPython |
1765539 |
class TokenGenerator(object):
token_separator = ':'
component_separator = '.'
def __init__(self, component, module):
self._component = component
self._module = module
self._tag_prefix = self.component_separator.join([self._component, self._module]) + self.token_separator
... | StarcoderdataPython |
3215151 | <gh_stars>1-10
# base imports
from base.middleware import RequestMiddleware
from base.utils import get_our_models
# django imports
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
@receiver(post_save)
def audit_log(sender, instance, cre... | StarcoderdataPython |
6524548 | <reponame>sorasful/minos-python<filename>packages/core/minos-microservice-aggregate/tests/test_aggregate/test_entities/test_models/test_base.py
import unittest
from uuid import (
UUID,
uuid4,
)
from minos.aggregate import (
Entity,
)
from minos.common import (
NULL_UUID,
DeclarativeModel,
)
from te... | StarcoderdataPython |
3428726 | import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
channels = [3, 64, 256, 512]
self.leaky_relu = nn.LeakyReLU(0.2)
self.sigmoid = nn.Sigmoid()
self.conv1 = nn.Conv2d(channels[0], channels[1], kernel... | StarcoderdataPython |
6460023 | Increment & Decrement Triangle Pattern
Increment & Decrement Triangle Pattern: The program must accept an Integer N as the input. The program must print hyphens and integers In N+1 lines based on the following conditions.
In the 1st line, the program must print N hyphens and an integer (0).
In the 2nd line, the progra... | StarcoderdataPython |
3229360 | <reponame>gsw945/flask-sio-demo<filename>run.py
# -*- coding: utf-8 -*-
from flask import Flask, request
from sio_server import socketio
from task_client import print_log
app = Flask(__name__)
socketio.init_app(app)
app.socketio = socketio
index_tmpl_str = '''
<!DOCUMENT html>
<html>
<head>
<meta charset="uff-... | StarcoderdataPython |
3571008 | import selenium.common.exceptions
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import O... | StarcoderdataPython |
364117 | # -*- coding: utf-8 -*-
"""
整个数据集的错误案例
"""
import os
import jieba
import re
import pandas as pd
import pickle
import torch
from torch.autograd import Variable
from data_process import data_processing
from TextCNN import TextCNN
from BiLSTM import BiLSTM
from TextCNN_BN import TextCNN_BN, TextCNN_m... | StarcoderdataPython |
1908994 | """
练习1:定义一个类描述数字时钟。
"""
from time import sleep
class Clock(object):
def __init__(self, h=0, m=0, s=0):
# 如果希望属性是私有的,在给属性命名时可以用两个下划线作为开头
self._h = h
self._m = m
self._s = s
def run(self):
self._s += 1
if self._s == 60:
self._s = 0
self... | StarcoderdataPython |
9628056 | #!/usr/bin/env python2
# Written for python 2.7
# This script is used for triggering a search in Sonarr for a specific numner of episodes
# Stdlib
import urlparse
import logging
import datetime
# 3rf Party
import yaml
import requests
with open("sonarr_backfiller.yaml", "r") as settings_file:
settings_import =... | StarcoderdataPython |
6540523 | <filename>rules/rule7.py
#####################################
### RULE 7: lf_semmeddb_triggers ###
#####################################
'''
semmeddb_triggers: keywords that indicate an almost confirmed presence of ADE-Drug from SemMedDB // note: SemMedDB's CUI used to match mentions in discharge summaries
MATCHIN... | StarcoderdataPython |
4963638 | import pytest
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
instance = cluster.add_instance("instance")
@pytest.fixture(scope="module", autouse=True)
def setup_nodes():
try:
cluster.start()
yield cluster
finally:
cluster.shutdown()
def test_htt... | StarcoderdataPython |
1722825 | from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
rooms_idx, bedrooms_idx, population_idx, households_idx = 3, 4, 5, 6
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room=True):
self.add_bedrooms_per_room = add_bedrooms_per_ro... | StarcoderdataPython |
3547095 | # Copyright (c) 2018 Evalf
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... | StarcoderdataPython |
6629853 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
from django.core.serializers.json import DjangoJSONEncoder
from konst import Constant
class ExtendedJSONEncoder(DjangoJSONEncoder):
"""Add support for serializing our class Constant."""
def default(self, obj):
if isinstance... | StarcoderdataPython |
1906562 | import gym
import os
import numpy as np
import pickle
import gym_minigrid
from gym_minigrid import wrappers
import torch
import torch.nn as nn
import pfrl
from pfrl.agents import PPO
from pfrl.utils.batch_states import batch_states
from imitation.data.types import Trajectory
from modules.pfrl_networks import get_m... | StarcoderdataPython |
5102817 | <filename>webapp/webapp/html_builder.py
SQLI1_LINKS = {
"vulnerability_source_code": "https://github.com/neumaneuma/appseccheat.codes/blob/main/webapp/webapp/vulnerabilities/sqli_login_bypass.py",
"vulnerability_gist": "https://gist.github.com/neumaneuma/39a853dfe14e7084ecc8ac8b304c60a3.js",
"exploit_source... | StarcoderdataPython |
5069812 | <filename>burgerkin-board/__init__.py<gh_stars>0
from burgerkin-board.board import Board
| StarcoderdataPython |
3441695 | '''
Blind Curated 75 - Problem 72
=============================
Non-overlapping Intervals
-------------------------
Given a collection of intervals, find the minimum number of intervals you need
to remove to make the rest of the intervals non-overlapping.
[→ LeetCode][1]
[1]: https://leetcode.com/problems/non-overl... | StarcoderdataPython |
3501639 | <filename>quest/quests/prison.py
import copy
from random import randint
from ..quest import Quest
from ..quest_segment import QuestSegment
from utils.command_set import CommandSet
from utils.string_parsing import list_to_string
GOLD_REWARD = 350
GOLD_PENALTY = 50
GOLD_PENALTY_WAIT = 120
GOLD_VARIANCE = 26
EXP_REWARD... | StarcoderdataPython |
8042552 | <filename>buying/migrations/0006_depot_sign_up_secret.py
# Generated by Django 3.1.3 on 2020-11-24 14:52
import buying.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('buying', '0005_auto_20201123_1650'),
]
operations = [
migratio... | StarcoderdataPython |
1892829 |
"""
from zlib import crc32
import struct
def u32_as_bytes_le(x):
return struct.pack("I",x)
value = crc32(b"",0)
for i in range(0,10000):
value = crc32(u32_as_bytes_le(value),0)
print("{:08x}".format(value))
"""
# Xorshift+
def rng(seed):
s0 = seed ^ 0xabcd1234abcd1234
s1 = seed ^ 0xdcba4321dcba4321... | StarcoderdataPython |
4966841 | <filename>src/submit_results.py
import requests
from concurrent.futures import ThreadPoolExecutor
# post massege to STA
def post_single_STA(payloads,num,url,user,password):
resp = requests.post(url+'/s/Observations', json=payloads[num], auth=requests.auth.HTTPBasicAuth(user, password))
print(resp.text)
... | StarcoderdataPython |
1946253 | def run():
from pyfiglet import Figlet
f = Figlet(style='slant')
f.renderText("Tutorial")
start = """
Welcome to the BabySploit Tutorial
In this tutorial you will learn how to navigate and use
BabySploit. The framework is geared towards beginners so
it shouldn't be too hard to get the hang of things.
... | StarcoderdataPython |
11227860 | """
In:
* 23andMe_raw_genotype.txt
Out:
* missing_rsids.v rsid
* missing_genos.v (rsid, genotype)
* dataframe.v immediate report for app dashboard
* dataframe.csv immediate csv for app dashboard
Trigger:
* display available research report in web-app
* collect research pubs for missing rsids
* collect m... | StarcoderdataPython |
12842833 | """
m2wsgi.io.gevent: gevent-based I/O module for m2wsgi
=====================================================
This module provides subclasses of m2wsgi.WSGIHandler and related classes
that are specifically tuned for running under gevent. You can import
and use the classes directory from here, or you can select th... | StarcoderdataPython |
11342120 | <filename>polls/admin.py
from django.contrib import admin
from .models import Question, Choice
# class ChoiceInline(admin.StackedInline):
class ChoiceInline(admin.TabularInline):
# 通过 TabularInline(替代 StackedInline ),关联对象以一种表格式的方式展示,显得更加紧凑
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
list_... | StarcoderdataPython |
1699288 | # -*- coding:utf-8 -*-
from django.urls import path
from docs.views.infovalue import (
# InfoValueCreateApiView,
InfoValueAddApiView,
InfoValueListApiView,
InfoValueDetailApiView,
InfoValueListAllArticleApiView,
)
urlpatterns = [
# 前缀:/api/v1/docs/infovalue/
# 信息值
# path("create", In... | StarcoderdataPython |
6460233 | <filename>ticker_dashboard.py<gh_stars>0
"""
Description: Dashboard to interact with option visuals
"""
import datetime
import streamlit as st
from wallstreet import Stock
from option_utils import (
collect_option_data,
plot_option_percent_gain,
plot_option_asset_value
)
# Constants
FRIDAY_WEEKDAY = 4
TO... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.