text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_prefix|># repo: TitorX/gkit path: /gkit/core/raster.py
import numpy as np
from numpy.ma import MaskedArray
from osgeo import gdal, osr, ogr
from scipy.ndimage.filters import generic_filter as gf
import gkit as gk
# Data type mapping between numpy and gdal.
TYPE = {
np.dtype(np.int8): gdal.GDT_Byte,
np... | code_fim | hard | {
"lang": "python",
"repo": "TitorX/gkit",
"path": "/gkit/core/raster.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if if_show:
plt.colorbar(orientation='horizontal')
plt.show()
def show(self, *args, **kwargs):
"""A shortcut of :meth:`self.plot`. Just set ``if_show=True``.
"""
kwargs['if_show'] = True
self.plot(*args, **kwargs)
def rolling(self, ... | code_fim | hard | {
"lang": "python",
"repo": "TitorX/gkit",
"path": "/gkit/core/raster.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Quan3Xin/tf_estimator_demo path: /test_estimator.py
import os
import tensorflow as tf
import numpy as np
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
def my_init_fn():
# 一个单独的输入
x = np.arange(100, dtype=np.float32) / 100.0
... | code_fim | hard | {
"lang": "python",
"repo": "Quan3Xin/tf_estimator_demo",
"path": "/test_estimator.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def my_model_fn(features, labels, mode, params):
# 直接使用 features & labels
# 构建模型
logits = tf.keras.layers.Dense(1, input_shape=((1, )))
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {'logits': logits}
return tf.estimator.EstimatorSpec(mode, predictions=predictio... | code_fim | medium | {
"lang": "python",
"repo": "Quan3Xin/tf_estimator_demo",
"path": "/test_estimator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {'logits': logits}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
# 获取损失函数
if labels is not None:
labels = tf.cast(tf.reshape(labels, [-1, 1]), dtype=tf.float32)
loss = tf.losses.mean_squared... | code_fim | hard | {
"lang": "python",
"repo": "Quan3Xin/tf_estimator_demo",
"path": "/test_estimator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: AndyMacDonald/YearlyProblem path: /yearly_problem2.py
#!/usr/bin/python
# Yearly problem, consume 1 digit at a time, construct trees and evaluate when all digits are consumed
import argparse
solutions = {}
def list_to_string(l):
return ''.join(map(str,l))
def list_to_int(l):
return int(li... | code_fim | hard | {
"lang": "python",
"repo": "AndyMacDonald/YearlyProblem",
"path": "/yearly_problem2.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return new_trees
def add_digit_to_trees(trees, d):
new_trees = []
for t in trees:
new_trees.extend(add_digit_to_tree(t, d))
return new_trees
def solve(year):
trees = []
while year > 0:
d = year % 10
year = year / 10
if len(trees) == 0:
trees = [[[d]]]
else:
... | code_fim | hard | {
"lang": "python",
"repo": "AndyMacDonald/YearlyProblem",
"path": "/yearly_problem2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Add new subtrees
for op in ['+', '-', '*', '/', '^']:
new_trees.append([op, [ld], tree])
if not commutative(op):
new_trees.append([op, tree, [ld]])
return new_trees
def add_digit_to_trees(trees, d):
new_trees = []
for t in trees:
new_trees.extend(add_digit_to_tree(t, d))
... | code_fim | hard | {
"lang": "python",
"repo": "AndyMacDonald/YearlyProblem",
"path": "/yearly_problem2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Azure/azure-cli path: /src/azure-cli/azure/cli/command_modules/keyvault/vendored_sdks/azure_keyvault_t1/key_vault_client.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the ... | code_fim | hard | {
"lang": "python",
"repo": "Azure/azure-cli",
"path": "/src/azure-cli/azure/cli/command_modules/keyvault/vendored_sdks/azure_keyvault_t1/key_vault_client.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if api_version == v7_2_VERSION:
from .v7_2 import models as implModels
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return implModels
def _get_client_impl(self):
"""
Get the versioned client imple... | code_fim | hard | {
"lang": "python",
"repo": "Azure/azure-cli",
"path": "/src/azure-cli/azure/cli/command_modules/keyvault/vendored_sdks/azure_keyvault_t1/key_vault_client.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> purchase_re = re.compile(r'^(?:Karta|Карта) ([0-9]+?): (.+?), (.+?) ([0-9.]+) (.+?)[.,] (?:(?:комиссия|komissiya) D([0-9.]+) (.+?)\. )?(?:(.+?)\. )? *(?:Доступно|Dostupno) ([0-9.]+) (.+?)\.')
for transaction in trans_list:
try:
values = purchase_re.match(transaction['body'])
... | code_fim | hard | {
"lang": "python",
"repo": "mk-99/sbermaster",
"path": "/vestabank.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mk-99/sbermaster path: /vestabank.py
#!/usr/local/bin/python3
import re, pprint
from decimal import Decimal
from dateutil.parser import parse as date_parse
def stop_words(message):
for word in ('карта', 'karta'):
if word in message['body'].lower():
for word in ('otrazhe... | code_fim | hard | {
"lang": "python",
"repo": "mk-99/sbermaster",
"path": "/vestabank.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># --------------
#Code starts here
race_0=census[census[:,2]==0]
race_1=census[census[:,2]==1]
race_2=census[census[:,2]==2]
race_3=census[census[:,2]==3]
race_4=census[census[:,2]==4]
len_0=len(race_0)
len_1=len(race_1)
len_2=len(race_2)
len_3=len(race_3)
len_4=len(race_4)
length=[len_0,len_... | code_fim | medium | {
"lang": "python",
"repo": "gurman01/ga-learner-dsmp-repo",
"path": "/Census/code.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gurman01/ga-learner-dsmp-repo path: /Census/code.py
# --------------
# Importing header files
import numpy as np
census=[]
# Path of the file has been stored in variable called 'path'
data = np.genfromtxt(path, delimiter=",", skip_header=1)
#New record
new_record=np.array([[50, 9, 4, 1... | code_fim | medium | {
"lang": "python",
"repo": "gurman01/ga-learner-dsmp-repo",
"path": "/Census/code.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: AvantikaDG/MET-CS777 path: /Spark-Example-FlightsData/flights_example.py
# https://s3.amazonaws.com/metcs777/flights.csv.bz2
# s3n://metcs777/flights.csv.bz2
# lines = sc.textFile("file:///home/kia/Data/Collected-Datasets/flight-delays/flight-delays/flights.csv")
lines = sc.textFile("s3://metcs... | code_fim | hard | {
"lang": "python",
"repo": "AvantikaDG/MET-CS777",
"path": "/Spark-Example-FlightsData/flights_example.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
#Q11 Which date of year has the highest rate of flight cancellations?
# Rate of flight cancellation is calculated by deviding number of canceled flights by total number of flights.
#Q12 Calculate the number of flights to each destination state
# For each carrier, for which state do they have the larg... | code_fim | hard | {
"lang": "python",
"repo": "AvantikaDG/MET-CS777",
"path": "/Spark-Example-FlightsData/flights_example.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
exit(main(sys.argv))<|fim_prefix|># repo: brcrista/Python-Package-Template path: /placeholder_package_name/__main__.py
"""
This file makes a module runnable with `python -m`.
"""
import sys
from placeholder_package_name.console import Console
def main(args):
console ... | code_fim | medium | {
"lang": "python",
"repo": "brcrista/Python-Package-Template",
"path": "/placeholder_package_name/__main__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> console = Console()
try:
return 0
except Exception as ex:
console.error(ex)
return 1
if __name__ == '__main__':
exit(main(sys.argv))<|fim_prefix|># repo: brcrista/Python-Package-Template path: /placeholder_package_name/__main__.py
"""
This file makes a module run... | code_fim | medium | {
"lang": "python",
"repo": "brcrista/Python-Package-Template",
"path": "/placeholder_package_name/__main__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: brcrista/Python-Package-Template path: /placeholder_package_name/__main__.py
"""
This file makes a module runnable with `python -m`.
"""
<|fim_suffix|> console = Console()
try:
return 0
except Exception as ex:
console.error(ex)
return 1
if __name__ == '__main... | code_fim | medium | {
"lang": "python",
"repo": "brcrista/Python-Package-Template",
"path": "/placeholder_package_name/__main__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Returns:
Numpy array of the tokenization sentences with masking,
infos,
stats
# Raises:
ValueError: When maximum length is not set and cannot be inferred.
"""
if max_sentences is None and not hasattr(sentences, '__len__'):... | code_fim | hard | {
"lang": "python",
"repo": "hon9g/Text-to-Color",
"path": "/deepmoji/sentence_tokenizer.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # For standard word generators all sentences should be tokenized
# this is not necessarily the case for custom wordgenerators as they
# may filter the sentences etc.
if not self.uses_custom_wordgen and not self.ignore_sentences_with_only_custom:
assert len(sente... | code_fim | hard | {
"lang": "python",
"repo": "hon9g/Text-to-Color",
"path": "/deepmoji/sentence_tokenizer.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hon9g/Text-to-Color path: /deepmoji/sentence_tokenizer.py
'''
Provides functionality for converting a given list of tokens (words) into
numbers, according to the given vocabulary.
'''
from __future__ import print_function, division
import numpy as np
from deepmoji.word_generator import WordGener... | code_fim | hard | {
"lang": "python",
"repo": "hon9g/Text-to-Color",
"path": "/deepmoji/sentence_tokenizer.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jgoodknight/spectroscopy path: /src/Spacetime.py
self.energyUnit = numberOfWavenumbersInEnergyUnit #wavenumbers
self.energyScaleWavenumbers = self.energyUnit
self.lengthScaleMeters = self.SCALE_LENGTH
self.timeScaleSeconds = self.SCALE_TIME
self.energyScaleJoul... | code_fim | hard | {
"lang": "python",
"repo": "jgoodknight/spectroscopy",
"path": "/src/Spacetime.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Helper function for the amplitude setting function
[f(x), g(y), ...]
additive=True => F(x, y, ...) = f(x) + g(y) + ...
additive=False => F(x, y, ...) = f(x) * g(y) * ..."""
output = self.functionSpaceZero()
if additive:
initialValue = 0.0
... | code_fim | hard | {
"lang": "python",
"repo": "jgoodknight/spectroscopy",
"path": "/src/Spacetime.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return (newX, newY, newZ)
def randomRotateTuple(self, tupleToRotate):
"Returns a random angle and a copy of the tuple, rotated by three random angles in 3-space"
xAngle = np.random.uniform(0.0, 2.0 * np.pi )
yAngle = np.random.uniform(0.0, 2.0 * np.pi )
zAngle ... | code_fim | hard | {
"lang": "python",
"repo": "jgoodknight/spectroscopy",
"path": "/src/Spacetime.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_is_okay_to_run(self):
with mock.patch(('ndscheduler.corescheduler.core.base.'
'BaseScheduler.is_okay_to_run')) as mock_should_run:
mock_should_run.return_value = True
job_stores = {'default': DatastoreSqlite.get_instance()}
... | code_fim | hard | {
"lang": "python",
"repo": "Nextdoor/ndscheduler",
"path": "/ndscheduler/corescheduler/core/base_test.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Nextdoor/ndscheduler path: /ndscheduler/corescheduler/core/base_test.py
"""Unit tests for BaseScheduler class."""
import unittest
import mock
from ndscheduler.corescheduler.core.base import BaseScheduler
from ndscheduler.corescheduler.datastore.providers.sqlite import DatastoreSqlite
class B... | code_fim | hard | {
"lang": "python",
"repo": "Nextdoor/ndscheduler",
"path": "/ndscheduler/corescheduler/core/base_test.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: neurodata/brainlit path: /brainlit/algorithms/connect_fragments/tests/test_viterbrain.py
from asyncio import create_task
import pytest
import zarr
from pathlib import Path
import numpy as np
from brainlit.algorithms.connect_fragments.viterbrain import (
ViterBrain,
explain_viterbrain,
)
f... | code_fim | hard | {
"lang": "python",
"repo": "neurodata/brainlit",
"path": "/brainlit/algorithms/connect_fragments/tests/test_viterbrain.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> cost = vb.frag_frag_dist_coord(
pt1=[0, 0, 0], orientation1=[1, 0, 0], pt2=[2, 0, 0], orientation2=[-1, 0, 0]
)
assert cost == np.inf
def test_frag_frag_dist_simple(create_vb):
vb = create_vb
cost = vb.frag_frag_dist_simple(state1=0, state2=2)
assert cost == 24 + 6**2
... | code_fim | hard | {
"lang": "python",
"repo": "neurodata/brainlit",
"path": "/brainlit/algorithms/connect_fragments/tests/test_viterbrain.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hanweiwei514/Visual-fixation-system path: /SysScreen.py
import os
from flask import Flask
from flask import render_template
from flask import request, url_for
import json
from templates.UiBar import UiBar
from templates.UiPie import UiPie
from eyeDataHandler.dataHandler import handle_result_img
i... | code_fim | hard | {
"lang": "python",
"repo": "hanweiwei514/Visual-fixation-system",
"path": "/SysScreen.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>@app.route('/show_progress')
def show_progress():
num = 0
path = os.path.join(basedir, 'upload/images')
file_list = os.listdir(path)
for i in range(0, len(file_list)):
file_path = os.path.join(path,file_list[i] )
if os.path.isfile(file_path):
num = num + 1
p... | code_fim | hard | {
"lang": "python",
"repo": "hanweiwei514/Visual-fixation-system",
"path": "/SysScreen.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mdcollins80/PAW-api path: /paw2018/nflgames/serializers.py
from .models import Game
from rest_framework import serializers
from paw2018.nflteams.serializers import TeamNameSerializer
class GameSerializer(serializers.ModelSerializer):
away_team = TeamNameSerializer(read_only=True)
home_te... | code_fim | hard | {
"lang": "python",
"repo": "mdcollins80/PAW-api",
"path": "/paw2018/nflgames/serializers.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> class Meta:
model = Game
fields = ('id', '__str__', 'week_num', 'weekday', 'kickoff', 'season',
'home_team', 'home_team_score', 'away_team', 'away_team_score',
'winner')
class GameIDSerializer(serializers.ModelSerializer):
class Meta:
mo... | code_fim | medium | {
"lang": "python",
"repo": "mdcollins80/PAW-api",
"path": "/paw2018/nflgames/serializers.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>copyfile('build.py', TMP_BUILD)
# COMPILE CODE AT MULTIPLE RESOLUTIONS USING SEPARATE BUILD FILE
for n in range(len(RES)):
util.change_cparm('N1TOT', RES[n], TMP_BUILD)
util.change_cparm('N2TOT', RES[n], TMP_BUILD)
call([sys.executable, TMP_BUILD, '-dir', TMP_DIR])
call(['cp', os.path.join(os.get... | code_fim | hard | {
"lang": "python",
"repo": "lanl/nubhlight",
"path": "/test/bondi.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lanl/nubhlight path: /test/bondi.py
################################################################################
# #
# BONDI INFLOW #
# ... | code_fim | hard | {
"lang": "python",
"repo": "lanl/nubhlight",
"path": "/test/bondi.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> ax = fig.add_subplot(1,1,1)
ax.plot(RES, L1, marker='s', label='RHO')
amp = 1.
ax.plot([RES[0]/2., RES[-1]*2.],
10.*amp*np.asarray([RES[0]/2., RES[-1]*2.])**-2.,
color='k', linestyle='--', label='N^-2')
plt.xscale('log', basex=2); plt.yscale('log')
plt.xlim([RES[0]/np.sqrt(2.), RES[-1... | code_fim | hard | {
"lang": "python",
"repo": "lanl/nubhlight",
"path": "/test/bondi.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sanghyun-son/srwarp path: /src/data/sr/div2k/base.py
from os import path
from data import common
from data.sr import dataclass
_parent_class = dataclass.SRData
class DIV2K(_parent_class):
'''
DIV2K mean:
R: 0.4488
G: 0.4371
B: 0.4040
'''
<|fim_suffix|> ... | code_fim | hard | {
"lang": "python",
"repo": "sanghyun-son/srwarp",
"path": "/src/data/sr/div2k/base.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def apath(self):
return path.join(self.dpath, 'DIV2K')
def get_path(self, degradation, scale):
if scale.is_integer():
scale = int(scale)
if not (self.train or self.tval):
split = 'valid'
else:
split = 'train'
path_hr = ... | code_fim | hard | {
"lang": "python",
"repo": "sanghyun-son/srwarp",
"path": "/src/data/sr/div2k/base.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tdgunes/pyplyn path: /pyplyn/outputs.py
# -*- coding: utf-8 -*-
"""
pyplyn.outputs
~~~~~~~~~~
Some useful output classes
Author: Taha Dogan Gunes
License: MIT, see LICENSE for more details.
"""
from . import elements
class Writer(elements.OutPypElement):
<|fim_suffix|>class LineWriter(Writer... | code_fim | hard | {
"lang": "python",
"repo": "tdgunes/pyplyn",
"path": "/pyplyn/outputs.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class Gatherer(elements.OutPypElement):
"""
Outputs are gathered in to the pool inside this gatherer class
after pipe is totally flowed, you can access the data by accesing to
self.pool list
"""
def __init__(self):
self.pool = []
def extract(self, data):
self.p... | code_fim | hard | {
"lang": "python",
"repo": "tdgunes/pyplyn",
"path": "/pyplyn/outputs.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: apanangadan/autograde-github-classroom path: /rollback-to-deadline.py
#! /usr/bin/env python3
#Acknowledgment: https://github.com/Sirusblk
import os, shutil, subprocess
from argparse import ArgumentParser
DATE_STRING = '2018-02-18 01:00 PST'
#DATE_STRING = '2018-04-30 01:00 PST'
def rollback_... | code_fim | hard | {
"lang": "python",
"repo": "apanangadan/autograde-github-classroom",
"path": "/rollback-to-deadline.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def rollback_all():
""" Create parser for command line arguments """
parser = ArgumentParser(
usage=u'python -m rollback-to-deadline -h',
description=' rollback all submissions to last commit before assignment deadline')
parser.add_argument('-d', '--dest', help=u'Destin... | code_fim | hard | {
"lang": "python",
"repo": "apanangadan/autograde-github-classroom",
"path": "/rollback-to-deadline.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># Create an app
app = Flask(__name__)
##########################################################
# Decorate Flask Routes
##########################################################
# 3. Define the route
@app.route("/")
def home():
print("Server received request for 'home' page...")
return "Welcom... | code_fim | hard | {
"lang": "python",
"repo": "Soup-or-Salad/Project_NBA",
"path": "/testapp.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Soup-or-Salad/Project_NBA path: /testapp.py
# import dependencies
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
# Import pgadmin password from p... | code_fim | medium | {
"lang": "python",
"repo": "Soup-or-Salad/Project_NBA",
"path": "/testapp.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hamzajaved05/text2map path: /trainingbh.py
"""
Author: Hamza
Dated: 20.04.2019
Project: texttomap
"""
import argparse
import pickle
import torch.optim as optim
from math import ceil
from tensorboardX import SummaryWriter
import pandas as pd
from torch.utils.data import DataLoader
from util.loade... | code_fim | hard | {
"lang": "python",
"repo": "hamzajaved05/text2map",
"path": "/trainingbh.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>logging.basicConfig(filename='models_bh/' + args.logid + args.model + '.log', filemode='w', format='%(message)s')
logger = logging.getLogger('dummy')
loggersparse = logging.getLogger("dummy2")
logger.addHandler(logging.FileHandler('models_bh/' + args.logid + args.model + '.log'))
loggersparse.addHandler(l... | code_fim | hard | {
"lang": "python",
"repo": "hamzajaved05/text2map",
"path": "/trainingbh.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>valid_class = validation(klass_v, words_v, words_sparse_v, jpgs_v, args.impath, Network, Writer)
optimizer = optim.Adam(Network.parameters(), lr=args.lr)
epochs = args.epoch
train_accuracy = []
train_loss = []
validation_accuracy = []
validation_loss = []
# early_stop = EarlyStopping(patience=100, verbo... | code_fim | hard | {
"lang": "python",
"repo": "hamzajaved05/text2map",
"path": "/trainingbh.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: marco-c/gecko-dev-wordified path: /testing/web-platform/tests/tools/ci/tc/taskgraph.py
#
mypy
:
allow
-
untyped
-
defs
import
json
import
os
import
re
from
collections
import
OrderedDict
from
copy
import
deepcopy
import
yaml
here
=
os
.
path
.
dirname
(
__file__
)
def
first
(
iterable
)
:
#
... | code_fim | hard | {
"lang": "python",
"repo": "marco-c/gecko-dev-wordified",
"path": "/testing/web-platform/tests/tools/ci/tc/taskgraph.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>return
rv
def
load_tasks
(
tasks_data
)
:
map_resolved_tasks
=
OrderedDict
(
)
tasks
=
[
]
for
task
in
tasks_data
[
"
tasks
"
]
:
if
len
(
task
.
keys
(
)
)
!
=
1
:
raise
ValueError
(
"
Each
task
must
be
an
object
with
a
single
property
"
)
for
task
in
expand_... | code_fim | hard | {
"lang": "python",
"repo": "marco-c/gecko-dev-wordified",
"path": "/testing/web-platform/tests/tools/ci/tc/taskgraph.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> ...
@abstractmethod
def get_all_variables(self) -> T:
...
@property
def variables(self) -> VariableSet:
return self._variables
@property
def groups(self) -> GroupSet:
return self._groups<|fim_prefix|># repo: drawjk705/the_census path: /the_census... | code_fim | medium | {
"lang": "python",
"repo": "drawjk705/the_census",
"path": "/the_census/_variables/repository/interface.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: drawjk705/the_census path: /the_census/_variables/repository/interface.py
from abc import ABC, abstractmethod
from typing import Generic, TypeVar
from the_census._variables.models import GroupCode
from the_census._variables.repository.models import GroupSet, VariableSet
T = TypeVar("T")
class... | code_fim | hard | {
"lang": "python",
"repo": "drawjk705/the_census",
"path": "/the_census/_variables/repository/interface.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def transform(self, x):
assert isinstance(x, Mapping)
typ = type(x)
return typ(item
for k, v in x.items()
for item in self._transform(
v, prefix=k.replace("\\", "\\\\").replace(".", "\\.")
).items()... | code_fim | hard | {
"lang": "python",
"repo": "polyrize/neo4j-python-driver",
"path": "/src/neo4j/_data.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: polyrize/neo4j-python-driver path: /src/neo4j/_data.py
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [https://neo4j.com]
#
# This file is part of Neo4j.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | code_fim | hard | {
"lang": "python",
"repo": "polyrize/neo4j-python-driver",
"path": "/src/neo4j/_data.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """ Return the fields of the record as a list of key and value tuples
:returns: a list of value tuples
"""
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
... | code_fim | hard | {
"lang": "python",
"repo": "polyrize/neo4j-python-driver",
"path": "/src/neo4j/_data.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Write components table to be pasted into 'COMPONENTS.md' and dependencies.xml for BDS scan
dependencies_listing_content = textwrap.dedent("""\
| Component | Version | Repo/Website | License |
| --------- | ------- | ------------ | ------- |
""")
for dep in all_deps_data:
... | code_fim | hard | {
"lang": "python",
"repo": "seriva/epiphany",
"path": "/.devcontainer/gen-dependency-info.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: seriva/epiphany path: /.devcontainer/gen-dependency-info.py
import sys
import json
import os
import urllib.request
import logging
from functools import reduce
from typing import Set, List, Dict
import pkg_resources
import textwrap
def get_dependencies_from_requirements() -> Set[str]:
req = ... | code_fim | hard | {
"lang": "python",
"repo": "seriva/epiphany",
"path": "/.devcontainer/gen-dependency-info.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@BundleActivator
class Activator(object):
"""
The bundle activator
"""
def __init__(self):
"""
Sets up members
"""
self.__registration = None
def start(self, context):
"""
Bundle started
@param context The bundle context
... | code_fim | hard | {
"lang": "python",
"repo": "tcalmant/ipopo",
"path": "/samples/remote/provider.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Register the service with the Java specification
self.__registration = context.register_service(
SERVICE_SPECIFICATION, HelloWorldImpl(), props
)
def stop(self, context):
"""
Bundle stopped
@param context The bundle context
"""
... | code_fim | hard | {
"lang": "python",
"repo": "tcalmant/ipopo",
"path": "/samples/remote/provider.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tcalmant/ipopo path: /samples/remote/provider.py
#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Greeting service provider
:author: Thomas Calmant
:copyright: Copyright 2020, Thomas Calmant
:license: Apache License 2.0
..
Copyright 2020 Thomas Calmant
Licensed under the Apache L... | code_fim | hard | {
"lang": "python",
"repo": "tcalmant/ipopo",
"path": "/samples/remote/provider.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>number was", missingno)
Arr = [1,2,3,5,6,7,8,9,10]
n = 10
MissingNoInTheRange(Arr, n)<|fim_prefix|># repo: aparnamaleth/CodingPractice path: /Random/MissingNo.py
def MissingNoInTheRange(Arr, n):
total = 0
a = len(Arr)
for i in range (a):
tota<|fim_middle|>l = total + Arr[i]
actualsum = n/2*(11)
m... | code_fim | medium | {
"lang": "python",
"repo": "aparnamaleth/CodingPractice",
"path": "/Random/MissingNo.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aparnamaleth/CodingPractice path: /Random/MissingNo.py
def MissingNoInTheRange(Arr, n):
total = 0
a = len(Arr)
for i in range (a):
tota<|fim_suffix|>number was", missingno)
Arr = [1,2,3,5,6,7,8,9,10]
n = 10
MissingNoInTheRange(Arr, n)<|fim_middle|>l = total + Arr[i]
actualsum = n/2*(11)
m... | code_fim | medium | {
"lang": "python",
"repo": "aparnamaleth/CodingPractice",
"path": "/Random/MissingNo.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return full_grad_diff / float(n)
######################################################################
def func_val_bin_class_loss_2(n, XYw_bias):
"""! Compute the objective value of loss function 2
\f$\ell_2(Y(Xw+b)) := \left(1 - \frac{1}{1 + \exp[-Y(Xw+b)]}\right)^2 \f$
for a given \f$ \omega ... | code_fim | hard | {
"lang": "python",
"repo": "xiaogaogaoxiao/StochasticProximalMethods",
"path": "/python_src/util_BinClass.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: xiaogaogaoxiao/StochasticProximalMethods path: /python_src/util_BinClass.py
ambda \|.\|_1} = {arg\min_x}\left\{\|.\|_1^2 + \frac{1}{2\lambda}\|x - w\|^2\right\} \f$
Parameters
----------
@param w : input vector
@param lamb : penalty paramemeter
Returns
-------
@retval : perform sof... | code_fim | hard | {
"lang": "python",
"repo": "xiaogaogaoxiao/StochasticProximalMethods",
"path": "/python_src/util_BinClass.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: xiaogaogaoxiao/StochasticProximalMethods path: /python_src/util_BinClass.py
:
"""! Compute accuracy
Parameters
----------
@param n : sample size
@param d : number of features
@param X : input data
@param Y : input label
@param bias : bias vector
@param w : input vector
@param nnzX : av... | code_fim | hard | {
"lang": "python",
"repo": "xiaogaogaoxiao/StochasticProximalMethods",
"path": "/python_src/util_BinClass.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|># Generates and return the empirical distribution of m-grams.
def get_empirical_distribution(text, m):
ed = {}
grams = generate_grams(text, m)
for g in grams:
if g in ed:
ed[g] = ed[g] + 1
else:
ed[g] = 1
for g in ed:
ed[g] = ed[g] / len(gram... | code_fim | hard | {
"lang": "python",
"repo": "castuloramirez/TextFrequencyAnalysis",
"path": "/TextFrequencyAnalysis.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: castuloramirez/TextFrequencyAnalysis path: /TextFrequencyAnalysis.py
import math
import re
import string
import sys
from collections import Counter
import matplotlib.pyplot as plt
import pandas
# Shows the list of functions that can be run, and the user chooses one of them.
def option_menu():
... | code_fim | hard | {
"lang": "python",
"repo": "castuloramirez/TextFrequencyAnalysis",
"path": "/TextFrequencyAnalysis.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> counts = Counter(data)
df = pandas.DataFrame.from_dict(counts, orient='index')
df.plot(kind='bar', color='blue', legend=None)
plt.title("Character Frequencies")
plt.ylabel('Frequency')
plt.xlabel('Characters')
plt.savefig('frequency_histogram.pdf')
plt.show()
# Generates ... | code_fim | hard | {
"lang": "python",
"repo": "castuloramirez/TextFrequencyAnalysis",
"path": "/TextFrequencyAnalysis.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: J-CPelletier/webcomix path: /webcomix/exceptions.py
class CrawlerBlocked(Exception):
pass
<|fim_suffix|> def __init__(self, failed_url, next_page_xpath):
self.failed_url = failed_url
self.next_page_xpath = next_page_xpath<|fim_middle|>class NextLinkNotFound(Exception):
| code_fim | easy | {
"lang": "python",
"repo": "J-CPelletier/webcomix",
"path": "/webcomix/exceptions.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __init__(self, failed_url, next_page_xpath):
self.failed_url = failed_url
self.next_page_xpath = next_page_xpath<|fim_prefix|># repo: J-CPelletier/webcomix path: /webcomix/exceptions.py
class CrawlerBlocked(Exception):
pass
<|fim_middle|>
class NextLinkNotFound(Exception):
| code_fim | easy | {
"lang": "python",
"repo": "J-CPelletier/webcomix",
"path": "/webcomix/exceptions.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: emorynlp/swne path: /scripts/strip.py
import os
import glob
import json
import string
def nontext(sentence, bidx, tout=None):
curr_token = sentence[bidx]
if curr_token in {'#', '--'}:
return bidx
elif curr_token == '<':
eidx = next((i for i, token in enumerate(sent... | code_fim | hard | {
"lang": "python",
"repo": "emorynlp/swne",
"path": "/scripts/strip.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if new_sentence and (len(new_sentence) > 2 or any(e[0] == sid for e in old_entities)):
map_sentences[sid] = len(new_sentences)
new_sentences.append(new_sentence)
for old_entity in old_entities:
old_sid = old_entity[0]
old_bid = o... | code_fim | hard | {
"lang": "python",
"repo": "emorynlp/swne",
"path": "/scripts/strip.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> doc['sentences_exc'] = new_sentences
doc['named_entities_exc'] = new_entities
out_file = open(os.path.join(out_dir, os.path.basename(in_file)), 'w')
json.dump(doc, out_file)
if __name__ == "__main__":
IN_DIR = '../dat/swne'
OUT_DIR = '../dat/swne_exc'
# t... | code_fim | hard | {
"lang": "python",
"repo": "emorynlp/swne",
"path": "/scripts/strip.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jzi040941/django_quiz path: /teacher/crispy_layout.py
from __future__ import unicode_literals
from random import randint
from django.template import Template
from django.template.defaultfilters import slugify
from django.template.loader import render_to_string
from crispy_forms.compatibility i... | code_fim | medium | {
"lang": "python",
"repo": "jzi040941/django_quiz",
"path": "/teacher/crispy_layout.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
extra_context = extra_context.copy() if extra_context is not None else {}
template = self.get_template_name(template_pack)
extra_context.update({
'crispy_appended... | code_fim | medium | {
"lang": "python",
"repo": "jzi040941/django_quiz",
"path": "/teacher/crispy_layout.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
mnist with plotting
"""
(train_data_node,
train_labels_node,
validation_data_node,
test_data_node,
# predictions
train_prediction,
validation_prediction,
test_prediction,
# weights
conv1_weights,
conv2_weights,
fc1_weights,
fc2_weights,
... | code_fim | hard | {
"lang": "python",
"repo": "KEVINYZY/tdb",
"path": "/tdb/tests/test_mnist.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: KEVINYZY/tdb path: /tdb/tests/test_mnist.py
"""
HT debugging on a simple LeNET-5 convolutional model
"""
import numpy as np
import sys
import tensorflow as tf
import unittest
import tdb
from tdb.examples import mnist, viz
class TestMNIST(unittest.TestCase):
def test_1(self):
# single pas... | code_fim | hard | {
"lang": "python",
"repo": "KEVINYZY/tdb",
"path": "/tdb/tests/test_mnist.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # pdb.set_trace()
# result=s.run(optimizer,feed_dict)
# pdb.set_trace()
# tmp
# return
evals=[optimizer,loss,train_prediction,conv1_weights,conv2_weights,fc1_weights,fc2_weights]
# define some plotting functions
# use one debugSession per run
# attach plot n... | code_fim | hard | {
"lang": "python",
"repo": "KEVINYZY/tdb",
"path": "/tdb/tests/test_mnist.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: VishalSharma0309/gap_sdk path: /tools/nntool/graph/types/linear.py
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundatio... | code_fim | hard | {
"lang": "python",
"repo": "VishalSharma0309/gap_sdk",
"path": "/tools/nntool/graph/types/linear.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> return FcParameters(name, filt=self.filter.clone(), has_bias=self.has_bias)
def compute_load(self):
return self.in_dims[0].size() * self.out_dims[0].c
def __str__(self):
return "F {} {}".format(self.filter, self.at_options or "")<|fim_prefix|># repo: VishalSharma0309/gap_... | code_fim | hard | {
"lang": "python",
"repo": "VishalSharma0309/gap_sdk",
"path": "/tools/nntool/graph/types/linear.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: danielSoler93/AdaptivePELE path: /AdaptivePELE/utilities/generate_topology_object.py
import os
import glob
import argparse
from AdaptivePELE.utilities import utilities
def parseArguments():
"""
Parse the command-line options
:returns: object -- Object containing the options... | code_fim | medium | {
"lang": "python",
"repo": "danielSoler93/AdaptivePELE",
"path": "/AdaptivePELE/utilities/generate_topology_object.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def main(top_path):
sim_folder = os.path.abspath(os.path.join(top_path, os.path.pardir))
epochs = utilities.get_epoch_folders(sim_folder)
top = utilities.Topology(top_path)
topology_files = glob.glob(os.path.join(top_path, "topology*.pdb"))
topology_files.sort(key=utilities.getTrajNum)... | code_fim | hard | {
"lang": "python",
"repo": "danielSoler93/AdaptivePELE",
"path": "/AdaptivePELE/utilities/generate_topology_object.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rapidpro/tracpro path: /tracpro/groups/views.py
from __future__ import absolute_import, unicode_literals
import logging
import json
from dash.orgs.views import OrgPermsMixin
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolv... | code_fim | hard | {
"lang": "python",
"repo": "rapidpro/tracpro",
"path": "/tracpro/groups/views.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> kwargs = super(RegionCRUDL.Select, self).get_form_kwargs()
kwargs.setdefault('model', RegionCRUDL.model)
kwargs.setdefault('org', self.request.org)
return kwargs
def form_valid(self, form):
uuids = form.cleaned_data['groups']
... | code_fim | hard | {
"lang": "python",
"repo": "rapidpro/tracpro",
"path": "/tracpro/groups/views.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
# addBinary(addBinary(1,[]),1)+'0'
# addBinary(addBinary(1,[]),1) + '0' ==> addBinary(1,[]) return a =1 B
# addBinary(1,1)+'0'
# return {addBinary(addBinary(a[0:-1],b[0:-1]),'1')+'0' } +'0' ==> addBinary(a[0:-1],b[0:-1]) return empty A
# return {addBinary(empty,'1')+'0' } +'0' ===> addBinary(empty... | code_fim | hard | {
"lang": "python",
"repo": "PRkudupu/Algo-python",
"path": "/basics/py/add_binary.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># In[14]:
def add_binary(a,b):
print("len(a) {}".format(len(a)))
print("len(b) {}".format(len(b)))
print("a[-1] {}".format(a[-1]))
print("b[-1] {}".format(b[-1]))
print("a[0:-1]) {}".format(a[0:-1]))
print("b[0:-1]) {}".format(b[0:-1]))
if len(a)==0:
print("len a... | code_fim | hard | {
"lang": "python",
"repo": "PRkudupu/Algo-python",
"path": "/basics/py/add_binary.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: PRkudupu/Algo-python path: /basics/py/add_binary.py
#!/usr/bin/env python
# coding: utf-8
# ## Given two binary strings, return their sum (also a binary string).
#
# The input strings are both non-empty and contains only characters 1 or 0.
#
# ### Example 1:
#
# Input: a = "11", b = "1"
# Out... | code_fim | hard | {
"lang": "python",
"repo": "PRkudupu/Algo-python",
"path": "/basics/py/add_binary.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Fabianexe/Superbubble path: /LSD/inout/__init__.py
import networkx as nx
def load(path, f="edgelist"):
if path == "-":
from sys import stdin
path = stdin.buffer
g = None
if f == "edgelist":
g = load_edgelist(path)
elif f == "adjlist":
g = load_adj... | code_fim | medium | {
"lang": "python",
"repo": "Fabianexe/Superbubble",
"path": "/LSD/inout/__init__.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def load_gpickle(path):
return nx.read_gpickle
def load_graph6(path):
return nx.read_graph6
def load_graphml(path):
return nx.read_graphml
def load_leda(path):
return nx.read_leda
def load_pajek(path):
return nx.read_pajek
def load_sparse6(path):
return nx.read_sparse6
... | code_fim | hard | {
"lang": "python",
"repo": "Fabianexe/Superbubble",
"path": "/LSD/inout/__init__.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ipa-rar/ros2_practice_workspace path: /ros2_sub/launch/sub_launch.py
from launch import LaunchDescription
from launch_ros.actions import Node
<|fim_suffix|> sub_node = Node(
package="ros2_sub",
executable="number_subscriber"
)
ld.add_action(sub_node)
return ld... | code_fim | medium | {
"lang": "python",
"repo": "ipa-rar/ros2_practice_workspace",
"path": "/ros2_sub/launch/sub_launch.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> ld.add_action(sub_node)
return ld<|fim_prefix|># repo: ipa-rar/ros2_practice_workspace path: /ros2_sub/launch/sub_launch.py
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
<|fim_middle|> ld = LaunchDescription()
sub_node = N... | code_fim | medium | {
"lang": "python",
"repo": "ipa-rar/ros2_practice_workspace",
"path": "/ros2_sub/launch/sub_launch.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recur... | code_fim | hard | {
"lang": "python",
"repo": "fylein/fyle-qbo-api",
"path": "/q_cluster_watcher.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: fylein/fyle-qbo-api path: /q_cluster_watcher.py
import logging
import os
import sys
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
class LoggingEventHandler(FileSystemEventHandler):
<|fim_suffix|> super().on_modified(event)
... | code_fim | hard | {
"lang": "python",
"repo": "fylein/fyle-qbo-api",
"path": "/q_cluster_watcher.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ajvreugdenhil/NFC-UID-Tool path: /uid_tool.py
from smartcard.System import readers
from smartcard.util import toHexString
from smartcard.ATR import ATR
from smartcard.CardType import AnyCardType
from smartcard.pcsc import PCSCExceptions
import sys
import logging
logging.basicConfig(
format='... | code_fim | hard | {
"lang": "python",
"repo": "ajvreugdenhil/NFC-UID-Tool",
"path": "/uid_tool.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def main():
logger.error("Be careful! Somewhere along the line I borked my only 7B card. This current code is not known-good")
'''
write_uid_desfire("aabbccddeeff11")
uid = get_uid()
print("UID: " + ' '.join('{:02x}'.format(x) for x in uid))
'''
if __name__ == "__main__":
ma... | code_fim | hard | {
"lang": "python",
"repo": "ajvreugdenhil/NFC-UID-Tool",
"path": "/uid_tool.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> userdata_values = bytes.fromhex(userdata)
# Note, mfclassic only allows writing of 16 bytes at a time (that's one block)
assert len(userdata_values) == 16
write_command = data_write_command + [blocknr, len(userdata_values)]
for b in userdata_values:
write_command.append(b)
... | code_fim | hard | {
"lang": "python",
"repo": "ajvreugdenhil/NFC-UID-Tool",
"path": "/uid_tool.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: apetrov/resonances path: /tests/tools.py
import resonances
def get_3body_elements_sample():
return {
"a": 2.398825840331548,
"e": 0.2194125828625336,
"inc": 0.23627318991620527,
"Omega": 0.6370508455573044,
"omega": 5.752902062786396,
"M": 2.4... | code_fim | hard | {
"lang": "python",
"repo": "apetrov/resonances",
"path": "/tests/tools.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def add_test_asteroid_to_simulation(sim):
elem = get_3body_elements_sample()
mmr = resonances.ThreeBody('4J-2S-1')
sim.add_body(elem, mmr, name='asteroid')
return sim<|fim_prefix|># repo: apetrov/resonances path: /tests/tools.py
import resonances
def get_3body_elements_sample():
ret... | code_fim | medium | {
"lang": "python",
"repo": "apetrov/resonances",
"path": "/tests/tools.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if self.se:
x = self.se_block(x) * x
x = self.pointwise_conv(x)
if self.in_channels == self.out_channels and self.stride == 1:
x = x + inputs
return x
class EffUNet(nn.Module):
""" U-Net with EfficientNet-B0 encoder """
def __init__(sel... | code_fim | hard | {
"lang": "python",
"repo": "silver-birch-wawa/Eff-UNet",
"path": "/models/EffUNet.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: silver-birch-wawa/Eff-UNet path: /models/EffUNet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class DecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(
nn.Conv2d(in... | code_fim | hard | {
"lang": "python",
"repo": "silver-birch-wawa/Eff-UNet",
"path": "/models/EffUNet.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># The dry heat values of cellulose, hemicellulose and lignin respectively are 17 MJ/kg (7,320 Btu/lb), 16.63 MJ/kg (7165 Btu/lb) and 21.13 MJ/kg (9,105 Btu/lb) [1]
# [1] Murphy W. K., and K. R. Masters. 1978. Gross heat of combustion of northern red oak (Quercus rubra) chemical components. Wood Sci. 10:1... | code_fim | hard | {
"lang": "python",
"repo": "yalinli2/Bioindustrial-Park",
"path": "/BioSTEAM 1.x.x/build/lib/biorefineries/lipidcane/species/pretreatment.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.