text string | size int64 | token_count int64 |
|---|---|---|
"""
Contains data ingest related functions
"""
import re
import os.path
from dateutil.parser import parse as dateparser
import typing
from typing import Dict
import cmr
from hatfieldcmr.ingest.file_type import MODISBlobType
MODIS_NAME = "modis-terra"
TITLE_PATTERN_STRING = r"\w+:([\w]+\.[\w]+):\w+"
TITLE_PATTERN = r... | 6,152 | 2,042 |
import twitter
import datetime
import feedparser
import re
import string
from django.core.management.base import BaseCommand
from optparse import make_option
from twittersmash.models import Feed, TwitterAccount, Message
import pytz
from pytz import timezone
central = timezone('US/Central')
utc = pytz.utc
# Parses th... | 9,520 | 2,376 |
import os
import unittest
from snowflet.lib import read_sql
from snowflet.lib import logging_config
from snowflet.lib import extract_args
from snowflet.lib import apply_kwargs
from snowflet.lib import strip_table
from snowflet.lib import extract_tables_from_query
from snowflet.lib import add_database_id_prefix
from sno... | 8,661 | 2,404 |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-AssignedAccess
GUID : 8530db6e-51c0-43d6-9d02-a8c2088526cd
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from ... | 3,207 | 1,587 |
from capture_image import CaptureImage
if __name__ == '__main__':
"""
This can be directly used from CLI
e.g.: source /home/pi/.smartcambuddy_venv/bin/activate
python smarcambuddy/take_a_photo.py
"""
CaptureImage.trigger()
| 249 | 88 |
from oyster.conf import settings
CELERY_IMPORTS = ['oyster.tasks'] + list(settings.CELERY_TASK_MODULES)
| 105 | 45 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sonnet as snt
import tensorflow as tf
from .drop_mask import make_drop_mask1
from .promotion_mask import make_promotion_mask
from ..boolean_board.black import select_black_fu_board, select_non_black_board
from ..boolean_board.empty import select_empty_board
from ..... | 2,891 | 958 |
from connect.devops_testing.bdd.fixtures import use_connect_request_dispatcher, use_connect_request_builder
from connect.devops_testing.request import Builder, Dispatcher
def test_should_successfully_initialize_request_builder_in_behave_context(behave_context):
use_connect_request_builder(behave_context)
ass... | 631 | 192 |
from django.apps import AppConfig
class KwueConfig(AppConfig):
name = 'kwue'
| 83 | 29 |
import sublime, sublime_plugin
import os, traceback
from ...libs import util
from ...libs import FlowCLI
class JavascriptEnhancementsRefactorConvertToArrowFunctionCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
view = self.view
selection = view.sel()[0]
flow_cli = FlowCLI(view)
res... | 2,492 | 792 |
import os
import sys
import base64
import fnmatch
from kconfiglib import Kconfig, expr_value, Symbol, Choice, MENU, COMMENT, BOOL, STRING, INT, HEX
from java.awt import BorderLayout, Dimension, FlowLayout
from java.awt.event import ActionListener, MouseEvent
from javax.swing import BorderFactory, BoxLayout, ImageIcon, ... | 33,374 | 10,251 |
# coding=utf-8
# pylint: disable=missing-docstring, unused-argument
import os.path
import sqlite3
import tempfile
import unittest
import sqlalchemy.ext.declarative
import sqlalchemy.orm
try:
# noinspection PyPackageRequirements
import ujson as json
except ImportError:
import json
import sqlalchemy_jsonf... | 3,495 | 1,087 |
'''Run Example 4.8 from Aho & Ullman p. 315-316, printing the steps to stdout.
'''
from cfg import aho_ullman, core
import sys
CFG = core.ContextFreeGrammar
G = CFG('''
S -> AA | AS | b
A -> SA | AS | a
''')
w = map(core.Terminal, 'abaab')
print 'G:'
print G
print
print 'w =', ''.join(map(str, w))
print
T = aho_u... | 587 | 251 |
from .convpool_op_base import ConvPoolOpBase
class PoolOp(ConvPoolOpBase):
def __init__(
self,
op_type='Pool',
pool_type=None,
global_pooling=False,
**kwargs
):
super(PoolOp, self).__init__(op_type=op_type, **kwargs)
self.global_pooli... | 495 | 162 |
import pytest
from django.db.models import Manager
from cegs_portal.search.json_templates.v1.dna_region import dnaregions
from cegs_portal.search.json_templates.v1.search_results import (
search_results as sr_json,
)
from cegs_portal.search.models import DNARegion, Facet
from cegs_portal.search.models.utils import... | 1,958 | 613 |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2021 Apple Inc. All Rights Reserved.
#
"""Utility functions to tag tensors with metadata.
The metadata remains with the tensor under torch operations that don't change
the values, e.g. .clone(), .contiguous(), .permute(), etc.
"""
import collections
imp... | 5,002 | 1,451 |
# Rohan E., Lukeš V.
# Modeling large-deforming fluid-saturated porous media using
# an Eulerian incremental formulation.
# Advances in Engineering Software, 113:84-95, 2017,
# https://doi.org/10.1016/j.advengsoft.2016.11.003
#
# Run simulation:
#
# ./simple.py example_largedef_porodyn-1/porodynhe_example2d.py
#
# Th... | 2,705 | 999 |
"""
Pluggable Django email backend for capturing outbound mail for QA/review purposes.
"""
__version__ = "1.0"
__author__ = "Scot Hacker"
__email__ = "shacker@birdhouse.org"
__url__ = "https://github.com/shacker/django-mailcheck"
__license__ = "BSD License"
| 260 | 94 |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 13:41:03 2019
@author: bwc
"""
import numpy as np
def bin_dat(dat,bin_width=0.001,user_roi=[],isBinAligned=False,isDensity=False):
user_roi = np.asarray(user_roi)
roi_supp = (user_roi.size == 2)
# Get roi
if isBinAligned and roi_supp:
low... | 4,923 | 2,209 |
import inspect # http://docs.python.org/2/library/inspect.html
from pprint import pprint
from bage_utils.dict_util import DictUtil # @UnusedImport
class InspectUtil(object):
@staticmethod
def summary():
frame = inspect.stack()[1]
d = {'file': frame[1], 'line': frame[2], 'function': frame[3]... | 1,138 | 397 |
import struct
class SeriesDefinition(object):
def __init__(self, seriesname, replicacount, generation, autotrim, recordsize, options, tombstonedon):
self._seriesname = seriesname
self._replicacount = replicacount
self._generation = generation
self._autotrim = autotrim
s... | 2,812 | 879 |
import os
import random
import time
import xlwt
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from front_login import *
from readConfig import ReadConfig
from db import DbOperate
from selenium.webdriver.chrome.options import Options
from mysql... | 3,914 | 1,330 |
# dashboard_generator.py
import os.path # helps to save in a different folder
import pandas as pd
import itertools
import locale # from https://stackoverflow.com/Questions/320929/currency-formatting-in-python
from os import listdir
from os.path import isfile, join
#for chart generation
import matplotlib
import matplo... | 5,367 | 1,847 |
from urllib.parse import urljoin
from scrapy import Request
from product_spider.items import RawData
from product_spider.utils.functions import strip
from product_spider.utils.spider_mixin import BaseSpider
class MedicalIsotopesSpider(BaseSpider):
name = "medicalisotopes"
base_url = "https://www.medicalisot... | 2,235 | 718 |
import yaml
def read_config(path):
with open(path, 'r') as f:
conf = yaml.safe_load(f)
return conf
| 117 | 45 |
#!/usr/bin/python
import os
lines = [line for line in open("hehe.txt")]
for line in lines:
i = 0
for c in line:
if (c != '_' and not (c >= '0' and c <= '9')):
break
i+=1
cmd = "mv " + line[0:i].strip() + line[i+5:].strip() + " lab2_" + line[0:i].strip() + line[i+5:].strip()
print cmd
os.system(cmd)
c... | 511 | 236 |
#!/usr/bin/enb python
import string, re
import Handler
#######################
# Define some regular expressions inside a quoted string
# then turn the string into the actual data structure.
# (I found it was easiest to understand when done this way.)
definitions = r"""
# These are the atomic symbols Da... | 9,819 | 3,678 |
# This is default settings for VisARTM for local usage
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(BASE_DIR, "data")
SECRET_KEY = 'yj_fhwf$-8ws1%a_vl5c0lf($#ke@c3+lu3l-f733k(j-!q*57'
DEBUG = True
ALLOWED_HOSTS = ["127.0.0.1"]
THREADING = True
REGISTRAT... | 2,915 | 1,029 |
"""pyvizio constants."""
DEVICE_CLASS_SPEAKER = "speaker"
DEVICE_CLASS_TV = "tv"
DEVICE_CLASS_CRAVE360 = "crave360"
DEFAULT_DEVICE_ID = "pyvizio"
DEFAULT_DEVICE_CLASS = DEVICE_CLASS_TV
DEFAULT_DEVICE_NAME = "Python Vizio"
DEFAULT_PORTS = [7345, 9000]
DEFAULT_TIMEOUT = 5
MAX_VOLUME = {DEVICE_CLASS_TV: 100, DEVICE_CLA... | 8,402 | 3,233 |
#
# covid19.py
# owid/latest/covid
#
from owid.catalog.meta import License, Source
import datetime as dt
import pandas as pd
from owid.catalog import Dataset, Table
from etl.helpers import downloaded
MEGAFILE_URL = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv"
def... | 1,858 | 640 |
import unittest
import interop
from SUASSystem import InteropClientConverter
from SUASSystem import Location
class SDATestCase(unittest.TestCase):
def setUp(self):
self.interop_client = InteropClientConverter()
def test_submit_target(self):
compiled_target_info = {
"latitude" : 38... | 1,175 | 362 |
import os
import json
#import fire
from collections import defaultdict
from pprint import pprint
from itertools import product
from .dataset import Dataset
class DocRED(Dataset):
def __init__(self, path):
super(DocRED, self).__init__(name='DocRED')
self.path = path
self._init()
... | 3,244 | 993 |
import os
class Account:
ACCOUNTS_STORAGE = {}
"""Ethereum account"""
def __init__(self):
self.address = "0x" + os.urandom(20).hex()
self.ACCOUNTS_STORAGE[self.address] = self
def __str__(self):
return f'Account {self.address}'
__repr__ = __str__
| 295 | 110 |
from abc import ABC, abstractmethod
from typing import Dict, Hashable, Tuple
import torch
import torch.nn as nn
import swyft
import swyft.utils
from swyft.networks.channelized import ResidualNetWithChannel
from swyft.networks.standardization import (
OnlineDictStandardizingLayer,
OnlineStandardizingLayer,
)
f... | 7,955 | 2,492 |
from output.models.nist_data.list_pkg.date.schema_instance.nistschema_sv_iv_list_date_min_length_1_xsd.nistschema_sv_iv_list_date_min_length_1 import NistschemaSvIvListDateMinLength1
__all__ = [
"NistschemaSvIvListDateMinLength1",
]
| 238 | 97 |
from collections import defaultdict
from enum import auto
from typing import Iterable, List, Optional, TYPE_CHECKING, Union
from mstrio import config
from mstrio.api import contacts
from mstrio.distribution_services.contact_group import ContactGroup
from mstrio.distribution_services.device import Device
from mstrio.ut... | 12,386 | 3,220 |
# Iterador a partir de una función generadora
def fib():
prev, curr = 0, 1
while True:
yield curr
prev, curr = curr, prev + curr
f = fib()
# Recorremos nuestro iterador, llamando a next(). Dentro del for se llama automáticamente a iter(f)
print(0, end=' ')
for n in range(16):
print(next(f)... | 330 | 114 |
#!/usr/bin/env python
import os
import sys
import platform
from setuptools import setup, Extension
if platform.system() != 'Windows' and platform.python_implementation() == "CPython":
ext_modules = [Extension('sevent/cbuffer', sources=['sevent/cbuffer.c'])]
else:
ext_modules = []
if os.path.exist... | 1,166 | 413 |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 ... | 1,229 | 405 |
import os
import warnings
warnings.simplefilter("ignore")
import csv
import numpy
import hyperopt
from hyperopt import Trials,tpe,hp,fmin
from keras.utils import to_categorical
import pickle
from loadConfiguration import Configuration
from objectCreation import createImagedObjects
from trainBCNN import run... | 16,444 | 4,526 |
from torch import cat, cos, float64, sin, stack, tensor
from torch.nn import Module, Parameter
from core.dynamics import RoboticDynamics
class CartPole(RoboticDynamics, Module):
def __init__(self, m_c, m_p, l, g=9.81):
RoboticDynamics.__init__(self, 2, 1)
Module.__init__(self)
self.params... | 1,202 | 461 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#######################################################################
# This script imports your Last.fm listening history #
# inside a MySQL or Sqlite database. #
# ... | 2,674 | 883 |
#!/usr/bin/env python3
"""
data file
read in data
"""
from typing import Tuple, Any
import pandas as pd
import tensorflow as tf
from loguru import logger
from utils import file_path_relative
import numpy as np
from transformers import DistilBertTokenizer
NUM_ROWS_TRAIN: int = 15000
TEST_RATIO: float = 0.2
def _run... | 2,617 | 877 |
# Kratos imports
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as UnitTest
from KratosMultiphysics.WindEngineeringApplication.test_suite import SuiteFlags, TestSuite
import run_cpp_tests
# STL imports
import pathlib
class TestLoader(UnitTest.TestLoader):
@property
def suiteClass(self):
... | 2,875 | 896 |
import re
import uuid
from copy import deepcopy
from datetime import datetime
from lxml import etree
from lxml.html import xhtml_to_html
from geoalchemy import WKTSpatialElement
from geolucidate.functions import _cleanup, _convert
from geolucidate.parser import parser_re
from cadorsfeed import db
from cadorsfeed.mo... | 5,739 | 1,800 |
from sstcam_sandbox import get_checs
from TargetCalibSB.pedestal import PedestalTargetCalib
from TargetCalibSB import get_cell_ids_for_waveform
from CHECLabPy.core.io import TIOReader
from tqdm import tqdm
from glob import glob
def process(path):
pedestal_path = path.replace("_r0.tio", "_ped.tcal")
reader = T... | 1,016 | 393 |
class Solution:
def search(self, nums: List[int], target: int) -> int:
# if len(nums) == 1:
# return 1 if nums[0] == target else 0
tmp = []
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] == target:
tmp.append(m)
... | 740 | 245 |
import pandas as pd
from typing import List, NamedTuple
from .timeseries import agg_by_category_by_date
from primitive_interfaces.base import PrimitiveBase
class AggregateByDateTimeCategory(PrimitiveBase[pd.DataFrame, List[str]]):
__author__ = 'distil'
def __init__(self):
pass
def get_params(sel... | 821 | 247 |
class DataSufficiencyException(Exception):
pass
class ModelFitException(Exception):
pass
class ModelPredictException(Exception):
pass
| 150 | 42 |
# 804. Unique Morse Code Words
class Solution:
def __init__(self):
self.morse_code = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
... | 2,723 | 1,036 |
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import logging
from pygna import output
from pygna.utils import YamlConfig
import pandas as pd
import random
import string
import seaborn as sns
import pygna.output as output
class BlockModel(object):
... | 19,779 | 6,634 |
from django.apps import AppConfig
class PrintshopsConfig(AppConfig):
name = 'printshops'
""" Register our signals """
def ready(self):
import printshops.signals
| 184 | 54 |
def grade(key, submission):
if submission.lower() == 'sea' or submission.lower() == 'the sea':
return True, "Yes! Miles learns Russian so he came up with the words that visually look same in both English and Russian."
else:
return False, "Nyet!"
| 275 | 81 |
import pandas as pd
people_dict = {
"weight": pd.Series([145, 182, 191],index=["joan", "bob", "mike"]),
"birthyear": pd.Series([2002, 2000, 1999], index=["bob", "joan", "mike"], name="year"),
"children": pd.Series([1, 2], index=["mike", "bob"]),
"hobby": pd.Series(["Rock Climbing", "S... | 443 | 189 |
#
# Copyright (C) 2014 Dominik Oepen
#
# This file is part of virtualsmartcard.
#
# virtualsmartcard 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
# l... | 3,440 | 1,210 |
###############################################################
# _ _ _ _ _
# | |__ (_) ___ _ __ __ _ _ __| |_(_) ___| | ___
# | '_ \| |/ _ \| '_ \ / _` | '__| __| |/ __| |/ _ \
# | |_) | | (_) | |_) | (_| | | | |_| | (__| | __/
# |_.__/|_|\___/| .__/ \__,_|_| \__|_|\___|_|\___... | 6,762 | 2,826 |
#!/usr/bin/python3
#
# This software is covered by The Unlicense license
#
import os, pymongo, sys
def print_mongo():
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["cpu_temperature"]
mycol = mydb["temps"]
#print(myclient.list_database_names())
for x in mycol.find()... | 593 | 205 |
# -*- coding: utf-8 -*-
def test_all_contains_only_valid_names():
import pycamunda.decisionreqdef
for name in pycamunda.decisionreqdef.__all__:
getattr(pycamunda.decisionreqdef, name)
| 203 | 77 |
import time
import torch
from torch import nn
from torch.nn import functional as F
#import spconv
import torchplus
from torchplus.nn import Empty, GroupNorm, Sequential
from torchplus.ops.array_ops import gather_nd, scatter_nd
from torchplus.tools import change_default_args
import sys
if '/opt/ros/kinetic/lib/python2.... | 2,185 | 892 |
import string
from typing import List, Dict
# inject code here #
def _mean_in_window(lines, i) -> float:
start = max(i - 5, 0)
finish = min(i + 5, len(lines) - 1)
sm, count = 0, 0
for n in range(start, finish):
sm += len(lines[n]) - 1 # minus one-char prefix
count += 1
return sm /... | 3,001 | 1,098 |
from django.conf.urls import include
from django.urls import path
from django.contrib import admin
from users.views import FacebookLogin
import django_js_reverse.views
from rest_framework.routers import DefaultRouter
from common.routes import routes as common_routes
router = DefaultRouter()
routes = common_routes
fo... | 1,241 | 368 |
import numpy as np
from path import Path
import random
import pickle
import torch
import os
import cv2
def load_as_float(path):
"""Loads image"""
im = cv2.imread(path)
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB).astype(np.float32)
return im
class SequenceFolder(torch.utils.data.Dataset)... | 7,302 | 3,559 |
import Queue
import select
import socket
from conf import ADDRESS, BACKLOG, SIZE
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
print 'starting up on %s port %s' % ADDRESS
server.bind(ADDRESS)
server.listen(BACKLOG)
inputs = [server]
outputs = []
message_queues = {}
while inputs:
... | 1,632 | 479 |
import re
import copy
from collections import defaultdict
from string import Template
# initialize the dictionary for the methods with checked exceptions such as {fake method: real method}
method_dict_checked = {'deleteRecord' : 'delete', \
'editText' : 'setText_new', \
'insertData' : 'insert_new', \
'setLayout... | 3,813 | 1,346 |
# a = 1
# b = 1
# while (not ((a==0) and (b==0))):
# a, b = map(int, input().split())
# print(a+b)
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break
print(a+b) | 272 | 107 |
from builtins import str
from .helpers import run
import logging
import subprocess
import functools
import types
logger = logging.getLogger("commander")
def maestro(scriptId):
"""Run a Keyboard Maestro script by ID (more robust) or name."""
run(
"""osascript -e 'tell application "Keyboard Maestro Eng... | 381 | 113 |
from planning_system.db.schema.views import _get_set_cols
def definition(session):
"""
Return UI view.
Complex view, which requires a dynamic pivot.
"""
pvt_list = _get_set_cols(session)
sql = f"""
SELECT costc, summary_code, summary, section, supersection, summary_order, sec_order, super... | 764 | 259 |
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
num_ops = target[0]
for i in range(1, len(target)):
diff = target[i]-target[i-1]
if diff > 0:
num_ops += diff
return num_ops
| 267 | 84 |
import torch
import torchvision.models as models
'''
Description:
convert torch module to JIT TracedModule.
功能说明:
将torch 模型转化为 JIT TracedModule。
'''
def TracedModelFactory(file_name, traced_model):
traced_model.save(file_name)
traced_model = torch.jit.load(file_name)
print("filename : ", file_name... | 756 | 283 |
# cppsimdata.py
# written by Michael H. Perrott
# with minor modifications by Doug Pastorello to work with both Python 2.7 and Python 3.4
# available at www.cppsim.com as part of the CppSim package
# Copyright (c) 2013-2017 by Michael H. Perrott
# This file is disributed under the MIT license (see Copying file)
impo... | 9,739 | 3,586 |
class ResProcessingError(Exception):
"""The base class for exceptions the occur during resonator processing."""
pass
class ResMinIsLeftMost(ResProcessingError):
"""Raised when the RWHM definition detects that the resonator's minima is the left-most point"""
pass
class ResMinIsRightMost(ResProcessing... | 1,217 | 338 |
import logging
from datetime import datetime
from typing import List
from notify.backends import BackendFactory
from notify.commands import Command
from notify.config import Config, Stack
from notify.notifications import Factory, Notification
from notify.strategies import StrategyFactory
class MaintainConfig:
de... | 5,977 | 1,604 |
technology = {
'kb': '''
Oculus(rift)
HTC(vive)
VR(Zuck, rift)
VR(Gabe, vive)
(Oculus(O) & HTC(H)) ==> Dominates(H, O)
(VR(V)) ==> Technology(T)
''',
'queries':'''
VR(x)
Dominates(x, y)
''',
}
Examples = {
'technology': technology,
} | 254 | 126 |
class Resolver:
def __init__(self):
self.resolvers = []
def addResolver(self,res,priority):
self.resolvers.append(dict(resolver=res,priority=priority))
self.resolvers.sort(key=lambda x: x["priority"])
def resolve(self,name):
for r in [x["resolver"] for x in self.resolvers[::-1]]:
success,result = r(name)
... | 817 | 330 |
import logging
import multiprocessing
import os
import time
from functools import partial
from multiprocessing import Process, Queue, Pool
from typing import Iterable
import pandas as pd
import pyarrow as pa
from feast.feature_set import FeatureSet
from feast.type_map import convert_dict_to_proto_values
from feast.type... | 8,113 | 2,426 |
import collections
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
scount, tcount = collections.Counter(s), collections.Counter(t)
for t in tcount:
if tcount[t] > scount[t]:
return t
... | 389 | 127 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 16,580 | 4,672 |
# -*- coding: utf-8 -*-
import pickle
import os
# third-party imports
import jsonpickle
class Submission:
def __init__(self):
# Source is either Tumblr or Reddit
self.source = u''
self.title = u''
self.author = u''
self.subreddit = u''
self.subredditTitle = u''
... | 4,136 | 1,406 |
#!/usr/bin/env python3.7
from decimal import Decimal
from collections import namedtuple
EventPrizeLevel = namedtuple(
"EventPrizeLevel", ["packs", "gems", "gold"], defaults=[0, 0, 0],
)
| 191 | 67 |
"""
Escreva um programa que faça o computador 'Pensar' em um número inteiro entre 0 e 5
e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
"""
from random import randint
numero_gerado_aleatoriamente = randint(0,5)
numero_digitado_pelo_usuario = int(input('Adivinhe qual número... | 621 | 224 |
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GATConv
class GCN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.5):
super(GCN, self).__init__()
self.dropout = dropout
self.conv1 = GCNConv(input_dim, hidd... | 1,699 | 594 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : scene_graph.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 07/19/2018
#
# This file is part of NSCL-PyTorch.
# Distributed under terms of the MIT license.
"""
Scene Graph generation.
"""
import os
import torch
import torch.nn as nn
impo... | 7,740 | 2,553 |
class Room (object):
def __init__(self, name, xl, yl, layout):
self.name = str(name)
self.xl = int(xl)
self.yl = int(yl)
self.layout = layout
def load_room_file(file):
roomfile = open(file, "r")
roomlist = []
linelist = []
for line in roomfile:
linelist.ap... | 789 | 284 |
import re
from abc import ABCMeta
from dateutil import parser
class BaseData(metaclass=ABCMeta):
def __init__(self):
self._lastmod = None
self._loc = None
@property
def lastmod(self):
return self._lastmod
@lastmod.setter
def lastmod(self, value):
self._lastmod = p... | 645 | 198 |
import unittest
import networkx as nx
from core.placement.spsolver import DPShortestPathSolver
class TestShorthestPathSolverMethods(unittest.TestCase):
def setUp(self):
self.g1 = nx.read_weighted_edgelist('tests/test-graph_1.txt', create_using=nx.MultiDiGraph, nodetype=int)
def test_shortest_path(self... | 630 | 232 |
"""
# INTEGER BREAK
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, ... | 1,285 | 437 |
#!/usr/bin/env python
from distutils.core import setup
SHORT_DESCR = "CAmera MOtion COMPensation using image stiching techniques to generate stabilized videos"
try:
LONG_DESCR = open('README.rst').read()
except IOError:
LONG_DESCR = SHORT_DESCR
setup(
name='camocomp',
version='0.1',
author='Adri... | 1,112 | 368 |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
li = [1, 2, 3, 4, 5, 6, 7]
return render_template('filter.html', li=li)
@app.template_filter('li_rv2') # 添加过滤器 方法二
def li_reverse(li):
res = list(li)
res.reverse()
return res
# app.add_template_filter... | 408 | 187 |
""""""
import matplotlib as mpl
__all__ = ["set"]
def set(tick_scale=1, rc=dict()):
"""
Control plot style and scaling using seaborn and the
matplotlib rcParams interface.
:param tick_scale: A scaler number controling the spacing
on tick marks, defaults to 1.
:type tick_scale: floa... | 801 | 294 |
# M1
def mul1(a1):
return lambda b1:b1*a1
myresult = mul1(3)
print(myresult(7))
#M-2
mul = lambda a = 3: (lambda b: a*b)
myres = mul()
print(myres)
print(myres(7))
| 169 | 85 |
from enum import Enum, auto
from typing import NamedTuple, Optional
class Parameter(NamedTuple):
class Kind(Enum):
ARG = auto()
VARARG = auto()
KWARG = auto()
name: str
annotation: Optional[str]
kind: Kind
def __eq__(self, other: "Parameter") -> bool:
if not isins... | 414 | 125 |
# -*- coding: utf-8 -*-
import numpy as np
from odbAccess import *
from abaqusConstants import *
filename = 'Job-4e-SS-Pulse'
"""
LOAD DATA
===============================================================================
"""
results = np.load(filename + '.npz')
vonMisesMax = results['vonMisesMax'].transpose()
vonMis... | 2,961 | 1,020 |
"""
SSH reimplementation in Python, made by Unazed Spectaculum under the MIT license
"""
import socket
import struct
class SSH(object):
"""
Abstracted interface for secure-shell protocol with underlying TCP structure
"""
def __init__(self, host_ip, hostname, host_port=22, version="SSH-2.0"):
... | 7,014 | 2,783 |
import random
def find_spelling(n):
"""
Finds d, r s.t. n-1 = 2^r * d
"""
r = 0
d = n - 1
# divmod used for large numbers
quotient, remainder = divmod(d, 2)
# while we can still divide 2's into n-1...
while remainder != 1:
r += 1
d = quotient # previo... | 1,140 | 438 |
#MARTY I2C PI
#SCRIPT BASED ON MATS WORK
#SCRIPT PUSHED INSIDE inmoovCustom : https://github.com/MyRobotLab/inmoov/tree/master/InmoovScript
raspi = Runtime.createAndStart("RasPi","RasPi")
adaFruit16c = Runtime.createAndStart("AdaFruit16C","Adafruit16CServoDriver")
adaFruit16c.setController("RasPi","1","0x40")
#
# This... | 4,859 | 2,303 |
from sklearn import tree, svm
from sklearn.neural_network import MLPClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression, RidgeClassifier
from sklearn.naive_baye... | 7,214 | 1,934 |
import pandas as pd
import numpy as np
import data_inputs, evaluate_EWRs
#--------------------------------------------------------------------------------------------------
def sum_events(events):
'''returns a sum of events'''
return int(round(events.sum(), 0))
def get_frequency(events):
'''Returns the f... | 8,099 | 2,365 |
import pandas as pd
writer = pd.ExcelWriter("data.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
| 247 | 81 |
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
setup(
name="dem",
version="0.0.8",
author="Ian Macaulay, Jeremy Opalach",
author_email="ismacaul@gmail.com",
url="http://www.github.com/nitehawck/dem",
description="An agnostic library/package manager for setting... | 1,564 | 466 |
# django imports
from django.contrib import admin
# lfs imports
from lfs.core.models import Action
from lfs.core.models import ActionGroup
from lfs.core.models import Shop
from lfs.core.models import Country
admin.site.register(Shop)
admin.site.register(Action)
admin.site.register(ActionGroup)
admin.site.register(Cou... | 326 | 99 |