file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_field.py | # test_field.py
#
# Copyright 2017 Daniel Mende <mail@c0decafe.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain th... | Value(b'\x00\x03', 10), Value(b'\x00\x04', 10), Value(b'\x03\xfb', 10), Value(b'\x03\xfc', 10),
Value(b'\x03\xfd', 10), Value(b'\x03\xfe', 10), Value(b'\x03\xff', 10), Value(b'\x01\xfc', 10),
Value(b'\x01\xfd', 10), Value(b'\x01\xfe', 10), Value(b'\x01\xff', 1... | def test_add_unaligned(self):
pass
def test_iter(self):
expected = [Value(b'\x01#', 10), Value(b'\x00\x00', 10), Value(b'\x00\x01', 10), Value(b'\x00\x02', 10), | random_line_split |
test_field.py | # test_field.py
#
# Copyright 2017 Daniel Mende <mail@c0decafe.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain th... | self.assertEqual(v1.size // 8, len(chars1) + len(chars2) + len(chars3))
def test_add_unaligned(self):
pass
def test_iter(self):
expected = [Value(b'\x01#', 10), Value(b'\x00\x00', 10), Value(b'\x00\x01', 10), Value(b'\x00\x02', 10),
Value(b'\x00\x03', 10), Value... | def test_init(self):
f = Field("test", b"\x01\x23", slice(10, 12), "std")
self.assertEqual(f.name, "test")
self.assertEqual(f.size, slice(10, 12, 1))
self.assertEqual(f.default, Value(b"\x01\x23", 10))
self.assertEqual(f.fuzz, "std")
def test_add_aligned(self):
chars... | identifier_body |
test_field.py | # test_field.py
#
# Copyright 2017 Daniel Mende <mail@c0decafe.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain th... | (self):
expected = [Value(b'\x01#', 10), Value(b'\x00\x00', 10), Value(b'\x00\x01', 10), Value(b'\x00\x02', 10),
Value(b'\x00\x03', 10), Value(b'\x00\x04', 10), Value(b'\x03\xfb', 10), Value(b'\x03\xfc', 10),
Value(b'\x03\xfd', 10), Value(b'\x03\xfe', 10), Value(b'\x03\xf... | test_iter | identifier_name |
sublimelinter.py | _instance
def __init__(self, *args, **kwargs):
"""Initialize a new instance."""
super().__init__(*args, **kwargs)
# Keeps track of which views we have assigned linters to
self.loaded_views = set()
# Keeps track of which views have actually been linted
self.linted_v... |
if self.is_scratch(view):
return
if view.id() not in persist.view_linters:
syntax_changed = self.check_syntax(view)
if not syntax_changed:
return
else:
syntax_changed = False
if syntax_changed or persist.settings.get('li... | # sublime_plugin.EventListener event handlers
def on_modified(self, view):
"""Called when a view is modified.""" | random_line_split |
sublimelinter.py | _instance
def __init__(self, *args, **kwargs):
"""Initialize a new instance."""
super().__init__(*args, **kwargs)
# Keeps track of which views we have assigned linters to
self.loaded_views = set()
# Keeps track of which views have actually been linted
self.linted_v... |
if persist.settings.get('lint_mode', 'background') in ('background', 'load/save'):
self.hit(view)
self.on_selection_modified_async(view)
def on_open_settings(self, view):
"""
Called when any settings file is opened.
view is the view that contains the ... | self.on_new(view) | conditional_block |
sublimelinter.py | _instance
def __init__(self, *args, **kwargs):
"""Initialize a new instance."""
super().__init__(*args, **kwargs)
# Keeps track of which views we have assigned linters to
self.loaded_views = set()
# Keeps track of which views have actually been linted
self.linted_v... |
def is_settings_file(self, view, user_only=False):
"""Return True if view is a SublimeLinter settings file."""
filename = view.file_name()
if not filename:
return False
if not filename.startswith(sublime.packages_path()):
return False
dirname, fi... | """
Called when any settings file is opened.
view is the view that contains the text of the settings file.
"""
if self.is_settings_file(view, user_only=True):
persist.settings.save(view=view) | identifier_body |
sublimelinter.py | _instance
def __init__(self, *args, **kwargs):
"""Initialize a new instance."""
super().__init__(*args, **kwargs)
# Keeps track of which views we have assigned linters to
self.loaded_views = set()
# Keeps track of which views have actually been linted
self.linted_v... | (self, view):
"""Called when the selection changes (cursor moves or text selected)."""
if self.is_scratch(view):
return
view = self.get_focused_view_id(view)
if view is None:
return
vid = view.id()
# Get the line number of the first line of th... | on_selection_modified_async | identifier_name |
template_common.py |
read the simulation specific datafiles and extract the ranges by field.
"""
from sirepo import simulation_db
run_dir = simulation_db.simulation_run_dir(PKDict(
simulationType=args['simulationType'],
simulationId=args['simulationId'],
report='animation',
))
data = simula... | res[k][v[0]] = True
return res
def parse_mpi_log(run_dir): | random_line_split | |
template_common.py | cls.__particle_info(sim_type, particle, beam)[0]
@classmethod
def __particle_info(cls, sim_type, particle, beam):
mass_and_charge = sirepo.sim_data.get_class(sim_type).schema().constants.get(
'particleMassAndCharge',
cls.PARTICLE_MASS_AND_CHARGE,
)
if particle i... | if model['plotRangeType'] == 'fixed':
r = [
_plot_range(model, 'horizontal'),
_plot_range(model, 'vertical'),
]
elif model['plotRangeType'] == 'fit' and 'fieldRange' in model:
r = [
model.fieldRange[model['x']],
... | conditional_block | |
template_common.py | if the file's extension matches any in
the list, otherwise False
If white_list is empty: False if the file's extension matches any in
black_list, otherwise True
"""
import os
if os.path.isdir(file_path):
return True
if white_list:
in_list = False
for ext... | text_data_file | identifier_name | |
template_common.py | muon=[0.1056583755, -1],
positron=[5.10998928e-4, 1],
proton=[0.938272046, 1],
)
@classmethod
def compute_energy(cls, sim_type, particle, energy):
p = PKDict(
mass=cls.get_mass(sim_type, particle, energy),
charge=cls.get_charge(sim_type, particle, energy),
... |
@classmethod
def __set_from_pc(cls, particle, energy):
r2 = energy.pc ** 2 / (particle.mass ** 2)
energy.beta = math.sqrt(r2 / (1 + r2))
cls.__set_from_beta(particle, energy)
def compute_field_range(args, compute_range):
""" Computes the fieldRange values for all parameters acros... | assert energy.gamma >= 1, \
'energy gamma out of range: {}'.format(energy.gamma)
energy.energy = energy.gamma * particle.mass
energy.kinetic_energy = energy.energy - particle.mass
energy.beta = math.sqrt(1.0 - 1.0 / (energy.gamma ** 2))
energy.pc = energy.gamma * energy.beta ... | identifier_body |
dstat_vmk_nic.py | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine... |
def vars(self):
ret = []
if op.netlist:
list = op.netlist
else:
list = self.discover
list.sort()
for name in list:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
... | ret = []
for l in self.fd[0].splitlines(replace=' /', delim='/'):
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'lo0': continue
... | identifier_body |
dstat_vmk_nic.py | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine... | for line in self.fd[0].readlines():
l = line.replace(' /','/').split()
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'Usa... | random_line_split | |
dstat_vmk_nic.py | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine... | (self, *list):
ret = []
for l in self.fd[0].splitlines(replace=' /', delim='/'):
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] =... | discover | identifier_name |
dstat_vmk_nic.py | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine... |
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'lo0': continue
if l[0] == 'Usage:': continue
ret.append(l[0])
ret.sort()
for item in list: ret.append(item)
return ret
def ... | continue | conditional_block |
qa_vco.py | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
import math
def sig_source_f(samp_rate, freq, amp, N):
t = [float(x) / samp_rate for x in range(N)]
y = [am... | gr_unittest.run(test_vco, "test_vco.xml") | conditional_block | |
qa_vco.py | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
import math
| t = [float(x) / samp_rate for x in range(N)]
y = [amp*math.cos(2.*math.pi*freq*x) for x in t]
return y
def sig_source_c(samp_rate, freq, amp, N):
t = [float(x) / samp_rate for x in range(N)]
y = [math.cos(2.*math.pi*freq*x) + \
1j*math.sin(2.*math.pi*freq*x) for x in t]
return y... | def sig_source_f(samp_rate, freq, amp, N): | random_line_split |
qa_vco.py | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
import math
def sig_source_f(samp_rate, freq, amp, N):
t = [float(x) / samp_rate for x in range(N)]
y = [am... | (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001(self):
src_data = 200*[0,] + 200*[0.5,] + 200*[1,]
expected_result = 200*[1,] + \
sig_source_f(1, 0.125, 1, 200) + \
sig_source_f(1, 0.25, 1, 200)
src = blocks.v... | setUp | identifier_name |
qa_vco.py | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
import math
def sig_source_f(samp_rate, freq, amp, N):
|
def sig_source_c(samp_rate, freq, amp, N):
t = [float(x) / samp_rate for x in range(N)]
y = [math.cos(2.*math.pi*freq*x) + \
1j*math.sin(2.*math.pi*freq*x) for x in t]
return y
class test_vco(gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown... | t = [float(x) / samp_rate for x in range(N)]
y = [amp*math.cos(2.*math.pi*freq*x) for x in t]
return y | identifier_body |
vera++.py | # run from root sources directory: python Scripts/vera++/vera++.py
import os
ignoredEndings = []
ignoredContent = [
"CMakeFiles",
"MyGUI_UString",
"pugixml",
"sigslot",
"Wrappers",
"MyGUI_KeyCode.h:58",
"InputConverter.h:896",
"MyGUI_RTTLayer.h:21",
"HotKeyManager.cpp:44",
"HotKeyManager.cpp:45",
"Common/Ba... |
return False
def parseOutput():
file = open("temp.vera++", 'r')
line = file.readline()
while line != "":
line = line[0:len(line)-1]
if (not isIgnoredWarning(line)):
print line
line = file.readline()
file.close ()
def checkDir(folder):
os.system("vera++ ../../" + folder + " -profile default 2> temp.v... | return True | conditional_block |
vera++.py | # run from root sources directory: python Scripts/vera++/vera++.py
import os
ignoredEndings = []
ignoredContent = [
"CMakeFiles",
"MyGUI_UString",
"pugixml",
"sigslot",
"Wrappers",
"MyGUI_KeyCode.h:58",
"InputConverter.h:896",
"MyGUI_RTTLayer.h:21",
"HotKeyManager.cpp:44",
"HotKeyManager.cpp:45",
"Common/Ba... | (warning):
for ignore in ignoredEndings:
if warning.endswith(ignore):
return True
for ignore in ignoredContent:
if warning.find(ignore) != -1:
return True
return False
def parseOutput():
file = open("temp.vera++", 'r')
line = file.readline()
while line != "":
line = line[0:len(line)-1]
if (not is... | isIgnoredWarning | identifier_name |
vera++.py | # run from root sources directory: python Scripts/vera++/vera++.py
import os
ignoredEndings = []
ignoredContent = [
"CMakeFiles",
"MyGUI_UString",
"pugixml",
"sigslot",
"Wrappers",
"MyGUI_KeyCode.h:58",
"InputConverter.h:896",
"MyGUI_RTTLayer.h:21",
"HotKeyManager.cpp:44",
"HotKeyManager.cpp:45",
"Common/Ba... |
def checkDir(folder):
os.system("vera++ ../../" + folder + " -profile default 2> temp.vera++")
parseOutput()
os.chdir("Scripts/vera++")
checkDir("*/*/*.h")
checkDir("*/*/*.cpp")
checkDir("*/*/*/*.h")
checkDir("*/*/*/*.cpp")
checkDir("Platforms/*/*/*/*.h")
checkDir("Platforms/*/*/*/*.cpp")
os.chdir("../..")
| file = open("temp.vera++", 'r')
line = file.readline()
while line != "":
line = line[0:len(line)-1]
if (not isIgnoredWarning(line)):
print line
line = file.readline()
file.close () | identifier_body |
vera++.py | # run from root sources directory: python Scripts/vera++/vera++.py
import os
ignoredEndings = []
ignoredContent = [
"CMakeFiles",
"MyGUI_UString",
"pugixml",
"sigslot",
"Wrappers",
"MyGUI_KeyCode.h:58",
"InputConverter.h:896",
"MyGUI_RTTLayer.h:21",
"HotKeyManager.cpp:44",
"HotKeyManager.cpp:45",
"Common/Ba... | checkDir("Platforms/*/*/*/*.cpp")
os.chdir("../..") | random_line_split | |
hydro_cli.py | import argparse
import sys
import os
from django.template import Template, Context
from django.conf import settings as django_settings
import django
__author__ = 'moshebasanchig'
def _create_file_from_template(template_file_name, destination_file_name, topology_name):
with open(template_file_name, 'r') as templa... | ```
from hydro.hydro_cluster import LocalHydro
local_hydro = LocalHydro()
from {dir_name}.topology1 import {topology_name}Topology
local_hydro.register('{topology_name}', {topology_name}Topology())
result = local_hydro.submit('{topology_name}', {{}})
print result.stream
```
"""
p... | Scaffolding completed successfully. Here's how to use your new topology: | random_line_split |
hydro_cli.py | import argparse
import sys
import os
from django.template import Template, Context
from django.conf import settings as django_settings
import django
__author__ = 'moshebasanchig'
def _create_file_from_template(template_file_name, destination_file_name, topology_name):
with open(template_file_name, 'r') as templa... |
def submit(args):
raise BaseException("submit not implemented")
def main():
parser = argparse.ArgumentParser(description='Hydro management tool')
subparsers = parser.add_subparsers()
scaffold_parser = subparsers.add_parser('scaffold', help='scaffold a new topology')
scaffold_parser.add_argument... | raise BaseException("listen not implemented") | identifier_body |
hydro_cli.py | import argparse
import sys
import os
from django.template import Template, Context
from django.conf import settings as django_settings
import django
__author__ = 'moshebasanchig'
def _create_file_from_template(template_file_name, destination_file_name, topology_name):
with open(template_file_name, 'r') as templa... |
if os.path.exists(dir_name):
print 'directory already exists. skipping.'
sys.exit(1)
os.makedirs(dir_name)
open('%s/__init__.py' % dir_name, 'w').close()
template_dir = '%s/templates' % os.path.dirname(os.path.realpath(__file__))
_create_file_from_template('%s/conf.template' % templ... | if not django_settings.configured:
django_settings.configure()
django.setup() | conditional_block |
hydro_cli.py | import argparse
import sys
import os
from django.template import Template, Context
from django.conf import settings as django_settings
import django
__author__ = 'moshebasanchig'
def _create_file_from_template(template_file_name, destination_file_name, topology_name):
with open(template_file_name, 'r') as templa... | (args):
raise BaseException("listen not implemented")
def submit(args):
raise BaseException("submit not implemented")
def main():
parser = argparse.ArgumentParser(description='Hydro management tool')
subparsers = parser.add_subparsers()
scaffold_parser = subparsers.add_parser('scaffold', help='s... | listen | identifier_name |
dft_pitch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of AudioLazy, the signal processing Python package.
# Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini
#
# AudioLazy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... | upd_time_in_ms = 200
# Update functions for each thread
def upd_value(): # Recording thread
pitches = iter(pitch_from_mic(upd_time_in_ms))
while not tk.should_finish:
tk.value = next(pitches)
def upd_timer(): # GUI mainloop thread
lbldata.set("\n".join(regex_note.findall(tk.value)[0]))
t... | try:
import tkinter
except ImportError:
import Tkinter as tkinter
import threading
import re
# Window (Tk init), text label and button
tk = tkinter.Tk()
tk.title(__doc__.strip().splitlines()[0])
lbldata = tkinter.StringVar(tk)
lbltext = tkinter.Label(tk, textvariable=lbldata, font=("Purisa", 72... | conditional_block |
dft_pitch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of AudioLazy, the signal processing Python package.
# Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini
#
# AudioLazy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... | (sig, threshold=.1, size=256, env=envelope.rms, cutoff=pi/2048):
sig = thub(sig, 2)
return sig * Stream( 1. if el <= threshold else threshold / el
for el in maverage(size)(env(sig, cutoff=cutoff)) )
@tostream
def dft_pitch(sig, size=2048, hop=None):
for blk in Stream(sig).blocks(size=size... | limiter | identifier_name |
dft_pitch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of AudioLazy, the signal processing Python package.
# Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini
#
# AudioLazy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... | import re
# Window (Tk init), text label and button
tk = tkinter.Tk()
tk.title(__doc__.strip().splitlines()[0])
lbldata = tkinter.StringVar(tk)
lbltext = tkinter.Label(tk, textvariable=lbldata, font=("Purisa", 72),
width=10)
lbltext.pack(expand=True, fill=tkinter.BOTH)
btnclos... | import threading | random_line_split |
dft_pitch.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of AudioLazy, the signal processing Python package.
# Copyright (C) 2012-2014 Danilo de Jesus da Silva Bellini
#
# AudioLazy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# ... |
def pitch_from_mic(upd_time_in_ms):
rate = 44100
s, Hz = sHz(rate)
api = sys.argv[1] if sys.argv[1:] else None # Choose API via command-line
chunks.size = 1 if api == "jack" else 16
with AudioIO(api=api) as recorder:
snd = recorder.record(rate=rate)
sndlow = lowpass(400 * Hz)(limiter(snd, cutoff=... | for blk in Stream(sig).blocks(size=size, hop=hop):
dft_data = rfft(blk)
idx, vmax = max(enumerate(dft_data),
key=lambda el: abs(el[1]) / (2 * el[0] / size + 1)
)
yield 2 * pi * idx / size | identifier_body |
es.py | from __future__ import absolute_import, division, print_function, unicode_literals
import time
import logging
import ujson as json
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.exceptions import ConnectionTimeout
from .config import config
from .es_mappings... |
def flush(self, retries=10):
""" Sends the current indexing batch to ES """
if len(self.buffer) == 0:
return
if not self.connected:
self.connect()
self.total_size += len(self.buffer)
logging.debug(
"ES: Flushing %s docs to index=%s (t... | """ Sends a "refresh" to the ES index, forcing the actual indexing of what was sent up until now """
if not self.connected:
return
if config["ENV"] not in ("local", "ci"):
raise Exception("refresh() not allowed in env %s" % config["ENV"])
self.indices().refresh(index=s... | identifier_body |
es.py | from __future__ import absolute_import, division, print_function, unicode_literals
import time
import logging
import ujson as json
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.exceptions import ConnectionTimeout
from .config import config
from .es_mappings... | self.total_size = 0
self.connected = False
self.client = None
def connect(self):
""" Establish the ES connection if not already done """
if self.connected:
return
self.connected = True
self.client = Elasticsearch(self.servers[self.index_name], tim... |
def __init__(self, index_name, batch_size=500):
self.index_name = index_name
self.buffer = []
self.batch_size = batch_size | random_line_split |
es.py | from __future__ import absolute_import, division, print_function, unicode_literals
import time
import logging
import ujson as json
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.exceptions import ConnectionTimeout
from .config import config
from .es_mappings... | (self):
""" Returns an elasticsearch.client.IndicesClient instance """
if not self.connected:
self.connect()
return IndicesClient(self.client)
def create(self, empty=False):
""" Creates the ES index """
if empty:
self.empty()
mappings = ES... | indices | identifier_name |
es.py | from __future__ import absolute_import, division, print_function, unicode_literals
import time
import logging
import ujson as json
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.exceptions import ConnectionTimeout
from .config import config
from .es_mappings... |
return IndicesClient(self.client)
def create(self, empty=False):
""" Creates the ES index """
if empty:
self.empty()
mappings = ES_MAPPINGS[self.index_name]
self.indices().create(index=self.index_name, body={
"settings": {
# TODO... | self.connect() | conditional_block |
LoadingOverlay.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { styled } from '@csegames/linaria/react';
import { Spinner } from '... | () {
return (
<Container>
<Spinner />
</Container>
);
}
}
export default LoadingOverlay;
| render | identifier_name |
LoadingOverlay.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { styled } from '@csegames/linaria/react';
import { Spinner } from '... | display: flex;
align-items: center;
justify-content: center;
z-index: 10;
`;
export interface LoadingOverlayProps {
}
class LoadingOverlay extends React.Component<LoadingOverlayProps> {
public render() {
return (
<Container>
<Spinner />
</Container>
);
}
}
export default Load... | random_line_split | |
sniff.py | #! /usr/bin/python
__author__="kebo"
__date__ ="$2009-11-5 11:15:55$"
import pcap
import sys
import string
import time
import socket
import struct
import getopt
protocols={socket.IPPROTO_TCP:'tcp',
socket.IPPROTO_UDP:'udp',
socket.IPPROTO_ICMP:'icmp'}
node = None
mb = None
decoder = None
def se... |
except KeyboardInterrupt:
print '%s' % sys.exc_type
print 'shutting down'
print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
| p.dispatch(1, print_packet) | conditional_block |
sniff.py | #! /usr/bin/python
__author__="kebo"
__date__ ="$2009-11-5 11:15:55$"
import pcap
import sys
import string
import time
import socket
import struct
import getopt
protocols={socket.IPPROTO_TCP:'tcp',
socket.IPPROTO_UDP:'udp',
socket.IPPROTO_ICMP:'icmp'}
node = None
mb = None | decoder = None
def send(payload):
sz = len(payload)
header= struct.pack("!h", sz)
return sys.stdout.write( header + payload )
def print_packet(pktlen, data, timestamp):
global mb
if not data:
return
#send(data)
#print data
#print timestamp
print '\n%s.%f' % (time.strftime('... | random_line_split | |
sniff.py | #! /usr/bin/python
__author__="kebo"
__date__ ="$2009-11-5 11:15:55$"
import pcap
import sys
import string
import time
import socket
import struct
import getopt
protocols={socket.IPPROTO_TCP:'tcp',
socket.IPPROTO_UDP:'udp',
socket.IPPROTO_ICMP:'icmp'}
node = None
mb = None
decoder = None
def se... | (pktlen, data, timestamp):
global mb
if not data:
return
#send(data)
#print data
#print timestamp
print '\n%s.%f' % (time.strftime('%H:%M',time.localtime(timestamp)),timestamp % 60)
if __name__=='__main__':
p = pcap.pcapObject()
#dev = pcap.lookupdev()
dev = "eth0"
net, ... | print_packet | identifier_name |
sniff.py | #! /usr/bin/python
__author__="kebo"
__date__ ="$2009-11-5 11:15:55$"
import pcap
import sys
import string
import time
import socket
import struct
import getopt
protocols={socket.IPPROTO_TCP:'tcp',
socket.IPPROTO_UDP:'udp',
socket.IPPROTO_ICMP:'icmp'}
node = None
mb = None
decoder = None
def se... |
if __name__=='__main__':
p = pcap.pcapObject()
#dev = pcap.lookupdev()
dev = "eth0"
net, mask = pcap.lookupnet(dev)
# note: to_ms does nothing on linux
p.open_live(dev, 1600, 0, 100)
#p.dump_open('dumpfile')
p.setfilter(string.join(["tcp","port 22"],' '), 0, 0)
# try-except block ... | global mb
if not data:
return
#send(data)
#print data
#print timestamp
print '\n%s.%f' % (time.strftime('%H:%M',time.localtime(timestamp)),timestamp % 60) | identifier_body |
field-destruction-order.rs | // run-pass
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
// In theory, it doesn't matter what order destructors are run in for rust
// because we have explicit ownership of values meaning that there's no need to
// run one before another. With unsafe code, however, there may be a safe
// interface which reli... | ;
struct B;
struct C {
a: A,
b: B,
}
static mut hit: bool = false;
impl Drop for A {
fn drop(&mut self) {
unsafe {
assert!(!hit);
hit = true;
}
}
}
impl Drop for B {
fn drop(&mut self) {
unsafe {
assert!(hit);
}
}
}
pub fn m... | A | identifier_name |
field-destruction-order.rs | // run-pass
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
// In theory, it doesn't matter what order destructors are run in for rust
// because we have explicit ownership of values meaning that there's no need to
// run one before another. With unsafe code, however, there may be a safe
// interface which reli... | }
}
impl Drop for B {
fn drop(&mut self) {
unsafe {
assert!(hit);
}
}
}
pub fn main() {
let _c = C { a: A, b: B };
} | fn drop(&mut self) {
unsafe {
assert!(!hit);
hit = true;
} | random_line_split |
info_base.rs | use super::{imports::Imports, *};
use crate::{codegen::Visibility, library, version::Version};
#[derive(Debug, Default)]
pub struct InfoBase {
pub full_name: String,
pub type_id: library::TypeId,
pub name: String,
pub functions: Vec<functions::Info>,
pub specials: special_functions::Infos,
pub ... | pub fn functions(&self) -> Vec<&functions::Info> {
self.functions
.iter()
.filter(|f| f.status.need_generate() && f.kind == library::FunctionKind::Function)
.collect()
}
} | }
| random_line_split |
info_base.rs | use super::{imports::Imports, *};
use crate::{codegen::Visibility, library, version::Version};
#[derive(Debug, Default)]
pub struct InfoBase {
pub full_name: String,
pub type_id: library::TypeId,
pub name: String,
pub functions: Vec<functions::Info>,
pub specials: special_functions::Infos,
pub ... | (&self) -> Vec<&functions::Info> {
self.functions
.iter()
.filter(|f| f.status.need_generate() && f.kind == library::FunctionKind::Function)
.collect()
}
}
| functions | identifier_name |
index.js | /* eslint-disable react/jsx-no-bind */
import React from 'react';
import { arrayOf, func, shape } from 'prop-types';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import IconButton from '@material-ui/core/IconButton'... |
export default function FolderMenu({
folderAction,
onMenuClick,
folder
}) {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = event => {
event.stopPropagation();
setAnchorEl(event.currentTarget);
};
const handleClose = event => {
event.s... | const useStyles = makeStyles(theme => ({
...styles
})); | random_line_split |
index.js | /* eslint-disable react/jsx-no-bind */
import React from 'react';
import { arrayOf, func, shape } from 'prop-types';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import IconButton from '@material-ui/core/IconButton'... | aria-haspopup="true"
onClick={handleClick}
>
<MoreVertIcon style={{ fontSize: 20 }} />
</IconButton>
<Menu
id="folder-tree-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
>
{folderAction.map(item => (
... | {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = event => {
event.stopPropagation();
setAnchorEl(event.currentTarget);
};
const handleClose = event => {
event.stopPropagation();
const type = event.target.getAttribute('data-type');
se... | identifier_body |
index.js | /* eslint-disable react/jsx-no-bind */
import React from 'react';
import { arrayOf, func, shape } from 'prop-types';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import IconButton from '@material-ui/core/IconButton'... | ({
folderAction,
onMenuClick,
folder
}) {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = event => {
event.stopPropagation();
setAnchorEl(event.currentTarget);
};
const handleClose = event => {
event.stopPropagation();
const type = ... | FolderMenu | identifier_name |
shared.js | exports.get = handleRequest;
exports.post = handleRequest;
exports.put = handleRequest;
exports.patch = handleRequest;
exports.del = handleRequest;
exports.handleRequest = handleRequest;
function handleRequest(req, res) {
var format = req.query.format || 'json'; | var output = { method: req.method };
for (var q in req.query) {
if (q !== 'format' && q !== 'status' && req.query.hasOwnProperty(q)) {
var val = req.query[q];
if (typeof val === 'string') {
if (!output.query) output.query = {};
output.query[q] = re... | var status = req.query.status || 200; | random_line_split |
shared.js | exports.get = handleRequest;
exports.post = handleRequest;
exports.put = handleRequest;
exports.patch = handleRequest;
exports.del = handleRequest;
exports.handleRequest = handleRequest;
function handleRequest(req, res) {
var format = req.query.format || 'json';
var status = req.query.status || 200;
var ou... | (value) {
if (value === null) return 'null';
var type = typeof value;
var result = '';
var i = 0;
switch (type.toLowerCase()) {
case 'string':
case 'boolean':
case 'number':
return value.toString();
case 'function':
case 'object':
if (O... | jsToXml | identifier_name |
shared.js | exports.get = handleRequest;
exports.post = handleRequest;
exports.put = handleRequest;
exports.patch = handleRequest;
exports.del = handleRequest;
exports.handleRequest = handleRequest;
function handleRequest(req, res) {
var format = req.query.format || 'json';
var status = req.query.status || 200;
var ou... |
}
if (req.body) {
output.body = req.body;
}
output.user = JSON.parse(JSON.stringify(req.user)); // remove functions
switch (format) {
case 'json':
break; // nothing to do
case 'xml':
res.set('Content-Type', 'text/xml');
output = objToXm... | {
res.set(reqHeader, reqHeaders[reqHeader]);
} | conditional_block |
shared.js | exports.get = handleRequest;
exports.post = handleRequest;
exports.put = handleRequest;
exports.patch = handleRequest;
exports.del = handleRequest;
exports.handleRequest = handleRequest;
function handleRequest(req, res) {
var format = req.query.format || 'json';
var status = req.query.status || 200;
var ou... |
function jsToXml(value) {
if (value === null) return 'null';
var type = typeof value;
var result = '';
var i = 0;
switch (type.toLowerCase()) {
case 'string':
case 'boolean':
case 'number':
return value.toString();
case 'function':
case 'object':... | {
return '<root>' + jsToXml(obj) + '</root>';
} | identifier_body |
index.js | // en routes definimos toda la interfaz
var express = require('express');
var router = express.Router();
var quizController = require('../controllers/quiz_controller.js');
var commentController = require('../controllers/comment_controller.js');
var sessionController = require('../controllers/session_controller.js');
... | router.get('/logout', sessionController.destroy); // destruir
router.get('/quizes', quizController.index);
router.get('/quizes/new', sessionController.loginRequired, quizController.new);
router.get('/quizes/:quizId(\\d+)', quizController.show);
router.get('/quizes/:quizId(\\d+)/answer', quizController.answer);
router.... | router.param('quizId', quizController.load);
router.param('commentId', commentController.load);
router.get('/login', sessionController.new); // formulario login
router.post('/login', sessionController.create); // crear | random_line_split |
index.ts | import {
Server,
} from './server';
import {
Database,
Downloader,
OAuth,
Socket,
Twitter,
} from '~/server/libs';
const token = {
'consumer_key': __env.consumer_key,
'consumer_secret': __env.consumer_secret,
'access_token': __env.access_token,
'access_token_secret': __env.access_token_secret,
};
const por... |
try {
await Promise.all([
Database.start(),
// Downloader.start(),
Twitter.start(),
]);
}
catch(error) {
console.log('start failed');
throw error;
}
})(); | }
catch(error) {
console.log('initialized failed');
throw error;
} | random_line_split |
x86_64_fuchsia.rs | use crate::spec::{SanitizerSet, StackProbeType, Target};
pub fn target() -> Target | {
let mut base = super::fuchsia_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
// don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved
base.stack_probes = StackProbeType::Call;
base.supported_sanitizers = SanitizerSet::ADDRESS;
Targ... | identifier_body | |
x86_64_fuchsia.rs | use crate::spec::{SanitizerSet, StackProbeType, Target};
pub fn target() -> Target {
let mut base = super::fuchsia_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
// don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved
base.stack_probes = St... | pointer_width: 64,
data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
.to_string(),
arch: "x86_64".to_string(),
options: base,
}
} | llvm_target: "x86_64-fuchsia".to_string(), | random_line_split |
x86_64_fuchsia.rs | use crate::spec::{SanitizerSet, StackProbeType, Target};
pub fn | () -> Target {
let mut base = super::fuchsia_base::opts();
base.cpu = "x86-64".to_string();
base.max_atomic_width = Some(64);
// don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved
base.stack_probes = StackProbeType::Call;
base.supported_sanitizers = SanitizerSet::ADDRE... | target | identifier_name |
__init__.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
| step_03_fip as fip,
step_04_famille as famille,
step_05_foyer as foyer,
step_06_rebuild as rebuild,
step_07_invalides as invalides,
step_08_final as final,
)
from openfisca_france_data.temporary import get_store
from openfisca_survey_manager.surveys import Survey
from openfisca_survey_manag... | from openfisca_france_data import default_config_files_directory as config_files_directory
from openfisca_france_data.erfs.input_data_builder import ( # analysis:ignore
step_01_pre_processing as pre_processing,
step_02_imputation_loyer as imputation_loyer, | random_line_split |
__init__.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from openfisca_france_data import default_config_files_directory as config_files_directory
from openfisca_france_data.erfs.input_data_builder import ( # analysis:ignore
step_01_pre_processing as pre_processing,
step_02_imputation_loyer... | # Saving the data_frame
openfisca_survey_collection = SurveyCollection(name = "openfisca", config_files_directory = config_files_directory)
output_data_directory = openfisca_survey_collection.config.get('data', 'output_directory')
survey_name = "openfisca_data_{}".format(year)
table = "input"
hd... | assert year is not None
pre_processing.create_indivim_menagem(year = year)
pre_processing.create_enfants_a_naitre(year = year)
# try:
# imputation_loyer.imputation_loyer(year = year)
# except Exception, e:
# log.info('Do not impute loyer because of the following error: \n {}'... | identifier_body |
__init__.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from openfisca_france_data import default_config_files_directory as config_files_directory
from openfisca_france_data.erfs.input_data_builder import ( # analysis:ignore
step_01_pre_processing as pre_processing,
step_02_imputation_loyer... | (year = None, check = False):
assert year is not None
pre_processing.create_indivim_menagem(year = year)
pre_processing.create_enfants_a_naitre(year = year)
# try:
# imputation_loyer.imputation_loyer(year = year)
# except Exception, e:
# log.info('Do not impute loyer bec... | build | identifier_name |
window.py | published by
the Free Software Foundation, version 3 of the License.
The Automated FTP Dominator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public Licens... | # Creates a menu bar and returns it to the caller - sadly they only look right if we're working with a QMainWindow
def makeMenubar(self):
# Make a new menubar
menubar = QtGui.QMenuBar()
# First menu entry - File, as always
file = menubar.addMenu('&File')
# Last file entry - as always
file.addSeparator()... |
return conf_hbox
| random_line_split |
window.py | , version 3 of the License.
The Automated FTP Dominator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have recei... | _confirmDiscardChanges | identifier_name | |
window.py | .gnu.org/licenses/>.
'''
from PyQt4 import QtGui, QtCore
from gui.dialogs.DomEditEntry import DomEditEntryDialog
class Config(QtGui.QMainWindow):
changes = None
configObject = None
_configname = 'default'
def __init__(self, config):
QtGui.QMainWindow.__init__(self, None)
self._config = config
self.setGe... | return True | conditional_block | |
window.py | published by
the Free Software Foundation, version 3 of the License.
The Automated FTP Dominator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public Licens... |
###############################################################################################################################
################################################### Listeners #################################################################
###########################################################... | if not self._confirmDiscardChanges():
return None
# Having attained that permission, let us proceed onward with great haste
try:
self.configObject = self._config.getConfig(str(config))
except Exception:
QtGui.QMessageBox.critical(self, 'Error', 'Error opening config file.')
self.configObject = None... | identifier_body |
army.js | Army = {
makeArmy : function(img)
{
var armyShared = ArmyShared.makeArmyShared(img, null);
var oldAttack = armyShared.attack;
var army = {
moving: function(x, y)
{
var moveMap = this.indexMovement().moveMap;
for(var i = 0; i < moveMap.length; i++)
{
if(moveMap[i].x == x && mo... |
}
},
attack : function(playerObj)
{
var result = oldAttack.call(this, playerObj);
if(result != null)
{
Server.sendBroadcast(JSON.stringify({type : "attack", id : this.id, idDef : playerObj.id, hurt : result}));
}
}
}
return Object.assign(armyShared, army);
}
}
... | {
var armyObj = Field.getArmyObject(x, y);
if(!armyObj)
{
this.moved(x, y, moveMap[i].speed);
Server.sendBroadcast(JSON.stringify({type : "moving", x : x, y : y, id : this.id, speed : this.speed}));
return;
}
} | conditional_block |
army.js | Army = {
makeArmy : function(img)
{
var armyShared = ArmyShared.makeArmyShared(img, null);
var oldAttack = armyShared.attack;
var army = {
moving: function(x, y)
{
var moveMap = this.indexMovement().moveMap;
for(var i = 0; i < moveMap.length; i++)
{
if(moveMap[i].x == x && mo... |
return;
}
}
}
},
attack : function(playerObj)
{
var result = oldAttack.call(this, playerObj);
if(result != null)
{
Server.sendBroadcast(JSON.stringify({type : "attack", id : this.id, idDef : playerObj.id, hurt : result}));
}
}
}
... | this.moved(x, y, moveMap[i].speed);
Server.sendBroadcast(JSON.stringify({type : "moving", x : x, y : y, id : this.id, speed : this.speed})); | random_line_split |
radionodelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use crate::dom::bin... | ,
}
}
}
}
// FIXME: This shouldn't need to be implemented here since NodeList (the parent of
// RadioNodeList) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-nodelist-item
fn IndexedGetter(&s... | {} | conditional_block |
radionodelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use crate::dom::bin... |
pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList>
where
T: Iterator<Item = DomRoot<Node>>,
{
RadioNodeList::new(
window,
NodeListType::Simple(iter.map(|r| Dom::from_ref(&*r)).collect()),
)
}
// FIXME: This shouldn't need ... | {
reflect_dom_object(
Box::new(RadioNodeList::new_inherited(list_type)),
window,
RadioNodeListBinding::Wrap,
)
} | identifier_body |
radionodelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use crate::dom::bin... | (window: &Window, list_type: NodeListType) -> DomRoot<RadioNodeList> {
reflect_dom_object(
Box::new(RadioNodeList::new_inherited(list_type)),
window,
RadioNodeListBinding::Wrap,
)
}
pub fn new_simple_list<T>(window: &Window, iter: T) -> DomRoot<RadioNodeList>... | new | identifier_name |
radionodelist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | use crate::dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::htmlinputelement::{... |
use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use crate::dom::bindings::codegen::Bindings::RadioNodeListBinding; | random_line_split |
variance-intersection-of-ref-and-opt-ref.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (field1: &i32, field2: Option<&i32>) -> i32 {
let list = List { field1: field1, field2: field2 };
*list.field1 + list.field2.cloned().unwrap_or(0)
}
fn main() {
let x = 22;
let y = Some(3);
let z = None;
assert_eq!(foo(&x, y.as_ref()), 25);
assert_eq!(foo(&x, z.as_ref()), 22);
}
| foo | identifier_name |
variance-intersection-of-ref-and-opt-ref.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let x = 22;
let y = Some(3);
let z = None;
assert_eq!(foo(&x, y.as_ref()), 25);
assert_eq!(foo(&x, z.as_ref()), 22);
}
| {
let list = List { field1: field1, field2: field2 };
*list.field1 + list.field2.cloned().unwrap_or(0)
} | identifier_body |
variance-intersection-of-ref-and-opt-ref.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn foo(field1: &i32, field2: Option<&i32>) -> i32 {
let list = List { field1: field1, field2: field2 };
*list.field1 + list.field2.cloned().unwrap_or(0)
}
fn main() {
let x = 22;
let y = Some(3);
let z = None;
assert_eq!(foo(&x, y.as_ref()), 25);
assert_eq!(foo(&x, z.as_ref()), 22);
} | field1: &'l i32,
field2: Option<&'l i32>,
} | random_line_split |
LinkedinExtractor.py | # -*- coding: utf-8 -*-
#imports
from linkedin import linkedin
import easygui
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import requests
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Mode = enum('PREVIEW', 'EDIT', ... |
for i in range(len(sys.argv)):
if str(sys.argv[i]).lower() == "-mode" and (i + 1) < len(sys.argv):
if str(sys.argv[i + 1]).lower() == "preview":
mode = Mode.PREVIEW
elif str(sys.argv[i + 1]).lower() == "edit":
mode = Mode.EDIT
elif str(sys.argv[i + 1]).lower() == "r... | fieldValues.append(i) | conditional_block |
LinkedinExtractor.py | # -*- coding: utf-8 -*-
#imports
from linkedin import linkedin
import easygui
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import requests
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Mode = enum('PREVIEW', 'EDIT', ... | RETURN_URL = ''
print "beginDSInfo"
print """fileName;#;true
csv_first_row_has_column_names;true;true;
csv_separator;|;true
csv_number_grouping;,;true
csv_number_decimal;.;true
csv_date_format;d.M.yyyy;true"""
print ''.join(['consumer_key;', str(fieldValues[0]).enc... | CONSUMER_KEY = fieldValues[0]
CONSUMER_SECRET = fieldValues[1]
USER_TOKEN = fieldValues[2]
USER_SECRET = fieldValues[3] | random_line_split |
LinkedinExtractor.py | # -*- coding: utf-8 -*-
#imports
from linkedin import linkedin
import easygui
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import requests
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Mode = enum('PREVIEW', 'EDIT', ... | (fieldValues):
fieldValues = easygui.multenterbox(msg = msg, title = title, fields = fieldNames, values = fieldValues )
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValu... | getScreenInput | identifier_name |
LinkedinExtractor.py | # -*- coding: utf-8 -*-
#imports
from linkedin import linkedin
import easygui
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import requests
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Mode = enum('PREVIEW', 'EDIT', ... |
def printData(fieldValues):
if fieldValues != None:
CONSUMER_KEY = fieldValues[0]
CONSUMER_SECRET = fieldValues[1]
USER_TOKEN = fieldValues[2]
USER_SECRET = fieldValues[3]
RETURN_URL = ''
print "beginDSInfo"
print """fileName;#;true
csv_first_row_h... | fieldValues = easygui.multenterbox(msg = msg, title = title, fields = fieldNames, values = fieldValues )
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":... | identifier_body |
sr-cyrl.js | //! moment.js locale configuration
//! locale : Serbian Cyrillic [sr-cyrl]
//! author : Milan Janačković<milanjanackovic@gmail.com> : https://github.com/milan-j
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../m... | case 2:
case 4:
case 5:
return '[у] dddd [у] LT';
}
},
lastDay : '[јуче у] LT',
lastWeek : function () {
var lastWeekDays = [
'[прошле] [недеље] [у... | case 6:
return '[у] [суботу] [у] LT';
case 1: | random_line_split |
sr-cyrl.js | //! moment.js locale configuration
//! locale : Serbian Cyrillic [sr-cyrl]
//! author : Milan Janačković<milanjanackovic@gmail.com> : https://github.com/milan-j
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../m... | ј_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'),
monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'),
monthsParseExact: true,
weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'),
weekdaysShort: 'нед._пон._уто._сре._че... |
};
var sr_cyrl = moment.defineLocale('sr-cyrl', {
months: 'јануар_фебруар_март_април_ма | conditional_block |
macro_parser.rs | $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a b. - - -
//!
//! Remaining input: ''
//! eof: [a $( a )* a b ·]
//! ```
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
u... | {
match tok {
token::Eof => "unexpected end of macro invocation".to_string(),
_ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)),
}
}
/// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
fn token_name_eq(t1 : &Token, t2 : &... | Token) -> String | identifier_name |
macro_parser.rs | $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a b. - - -
//!
//! Remaining input: ''
//! eof: [a $( a )* a b ·]
//! ```
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
u... | quality check, ignoring syntax context (that is, an unhygienic comparison)
fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
if let (Some(id1), Some(id2)) = (t1.ident(), t2.ident()) {
id1.name == id2.name
} else if let (&token::Lifetime(id1), &token::Lifetime(id2)) = (t1, t2) {
id1.name == id... | token::Eof => "unexpected end of macro invocation".to_string(),
_ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)),
}
}
/// Perform a token e | identifier_body |
macro_parser.rs | a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a b. - - -
//!
//! Remaining input: ''
//! eof: [a $( a )* a b ·]
//! ```
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
use ... | let mut new_pos = ei.up.clone().unwrap();
// update matches (the MBE "parse tree") by appending
// each tree as a subtree. | random_line_split | |
macro_parser.rs | $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a b. - - -
//!
//! Remaining input: ''
//! eof: [a $( a )* a b ·]
//! ```
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
u... | cupied(..) => {
return Err((sp, format!("duplicated bind name: {}", bind_name)))
}
}
}
TokenTree::Token(..) => (),
}
Ok(())
}
let mut ret_val = HashMap::new();
for m in ms {
match n_rec(sess, m, res... | spot.insert(res.next().unwrap());
}
Oc | conditional_block |
svm_how_to.py | Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public... | from nupic.bindings.math import GetNumpyDataType
type = GetNumpyDataType('NTA_Real')
type = 'float32'
#--------------------------------------------------------------------------------
# Simple use case
#--------------------------------------------------------------------------------
def simple():
print "Simp... | import sys
import pylab
import nupic.bindings.algorithms as algo | random_line_split |
svm_how_to.py | NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ver... | ():
print "Persistence"
numpy.random.seed(42)
n_dims = 2
n_class = 12
size = 100
labels = numpy.random.random_integers(0, 256, size)
samples = numpy.zeros((size, n_dims), dtype=type)
print "Generating data"
for i in range(0, size):
t = 6.28 * numpy.random.random_sample(... | persistence | identifier_name |
svm_how_to.py | NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ver... |
print "Training"
classifier.train(gamma = 1./3., C = 100, eps=1e-1)
print "Displaying model"
model = classifier.get_model()
print "Number of support vectors:", model.size()
print "Number of classes:", model.n_class()
print "Number of dimensions: ", model.n_dims()
print "Support vector... | pylab.ion()
pylab.plot(s[s[:,0]==0,1], s[s[:,0]==0,2], '.', color='r')
pylab.plot(s[s[:,0]==1,1], s[s[:,0]==1,2], '+', color='b')
pylab.plot(s[s[:,0]==2,1], s[s[:,0]==2,2], '^', color='g')
pylab.plot(s[s[:,0]==3,1], s[s[:,0]==3,2], 'v', color='g') | conditional_block |
svm_how_to.py | (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License v... | x = numpy.array(x_list, dtype=type)
classifier.add_sample(float(y), x)
print "Displaying problem"
problem = classifier.get_problem()
print "Problem size:", problem.size()
print "Problem dimensionality:", problem.n_dims()
print "Problem samples:"
s = numpy.zeros((problem.size(), ... | print "Simple"
numpy.random.seed(42)
n_dims = 2
n_class = 4
size = 200
labels = numpy.random.random_integers(0, n_class-1, size)
samples = numpy.zeros((size, n_dims), dtype=type)
do_plot = False
print "Generating data"
centers = numpy.array([[0,0],[0,1],[1,0],[1,1]])
for i in ra... | identifier_body |
table-module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {HeaderRowOutlet, DataRo... | CdkFooterCellDef, CdkFooterCell
} from './cell';
import {CdkTextColumn} from './text-column';
const EXPORTED_DECLARATIONS = [
CdkTable,
CdkRowDef,
CdkCellDef,
CdkCellOutlet,
CdkHeaderCellDef,
CdkFooterCellDef,
CdkColumnDef,
CdkCell,
CdkRow,
CdkHeaderCell,
CdkFooterCell,
CdkHeaderRow,
CdkHea... | } from './row';
import {
CdkColumnDef, CdkHeaderCellDef, CdkHeaderCell, CdkCell, CdkCellDef, | random_line_split |
table-module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {HeaderRowOutlet, DataRo... | { }
| CdkTableModule | identifier_name |
postCouchPotato.py | #!/usr/bin/env python
import sys
import os
import logging
from extensions import valid_tagging_extensions
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from tmdb_mp4 import tmdb_mp4
from autoprocess import plex
from post_processor import PostProcessor
from logging.config import fileConfig
logpat... |
plex.refreshPlex(settings, 'movie', log)
else:
log.info('File %s is invalid, ignoring' % inputfile)
except:
log.exception('File processing failed: %s' % inputfile)
| post_processor = PostProcessor(output_files, log)
post_processor.setMovie(imdbid)
post_processor.run_scripts() | conditional_block |
postCouchPotato.py | #!/usr/bin/env python
import sys
import os
import logging
from extensions import valid_tagging_extensions
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from tmdb_mp4 import tmdb_mp4
from autoprocess import plex
from post_processor import PostProcessor
from logging.config import fileConfig
logpat... | log.exception('File processing failed: %s' % inputfile) | else:
log.info('File %s is invalid, ignoring' % inputfile)
except: | random_line_split |
containerbuild.ts | "use strict";
import * as path from "path";
import * as tl from "vsts-task-lib/task";
import * as dockerCommandUtils from "docker-common/dockercommandutils";
import * as fileUtils from "docker-common/fileutils";
import * as pipelineUtils from "docker-common/pipelineutils";
import ContainerConnection from "docker-commo... | command.line(commandArguments);
var imageName = utils.getImageName();
var qualifyImageName = tl.getBoolInput("qualifyImageName");
if (qualifyImageName) {
imageName = connection.getQualifiedImageNameIfRequired(imageName);
}
command.arg(["-t", tl.getBoolInput("enforceDockerNamingConv... | {
var command = connection.createCommand();
command.arg("build");
var dockerfilepath = tl.getInput("dockerFile", true);
let dockerFile = fileUtils.findDockerFile(dockerfilepath);
if(!tl.exist(dockerFile)) {
throw new Error(tl.loc('ContainerDockerFileNotFound', dockerfilepath));
}
... | identifier_body |
containerbuild.ts | "use strict";
import * as path from "path";
import * as tl from "vsts-task-lib/task";
import * as dockerCommandUtils from "docker-common/dockercommandutils";
import * as fileUtils from "docker-common/fileutils";
import * as pipelineUtils from "docker-common/pipelineutils";
import ContainerConnection from "docker-commo... |
command.arg(context);
return connection.execCommand(command);
}
| {
context = tl.getPathInput("buildContext");
} | conditional_block |
containerbuild.ts | "use strict";
import * as path from "path";
import * as tl from "vsts-task-lib/task";
import * as dockerCommandUtils from "docker-common/dockercommandutils";
import * as fileUtils from "docker-common/fileutils";
import * as pipelineUtils from "docker-common/pipelineutils";
import ContainerConnection from "docker-commo... | command.arg(["-t", baseImageName]);
}
var memoryLimit = tl.getInput("memoryLimit");
if (memoryLimit) {
command.arg(["-m", memoryLimit]);
}
var context: string;
var useDefaultContext = tl.getBoolInput("useDefaultContext");
if (useDefaultContext) {
context = path.dirn... | });
}
var includeLatestTag = tl.getBoolInput("includeLatestTag");
if (baseImageName !== imageName && includeLatestTag) { | random_line_split |
containerbuild.ts | "use strict";
import * as path from "path";
import * as tl from "vsts-task-lib/task";
import * as dockerCommandUtils from "docker-common/dockercommandutils";
import * as fileUtils from "docker-common/fileutils";
import * as pipelineUtils from "docker-common/pipelineutils";
import ContainerConnection from "docker-commo... | (connection: ContainerConnection): any {
var command = connection.createCommand();
command.arg("build");
var dockerfilepath = tl.getInput("dockerFile", true);
let dockerFile = fileUtils.findDockerFile(dockerfilepath);
if(!tl.exist(dockerFile)) {
throw new Error(tl.loc('ContainerDockerF... | run | identifier_name |
app.js | ;(function() {
var ValueDirective = function() {
};
_.extend(ValueDirective.prototype, {
matcher: function($el) {
return $el.data('value');
},
run: function($el) {
$el.html($el.data('value'));
}
});
window.app = new xin.App({
el: x... |
},
localStorage: function(key, value) {
if(typeof value === 'function') {
this.storage('localStorage', key, undefined, value);
} else {
this.storage('localStorage', key, value);
}
},
clearStorage: function(type) { //... | {
this.storage('sessionStorage', key, value);
} | conditional_block |
app.js | ;(function() {
var ValueDirective = function() {
};
_.extend(ValueDirective.prototype, {
matcher: function($el) {
return $el.data('value');
},
run: function($el) {
$el.html($el.data('value'));
}
});
window.app = new xin.App({
el: x... | invoke: function(api, param, cb) {
api = api.split('.');
if(typeof(param) == "function") {
window.API[api[0]][api[1]](param);
} else {
delete arguments[0];
var opt = [],
j = 0;
for (var i in ... | }
},
| random_line_split |
Panel.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { assign } from 'lodash'
import autoBind from '../utils/autoBind'
const styles = {
'ClosedPanelWrapper': {
height: '40px'
},
'PanelWrapper': {
position: 'relative'
},
'Over': {
border: '1px dashed white',
ove... | color: 'white',
right: '10px',
fontSize: '16px',
top: '12px'
},
'OpenPanel': {
position: 'relative',
zIndex: '2',
top: '0',
left: '0',
padding: '7px',
paddingTop: '5px',
maxHeight: '30%',
display: 'block'
},
'ClosedPanel': {
height: '0',
position: 'relat... | random_line_split | |
Panel.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { assign } from 'lodash'
import autoBind from '../utils/autoBind'
const styles = {
'ClosedPanelWrapper': {
height: '40px'
},
'PanelWrapper': {
position: 'relative'
},
'Over': {
border: '1px dashed white',
ove... | (e) {
if (e.stopPropagation) {
e.stopPropagation() // stops the browser from redirecting.
}
const dragIndex = e.dataTransfer.getData('index')
const dropIndex = this.props.index.toString()
if (dragIndex !== dropIndex) {
this.props.reorder(dragIndex, dropIndex)
}
return false
}... | handleDrop | identifier_name |
Panel.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { assign } from 'lodash'
import autoBind from '../utils/autoBind'
const styles = {
'ClosedPanelWrapper': {
height: '40px'
},
'PanelWrapper': {
position: 'relative'
},
'Over': {
border: '1px dashed white',
ove... |
}
handleDragLeave() {
this.setState({ isOver: false })
// e.target.classList.remove('Over') // e.target is previous target element.
}
handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation() // stops the browser from redirecting.
}
const dragIndex = e.dataTransfer.getData('ind... | {
// e.target.classList.add('Over') // e.target is the current hover target.
this.setState({ isOver: true })
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.