id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1738434
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.metrics import accuracy_score, confusion_matrix,precision_recall_fscore_support, classification_report class Combinator(BaseEstimator, TransformerMixin): """ Static A posteriori Combinator of predictions. Args: - scheme: Str...
StarcoderdataPython
33599
from numpy import average, number from textblob import TextBlob class ScaleUtilities: average = 0 number = 0 def __init__(self, string, number): self.string = string def get_subjectivity_of(string): polarity = TextBlob(string).sentiment.polarity * 5 number += 1 average...
StarcoderdataPython
4813781
#coding:utf-8 import tensorflow as tf from model import ShowAndTell import keras import os import keras.backend as K import numpy as np K.set_learning_phase(0) FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("weight_path", "./keras_weight/weights_full.h5", "Weights data path") tf.app.flags.DEFINE_string(...
StarcoderdataPython
80295
from rest_framework import serializers from rest_framework_gis import serializers from rest_framework.serializers import CharField, IntegerField, BooleanField from passenger_census_api.models import PassengerCensus, AnnualRouteRidership, OrCensusBlockPolygons, WaCensusBlockPolygons, AnnualCensusBlockRidership, Censu...
StarcoderdataPython
3229871
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri May 3 14:28:57 2019 @author: logancross """ from mvpa2.suite import * from pymvpaw import * import matplotlib.pyplot as plt from mvpa2.measures.searchlight import sphere_searchlight import mvpa_utils_pav import sys your_path = '/Users/logancross/Docu...
StarcoderdataPython
129349
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyFilelock(PythonPackage): """A platform-independent file lock for Python. This packa...
StarcoderdataPython
67832
from tests.utils import WriteTests class WriteTh(WriteTests): fixture_dir = "tests/fixtures/templates/tags/th" class TestColspanMergesCells(WriteTh): template_file = "colspan_merges.html.jinja2" expected_result_file = "colspan_merges.xlsx" class TestRowspanMergesCells(WriteTh): template_file = "ro...
StarcoderdataPython
104006
from django.urls import path from . import views from django.conf.urls import url urlpatterns = [ url(r'^$', views.home, name='home'), path('', views.index, name='index'), path('compute/', views.ocr_view, name='ocr'), url('uploads/form/$', views.model_form_upload, name='model_form_upload'), ]
StarcoderdataPython
1730542
<reponame>renmengye/tfplus import numpy as np import os import time from tfplus.utils import cmd_args, logger, listener, OptionBase, Factory from tfplus.utils import plotter cmd_args.add('save_ckpt', 'bool', False) _factory = None def get_factory(): global _factory if _factory is None: _factory = F...
StarcoderdataPython
1609349
#!/usr/bin/env python import rospy from robotiq_common.AdvancedController import AdvancedController from robotiq_2f_gripper_control.msg import Robotiq2FGripper_robot_input, Robotiq2FGripper_robot_output class TwoFingerGripperController(AdvancedController): def __init__(self): super(TwoFingerGripperControl...
StarcoderdataPython
3321299
<gh_stars>0 """ This module to define neural network """ import json import os import sys import argparse import ConfigParser import paddle import paddle.fluid as fluid def db_lstm(data_reader, word, postag, p_word, conf_dict): """ Neural network structure definition: Stacked bidirectional ...
StarcoderdataPython
1738328
""" mfgmg module. Contains the ModflowGmg class. Note that the user can access the ModflowGmg class as `flopy.modflow.ModflowGmg`. Additional information for this MODFLOW package can be found at the `Online MODFLOW Guide <http://water.usgs.gov/ogw/modflow/MODFLOW-2005-Guide/gmg.htm>`_. """ import sys from ..pakbase ...
StarcoderdataPython
1750497
<reponame>meryusha/seeds_faster<filename>maskrcnn_benchmark/data/datasets/evaluation/seed/seed_predict.py # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import cv2 import torch from torchvision import transforms as T from maskrcnn_benchmark.modeling.detector import build_detection_model from m...
StarcoderdataPython
3329925
<reponame>Glignos/invenio-iiif<gh_stars>0 # -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """IIIF image previewer.""" from __future__ imp...
StarcoderdataPython
148726
import importlib.util import logging import os import re import signal import sys class FrameworkError(Exception): pass def load_module(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exe...
StarcoderdataPython
3301913
<reponame>jordyvanraalte/piqcer-client-python import requests from requests.auth import HTTPBasicAuth from ..resources.resource import Resource class Customers(Resource): def __init__(self): super().__init__("customers") def get_customer_addresses(self, id): return requests.get(self.config.ba...
StarcoderdataPython
32090
# /bin/env python # coding: utf-8 from __future__ import print_function import sys import argparse import logging import os import math import cv2 import numpy as np class GenerateSyntheticData: import PythonMagick as Magick def __init__(self, logger=None): if logger == None: logging.b...
StarcoderdataPython
38236
<reponame>project-scifi/scifiweb from django.conf.urls import include from django.conf.urls import url from django.shortcuts import redirect from django.shortcuts import reverse import scifiweb.about.urls import scifiweb.news.urls from scifiweb.home import home from scifiweb.robots import robots_dot_txt urlpatterns =...
StarcoderdataPython
3231971
# Copyright 2020 DeepMind Technologies 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
StarcoderdataPython
178117
<reponame>adnanqidwai/school_algorithms<gh_stars>1-10 from math import sqrt as _sqrt from ._if_not_valid_raise import (_if_not_int_or_float_raise, _if_not_positive_raise) def pythag_leg(hy, a): """ Calculates the length of a leg in right-angled triangle using the formula: ...
StarcoderdataPython
4839570
<reponame>adeebabdulsalam/py-stellar-base from typing import Union from ..call_builder.base_call_builder import BaseCallBuilder from ..client.base_async_client import BaseAsyncClient from ..client.base_sync_client import BaseSyncClient class TransactionsCallBuilder(BaseCallBuilder): """ Creates a new :class:`Tra...
StarcoderdataPython
1694041
# https://www.globaletraining.com/ # Simple Multiple Inheritance # ParentClass1 <--- ChildClassLevel1 <--- ChildClassLevel2 class ParentClass1: def __init__(self, message, message_id): print("ParentClass1 __init__") self.message = message self.message_id = message_id def click_happy(s...
StarcoderdataPython
4802817
import pickle from os import path as osp from typing import List from multiworld.envs.pygame import PickAndPlaceEnv from rlkit.envs.pygame.pnp_util import sample_pnp_sets from rlkit.misc import asset_loader from rlkit.launchers.config import LOCAL_LOG_DIR from rlkit.torch.sets import set def create_sets( env...
StarcoderdataPython
1669967
# n = nums.length # time = O(n) # space = O(1) # done time = 15m class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: if not nums: return 0 continuous_count = 1 max_continuous_count = 1 for i in range(1, len(nums)): if nums[i-1] < nums[i]: ...
StarcoderdataPython
1654841
<reponame>mgielda/hwt<gh_stars>100-1000 def internal(fn): """ Decorator which does not affect functionality but it is used as marker which tells that this object is not interesting for users and it is only used internally """ return fn
StarcoderdataPython
1667256
<filename>examples/formal_project/sampleproject/api/views.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging from sampleproject.base import MyBaseHandler from tornado.web import HTTPError class ApiHandler(MyBaseHandler): EXCEPTION_HANDLERS = { HTTPError: '_handle_http_error' } ...
StarcoderdataPython
3301909
<reponame>qfwysw/oft import time import torch from torchvision.transforms.functional import to_tensor from argparse import ArgumentParser import matplotlib.pyplot as plt from oft import KittiObjectDataset, OftNet, ObjectEncoder, visualize_objects def parse_args(): parser = ArgumentParser() parser.add_argume...
StarcoderdataPython
1630380
<gh_stars>1-10 import numpy as np import pandas as pd from MLFeatureSelection import sequence_selection from sklearn.linear_model import LogisticRegression from sklearn.model_selection import KFold """ MLFeatureSelection筛选特征 https://github.com/duxuhao/Feature-Selection """ sf = sequence_selection.Select(Sequence=True...
StarcoderdataPython
3206344
import torch import torch.nn as nn import torch.nn.functional as F class SSIM(nn.Module): """Layer to compute the SSIM loss between a pair of images """ def __init__(self): super(SSIM, self).__init__() self.mu_x_pool = nn.AvgPool2d(3, 1) self.mu_y_pool = nn.AvgPool2d(3, 1) ...
StarcoderdataPython
4836104
import pandas as pd import time import os import numpy as np import matplotlib.pyplot as plt from collections import defaultdict pd.set_option('mode.chained_assignment', None) # preprocessing of heterogeneous nodes and edges def preprocess_data(v_sample, e_sample, core_targets, ext_targets, core_testing): t0 = time....
StarcoderdataPython
3274207
<filename>Chapter04/ordereddict_keys.py<gh_stars>10-100 >>> d.keys() odict_keys(['a', 'c', 'd', 'e', 'b'])
StarcoderdataPython
42362
#!/usr/bin/env python3 from dev_aberto import hello from babel.dates import format_datetime from datetime import datetime import gettext gettext.install('hello', localedir='locale') if __name__ == '__main__': date, name = hello() date = format_datetime(datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')) print(...
StarcoderdataPython
1775519
<reponame>nathan4690/Simple-Chess<gh_stars>0 import chess import pygame from os.path import dirname from typing import Iterable pygame.init() infoObject = pygame.display.Info() RESOURCESPATH = (dirname(__file__)) + "/Resources/" SCREENWIDTH = 60*8 SCREENHEIGHT = 60*8 IMAGESNAME = ["wK","wQ","wR","wB","wN","w...
StarcoderdataPython
1726923
<filename>interfaces/result.py import torch from typing import Dict, Any from dataclasses import dataclass class Result: outputs: torch.Tensor loss: torch.Tensor def plot(self) -> Dict[str, Any]: return {} @dataclass class RecurrentResult(Result): outputs: torch.Tensor loss: torch.Tenso...
StarcoderdataPython
1691395
<filename>sevent/coroutines/loop.py<gh_stars>10-100 # -*- coding: utf-8 -*- # 2020/5/8 # create by: snower import types import greenlet from ..utils import get_logger def warp_coroutine(BaseIOLoop): class IOLoop(BaseIOLoop): def call_async(self, callback, *args, **kwargs): if isin...
StarcoderdataPython
62343
<reponame>philippschw/flightstats_API # -*- coding: utf-8 -*- #pylint:disable=too-many-lines """ This database should really be a database... Also - needs updating. Also - needs to move to Eva. """ from __future__ import unicode_literals, division, print_function AIRPORTS_ICAO_TO_IATA = { "YMOR" : "MRZ", ...
StarcoderdataPython
1715564
<filename>utils/utils_data.py<gh_stars>0 import logging import os import torch logger = logging.getLogger(__name__) class InputExample(object): """A single training/test example for classification.""" def __init__(self, guid, sentence, label): """Constructs a InputExample. Args: ...
StarcoderdataPython
3335765
<reponame>ElectronicBabylonianLiterature/dictionary from typing import Mapping, Type from marshmallow import Schema, fields, post_load from marshmallow_oneofschema import OneOfSchema from ebl.bibliography.application.reference_schema import ReferenceSchema from ebl.schemas import NameEnum from ebl.transliteration.app...
StarcoderdataPython
1642754
#!/usr/bin/env python # coding: utf-8 # In[50]: # 6. naloga # Source: # https://towardsdatascience.com/building-a-k-nearest-neighbors-k-nn-model-with-scikit-learn-51209555453a # https://medium.com/@svanillasun/how-to-deal-with-cross-validation-based-on-knn-algorithm-compute-auc-based-on-naive-bayes-ff4b8284cff4 #...
StarcoderdataPython
1683127
<gh_stars>0 import math import os import sys import numpy as np import torch from ising_model import ( data, l0_l2constrained_ise, l0_l2constrained_logreg, l1_constrained_logreg, l1_ise, l1_logreg, metrics, ) # Parameters current_id = sys.argv[1] dataset_root = sys.argv[2] N = int(sys.arg...
StarcoderdataPython
3299374
# Copyright 2020 NXP Semiconductors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
StarcoderdataPython
1716617
from .dsl import *
StarcoderdataPython
4826825
<filename>tests/test_0341-parquet-reader-writer.py # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE from __future__ import absolute_import import sys import os import pytest import numpy import awkward1 pyarrow_parquet = pytest.importorskip("pyarrow.parquet") def test_wr...
StarcoderdataPython
6025
from django.contrib import admin #from .models import * from . import models # Register your models here. admin.site.register(models.ClimbModel)
StarcoderdataPython
1692512
<reponame>T3kton/contractor_plugins<filename>contractor_plugins/AWS/migrations/0001_initial.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def load_foundation_blueprints( app, schema_editor ): FoundationBluePrint = app.get_model( 'BluePrint', ...
StarcoderdataPython
107834
<gh_stars>1-10 # ## Importing modules # Figure 3: Importing needed resources import cocotb from cocotb.triggers import FallingEdge import random # ### The tinyalu_utils module # All testbenches use tinyalu_utils, so store it in a central # place and add its path to the sys path so we can import it from pathlib impo...
StarcoderdataPython
3306922
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import local_evaluation_for_loop from datetime import datetime from tf import train_tensorflow_for_loop if __name__ == '__main__': elapsed_time, gin_binding...
StarcoderdataPython
1799253
import numpy as np from ray import tune exp_args = { 'stop': {'is_finished': True}, 'resume': False, 'verbose': True, 'checkpoint_freq': 0, 'checkpoint_at_end': False, 'num_samples': 1, 'resources_per_trial': {'cpu': 2, 'gpu': 1}, 'config': { 'SynDataset.dataset_choice': tune.grid_search( [...
StarcoderdataPython
116800
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 30 08:29:21 2019 @author: hhouse """ import pandas as pd # Load datasets as pandas dataframes df_nyc = pd.read_csv("stage3_format_nyc.csv") df_25pct = pd.read_csv("stage3_format_nyc_25pct.csv") # Deleting unnecessary columns del df_nyc['confidenc...
StarcoderdataPython
4803031
from django.core.management import setup_environ import os import sys sys.path.append(os.path.dirname(os.path.join('..','wp',__file__))) import settings setup_environ(settings) #==================================# from arp.models import ConservationFeature as F from django.template.defaultfilters import slugify def ...
StarcoderdataPython
1676479
<filename>dipy/io/gradients.py<gh_stars>1-10 from __future__ import division, print_function, absolute_import from os.path import splitext from ..utils.six import string_types import numpy as np def read_bvals_bvecs(fbvals, fbvecs): """ Read b-values and b-vectors from the disk Parameters --------...
StarcoderdataPython
1645489
<filename>apps/dbcache/migrations/0002_auto_20200226_1841.py # Generated by Django 3.0.3 on 2020-02-26 22:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("dbcache", "0001_initial"), ] operations = [ migrations.AddIndex( mo...
StarcoderdataPython
1679691
from GitMarco.tf import utils, metrics, basic import numpy as np from GitMarco.tf.losses import chamfer_distance, euclidian_dist_loss from GitMarco.tf.optimization import OptiLoss, GradientOptimizer from GitMarco.tf.pointnet import Pointnet, PointnetAe from GitMarco.tf.utils import limit_memory, random_dataset import p...
StarcoderdataPython
3254607
<filename>Predict.py import kashgari from configparser import ConfigParser def predict(model, text): '''预测 输入句子,返回时间标记列表 ''' text = text.replace(" ", ",") tag_list = model.predict([[char for char in text]]) return tag_list if __name__ == '__main__': cf = ConfigParser() cf.read('./conf...
StarcoderdataPython
1648734
<filename>EJC/simulation_so.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 1 16:47:17 2018 @author: esteban """ import numpy as np import solver as sol from scipy.special import gamma import matplotlib.pyplot as plt import matplotlib as mpl label_size = 14 mpl.rcParams['xtick.labelsize'] = ...
StarcoderdataPython
1675306
<reponame>TeamSprinkle/Sprinkle_Server """ DAO.py Sprinkle Created by LeeKW on 2021/02/18. """ from pymongo import MongoClient class DAO(): def __init__(self): # Database Init self.conn = MongoClient("mongodb://sprinkle:bitbitr35@localhost:27017/sprinkle").sprinkle def getConn(self): ...
StarcoderdataPython
162273
""" Writing Plugins --------------- nose supports plugins for test collection, selection, observation and reporting. There are two basic rules for plugins: * Plugin classes should subclass :class:`nose.plugins.Plugin`. * Plugins may implement any of the methods described in the class :doc:`IPluginInterface <interf...
StarcoderdataPython
153291
from tinder_py.tinder.xttp import Http class Entity: """ ABC for all Tinder entities. """ __slots__ = ["http", "id"] def __init__(self, entity: dict, http: Http): self.http = http if "_id" in entity: self.id: str = entity["_id"] elif "id" in enti...
StarcoderdataPython
4833911
<reponame>kif/freesas # -*- coding: utf-8 -*- # # Project: freesas # https://github.com/kif/freesas # # Copyright (C) 2017 European Synchrotron Radiation Facility, Grenoble, France # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docum...
StarcoderdataPython
25703
<reponame>Rory-Sullivan/yrlocationforecast """An example of accessing individual forecast variables.""" from metno_locationforecast import Place, Forecast USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast" new_york = Place("New York", 40.7, -74.0, 10) new_york_forecast = Fo...
StarcoderdataPython
1795563
<gh_stars>10-100 import unittest from PyStacks.PyStacks.template import templateCF class TestTemplate(unittest.TestCase): def test_templateCF_S3(self): resources = { 's3': { 'S3Bucket': { 'name': 'stuff.holder', 'accesscontrol': 'Public...
StarcoderdataPython
3330892
print('\033[1mCADASTRO DE PESSOAS\033[M') mais = hom = mulh = 0 while True: print('-' * 50) idade = int(input('Idade pessoa: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo da pessoa [M/F]: ')).strip().upper()[0] print('-' * 50) if idade > 18: mais += 1 if sexo ...
StarcoderdataPython
1655480
def main(): print("안녕하세요 사장님!") owner_name = input("사장님의 이름을 알려주세요:") print(owner_name + " 사장님 앞으로 멋진 식당을 만들어봐요") menu01 = input("첫번째 메뉴 이름을 정해주세요: ") menu02 = input("두번째 메뉴 이름을 정해주세요: ") menu03 = input("세번째 메뉴 이름을 정해주세요: ") print("이 식당에서는 아래와 같은 요리를 먹을수 있습니다.") print(menu...
StarcoderdataPython
1634059
# -*- coding: utf-8 -*- """ @Module SARibbonPannelOptionButton @Author ROOT @brief Pannel右下角的操作按钮 此按钮和一个action关联,使用SARibbonPannel.addOptionAction 函数用于生成此按钮,正常来说 用户并不需要直接操作此类,仅仅用于样式设计 如果一定要重载此按钮,可以通过重载 SARibbonElementCreateDelegate 的 SARibbonElementCreateDelegate.createRibbonPannelOptionButton来实现新的OptionButton ...
StarcoderdataPython
39143
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # reco hit production from RecoPPS.Local.ctppsDiamondRecHits_cfi import ctppsDiamondRecHits # local track fitting from RecoPPS.Local.ctppsDiamondLocalTracks_cfi import ctppsDiamondLocalTracks ctppsDiamondLocalReconstructionTask = cms.Task( ctppsDiamondR...
StarcoderdataPython
3270764
# 1,-2,3,-4,5 ESE 100 TAKK PRINT KRE num=1 while num<=100: if num%2==0: print(num*-1) else: print(num) num=num+1
StarcoderdataPython
1691517
<filename>postal_address/tests/__init__.py # -*- coding: utf-8 -*- # # Copyright (c) 2013-2018 Scaleway and Contributors. All Rights Reserved. # <NAME> <<EMAIL>> # # Licensed under the BSD 2-Clause License (the "License"); you may not use this # file except in compliance with the License. You ma...
StarcoderdataPython
4830501
<reponame>julianapereira99/SIB import itertools # Y is reserved to idenfify dependent variables import numpy as np import pandas as pd ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXZ' __all__ = ['label_gen', 'euclidian_distance', 'manhattan_distance', 'train_test_split', 'sig', 'add_intersect', 'l1_distance', 'l2_distance', 'min...
StarcoderdataPython
165122
<reponame>ondiiik/meteoink def localtime(sec): import time return time.localtime(sec + 946677600) def sleep_ms(ms): import time time.sleep(0.001 * ms) def ticks_ms(): import time return int(round(time.time() * 1000))
StarcoderdataPython
3308266
<gh_stars>0 from torch.nn.utils import spectral_norm import torch.nn as nn import torch class Flatten(nn.Module): """ Flattens an input value into size (batch_size, -1) """ @staticmethod def forward(x: torch.Tensor): """ Flattens an input value into size (batch_size, -1) ...
StarcoderdataPython
3369693
import argparse import os import json import fnmatch import re import yaml import glob import shutil LEGACY_SOURCE_FOLDER = "legacy/docs-ref-autogen" TARGET_SOURCE_FOLDER = "docs-ref-autogen" root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), "..")) def check_against_targeted_namespaces(test_line, n...
StarcoderdataPython
3390291
<gh_stars>0 a = int(input()) b = int(input()) c = int(input()) if (a % 2 == 0 or b % 2 == 0 or c % 2 == 0) \ and (a % 2 == 1 or b % 2 == 1 or c % 2 == 1): print("YES") else: print("NO")
StarcoderdataPython
3380528
<reponame>gridsum/IML-predictor- from .error import ErrorCode class PredictSuccessResponse: def __init__(self, memory_limit=None, error_code=ErrorCode.SUCCESS): self.mem = memory_limit self.error_code = error_code def get_response(self): return self.__dict__ class ModelBuildResponse...
StarcoderdataPython
1681517
<reponame>illuin-tech/opyoid from typing import Any, Type, TypeVar, Union, cast from .named import Named InjectedT = TypeVar("InjectedT", bound=Any) EMPTY = object() def get_class_full_name(klass: Union[Type, str]) -> str: if isinstance(klass, str): return klass if isinstance(klass, type) and issubc...
StarcoderdataPython
4826265
<filename>leetcode/graphs/all_paths_source_target.py # link: https://leetcode.com/problems/all-paths-from-source-to-target/ class Solution(object): def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ target_node= len(graph)-1 ...
StarcoderdataPython
1749090
# coding: utf-8 import numpy as np import tensorflow as tf from tensorflow.contrib.rnn import RNNCell from tensorflow.python.ops import rnn_cell_impl #from tensorflow.contrib.data.python.util import nest from tensorflow.contrib.framework import nest from tensorflow.contrib.seq2seq.python.ops.attention_wrapper import _b...
StarcoderdataPython
4823724
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-15 04:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('email_notifications', '0003_auto_20180206_1733'), ] ...
StarcoderdataPython
4984
<reponame>fintelia/habitationi #!/usr/bin/python # Copyright 2019 <NAME> # # 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 requ...
StarcoderdataPython
1643049
""" LibreASR source code """
StarcoderdataPython
1761117
''' ABC company is interested to computerize the salary payments of their employees DA: 80% Basic pay HRA: 30% Basic Pay PF: 12% of Basic Pay Input: Basic Pay Process: Salary=DA+HRA+Basic Pay-PF Output: Salary ''' basicpay=float(input("Enter Basic pay: ")) #salary is basicpay+DA+HRA-PF salary=basicpay+basicpay*0.80+b...
StarcoderdataPython
1662365
import argparse import random def main(): parser = argparse.ArgumentParser() parser.add_argument('--num-cpus', '-c', default=32, type=int, help='number of routers, default is 32') parser.add_argument('--mesh-rows', '-d', default=8, type=int, help='number of ...
StarcoderdataPython
3250332
<filename>StatsBot/test.py import discord import json import pandas as pd import numpy as np import pandasql as ps from datapuller import DataPuller from nba_search import * with open("account.info", encoding="utf-8") as f: accountDICT = json.loads(f.read()) info_fields = {'season': None, 'team':...
StarcoderdataPython
36681
<gh_stars>0 #!/usr/bin/env python import rospy import threading from ca_msgs.msg import Bumper from geometry_msgs.msg import Twist, Vector3 class StateMachine(object): def __init__(self): self.pub = rospy.Publisher("/cmd_vel", Twist, queue_size=10) self.goal_queue = [] def rotate(self, ang_vel): self...
StarcoderdataPython
17361
<reponame>Very1Fake/monitor<gh_stars>0 from typing import Dict _codes: Dict[int, str] = { # Debug (1xxxx) # System (100xx) 10000: 'Test debug', # Pipe (103xx) 10301: 'Reindexing parser', # Resolver (109xx) 10901: 'Executing catalog', 10902: 'Executing target', 10903: 'Catalog exec...
StarcoderdataPython
59328
import string from .network import g2p_network graphemes = ["<pad>", "<unk>", "</s>"] + list(string.ascii_lowercase) grapheme_to_index = {x: i for i, x in enumerate(graphemes)} UNKNOWN_GRAPHEME = grapheme_to_index["<unk>"] END_OF_WORD = grapheme_to_index["</s>"] phonemes = [ "<pad>", "<unk>", "<s>", ...
StarcoderdataPython
1677765
#!/usr/local/bin/python3 print ("hello world")
StarcoderdataPython
1774358
<filename>project1/src/util/modifiers.py # -*- coding: utf-8 -*- import itertools import numpy as np import implementations as impl import costs def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True): """Generate a minibatch iterator for a dataset. Takes as input two iterables (here the output desire...
StarcoderdataPython
29892
""" Freyr - A Free stock API """ import random import requests.utils header = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:83.0) Gecko/20100101 Firefox/83.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:83.0)...
StarcoderdataPython
1735414
""" @author: yuhao.he @contact: <<EMAIL>> @version: 0.0.1 @file: models.py @time: 2021/11/2 21:02 """ from tortoise import fields from src.utils.admin import ManyToOneModel, AbstractModel, AdminMixin, AdminMeta class Command(AbstractModel, ManyToOneModel, AdminMixin): class Admin(AdminMeta): label = "命令"...
StarcoderdataPython
3345242
### 'FileImport' import pretty pretty.arrowify(james="RITS", matt="CMIC") ### 'ModuleVariable' pretty.arrow="=>" pretty.arrowify(beauty=True, cause="consequence") ### 'ImportFrom' import math math.sin(math.pi) from math import sin sin(math.pi) from math import * sin(pi) ### 'ImportAlias' import math as m m.co...
StarcoderdataPython
3327828
<filename>examples/example_l2_routing.py #! /usr/bin/env python # -*- coding: utf-8 -*- from scapy.all import * # DST_MAC = "00:11:22:33:44:55" DST_MAC = "00:16:3e:0c:53:93" SRC_MAC = "00:00:70:5b:c7:34" DST_IPV4 = "192.168.127.12" SRC_IPV4 = "10.0.0.1" DST_IPV6 = "2001:db8:100::1" SRC_IPV6 = "2001:db8:100::2" DST_T...
StarcoderdataPython
1647986
"""Resamples a GeoTIFF file to make a KML and a PNG browse image for ASF""" import argparse import logging import os import sys from osgeo import gdal from hyp3lib.resample_geotiff import resample_geotiff def makeAsfBrowse(geotiff: str, base_name: str, use_nn=False, width: int = 2048): """ Make a KML and P...
StarcoderdataPython
4821317
<reponame>mikedingjan/ecs-deplojo import copy import json import operator import os.path import typing from string import Template class TaskDefinition: """A TaskDefinition exists out of a set of containers.""" def __init__(self, data): self._data = data @classmethod def load(cls, fh) -> "Ta...
StarcoderdataPython
1640503
<reponame>mikecokina/pypex import numpy as np from pypex.base import shape from pypex.poly2d.intersection import linter from pypex.base.conf import ROUND_PRECISION class Line(shape.Shape2D): __intersect__ = ['INTERSECT'] __overlapping__ = ['OVERLAP'] def __str__(self): return "Line: ...
StarcoderdataPython
181557
from typing import Tuple import numpy as np import torch import torch.nn as nn from rlcycle.common.abstract.action_selector import ActionSelector from rlcycle.common.utils.common_utils import np2tensor class SACActionSelector(ActionSelector): """Action selector for (vanilla) DDPG policy Attributes: ...
StarcoderdataPython
197945
<gh_stars>100-1000 # -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANT...
StarcoderdataPython
1739022
<filename>arborlife/eventloop.py import enum import logging import sys from datetime import datetime, timedelta from arborlife import config, observer from collections import namedtuple logger = logging.getLogger(__name__) ONE_HOUR = timedelta(hours=1) Epoch = namedtuple("Epoch", "event dtime",) class Event(enum....
StarcoderdataPython
3240543
<reponame>felixdittrich92/DeepLearning-tensorflow-keras import numpy as np import matplotlib.pyplot as plt import seaborn as sns from tensorflow.keras.models import * from tensorflow.keras.layers import * from tensorflow.keras.optimizers import * def f(x): return x**2 + x + 10 x = np.linspace(start=-10.0, stop=1...
StarcoderdataPython
4809932
<gh_stars>1-10 from test import TestProtocolCase, bad_client_wrong_broadcast, bad_client_output_vector import random import time class TestProtocol(TestProtocolCase): def test_001_cheat_in_sending_different_keys(self): good_threads = self.make_clients_threads(with_print = True, number_of_clients = self.nu...
StarcoderdataPython
3359184
import sys sys.path.append('../gen-py') from media_service import TextService from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol import random import string def main(): # Make socket socket = TSocket.TSocket("ath...
StarcoderdataPython