internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: hylang/hy

Issue:
Misplaced tracebacks from some models created in the reader
```
$ echo ';;;;;;\na.b' >ex.hy
$ hy ex.hy 
Traceback (most recent call last):
  …
  File "/tmp/ex.hy", line 1, in <module>
    ;;;;;;
NameError: name 'a' is not defined
```

The error is wrongly attributed to line 1 because the reader fails to set position information for a model created during the expansion of `a.b` into `(. a b)`. Contrast with this case, which is correct:

```
$ echo ';;;;;;\n(. a b)' >ex.hy
$ hy ex.hy                     
Traceback (most recent call last):
  …
  File "/tmp/ex.hy", line 2, in <module>
    (. a b)
NameError: name 'a' is not defined
```

I believe it suffices to call `model.replace(model)` in `HyReader.fill_pos`, so that positions are fixed recursively. I just need to write a test.

This bug is more consequential than it sounds because it can crash pytest internally, when non-existent columns of the source are retrieved for a traceback. Hy's own error reporting doesn't fail so badly in such a case.


Discussion:

Resolving patch:
diff --git a/hy/reader/hy_reader.py b/hy/reader/hy_reader.py
--- a/hy/reader/hy_reader.py
+++ b/hy/reader/hy_reader.py
@@ -128,7 +128,9 @@ def fill_pos(self, model, start):
         """
         model.start_line, model.start_column = start
         model.end_line, model.end_column = self.pos
-        return model
+        return model.replace(model)
+          # `replace` will recurse into submodels and set any model
+          # positions that are still unset the same way.
 
     def read_default(self, key):
         """Default reader handler when nothing in the table matches.


Test patch:
diff --git a/tests/test_reader.py b/tests/test_reader.py
--- a/tests/test_reader.py
+++ b/tests/test_reader.py
@@ -410,6 +410,13 @@ def test_lex_line_counting_multi_inner():
     assert inner.start_column == 5
 
 
+def test_line_counting_dotted():
+    # https://github.com/hylang/hy/issues/2422
+    x, = tokenize(";;;;;\na.b")
+    for e in (x, *x):
+        assert e.start_line == 2
+
+
 def test_dicts():
     """Ensure that we can tokenize a dict."""
     objs = tokenize("{foo bar bar baz}")
Repository: hylang/hy

Issue:
`(hy.models.Symbol "#foo")` should be an error
for the same reason as `(hy.models.Symbol "5")`: `#foo` doesn't parse as a symbol. It parses as a reader-macro call.


Discussion:

Resolving patch:
diff --git a/hy/reader/hy_reader.py b/hy/reader/hy_reader.py
--- a/hy/reader/hy_reader.py
+++ b/hy/reader/hy_reader.py
@@ -98,7 +98,7 @@ def err(msg):
     if reader is None:
         if (
             not ident
-            or ident[:1] == ":"
+            or ident[0] in ":#"
             or any(isnormalizedspace(c) for c in ident)
             or HyReader.NON_IDENT.intersection(ident)
         ):


Test patch:
diff --git a/tests/macros/test_macro_processor.py b/tests/macros/test_macro_processor.py
--- a/tests/macros/test_macro_processor.py
+++ b/tests/macros/test_macro_processor.py
@@ -55,7 +55,7 @@ def test_macroexpand_nan():
 
 def test_macroexpand_source_data():
     # https://github.com/hylang/hy/issues/1944
-    ast = Expression([Symbol("#@"), String("a")])
+    ast = Expression([Symbol("when"), String("a")])
     ast.start_line = 3
     ast.start_column = 5
     bad = macroexpand_1(ast, "hy.core.macros")
diff --git a/tests/test_models.py b/tests/test_models.py
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -28,7 +28,8 @@ def test_symbol_or_keyword():
     for x in ("foo", "foo-bar", "foo_bar", "✈é😂⁂"):
         assert str(Symbol(x)) == x
         assert Keyword(x).name == x
-    for x in ("", ":foo", "5"):
+    for x in ("", ":foo", "5", "#foo"):
+        # https://github.com/hylang/hy/issues/2383
         with pytest.raises(ValueError):
             Symbol(x)
         assert Keyword(x).name == x
Repository: hylang/hy

Issue:
Any capitalization of `NaN` and `Inf` are parsed as imaginary numbers with uppercase suffix `J`
This issue seems related to #1288 and #1294. Floating-point special values such as `NaN` and `Inf` are required to be capitalized exactly as such, but when used in imaginary number literals with _uppercase_ `J` suffix, any capitalization is allowed. In the same spirit as #1288, I believe this is unintended/undesired behavior.

```hy
NaNj ; valid (good)
NANj ; invalid (good)
Infj ; valid (good)
iNfj ; invalid (good)

NaNJ ; valid (good)
NANJ ; valid (should not be!)
InfJ ; valid (good)
iNfJ ; valid (should not be!)
```

Interestingly enough, this behavior only occurs in pure-imaginary literals; it doesn't surface in "compound" complex literals, which seem to have the correct behavior:

```hy
1+NaNj ; valid (good)
1+NANJ ; invalid (good)
```


Discussion:
Yeah, this is a bug. Thanks for catching it.

Resolving patch:
diff --git a/hy/models.py b/hy/models.py
--- a/hy/models.py
+++ b/hy/models.py
@@ -361,7 +361,7 @@ def __new__(cls, real, imag=0, *args, **kwargs):
         if isinstance(real, str):
             value = super().__new__(cls, strip_digit_separators(real))
             p1, _, p2 = real.lstrip("+-").replace("-", "+").partition("+")
-            check_inf_nan_cap(p1, value.imag if "j" in p1 else value.real)
+            check_inf_nan_cap(p1, value.imag if "j" in p1.lower() else value.real)
             if p2:
                 check_inf_nan_cap(p2, value.imag)
             return value


Test patch:
diff --git a/tests/test_reader.py b/tests/test_reader.py
--- a/tests/test_reader.py
+++ b/tests/test_reader.py
@@ -225,9 +225,13 @@ def t(x):
     def f(x):
         return [Expression([Symbol("foo"), x])]
 
+    assert t("2j") == f(Complex(2.0j))
+    assert t("2J") == f(Complex(2.0j))
     assert t("2.j") == f(Complex(2.0j))
+    assert t("2.J") == f(Complex(2.0j))
     assert t("-0.5j") == f(Complex(-0.5j))
     assert t("1.e7j") == f(Complex(1e7j))
+    assert t("1.e7J") == f(Complex(1e7j))
     assert t("j") == f(Symbol("j"))
     assert t("J") == f(Symbol("J"))
     assert isnan(t("NaNj")[0][1].imag)
@@ -236,6 +240,13 @@ def f(x):
     assert t("Inf-Infj") == f(Complex(complex(float("inf"), float("-inf"))))
     assert t("Inf-INFj") == f(Symbol("Inf-INFj"))
 
+    # https://github.com/hylang/hy/issues/2521
+    assert isnan(t("NaNJ")[0][1].imag)
+    assert t("nanJ") == f(Symbol("nanJ"))
+    assert t("InfJ") == f(Complex(complex(0, float("inf"))))
+    assert t("iNfJ") == f(Symbol("iNfJ"))
+    assert t("Inf-INFJ") == f(Symbol("Inf-INFJ"))
+
 
 def test_lex_digit_separators():
Repository: obspy/obspy

Issue:
obspy.db: Indexer returns error for mseed log files
e.g.:

```
...
2012-09-17 15:27:05,700 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.256: float division
2012-09-17 15:27:06,261 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.257: float division
2012-09-17 15:27:06,734 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.258: float division
2012-09-17 15:27:06,989 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.259: float division
2012-09-17 15:27:06,990 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.260: float division
2012-09-17 15:27:07,118 [ERROR] [Reading stream] /opt/seishub/seishub/data/archive/2012/GR/FUR/LOG.L/GR.FUR..LOG.L.2012.261: float division
... 
```

those warnings should be skipped for log files.

Example file can be found at https://github.com/obspy/sandbox/blob/master/attachments/2012-09/GR.FUR..LOG.L.2012.257



Discussion:

Resolving patch:
diff --git a/obspy.db/obspy/db/indexer.py b/obspy.db/obspy/db/indexer.py
--- a/obspy.db/obspy/db/indexer.py
+++ b/obspy.db/obspy/db/indexer.py
@@ -515,13 +515,17 @@ def worker(_i, input_queue, work_queue, output_queue, log_queue, mappings={}):
                         log_queue.append(msg % (filepath, e))
                         continue
                 # generate preview of trace
-                try:
-                    trace = createPreview(trace, 30)
-                    result['preview'] = trace.data.dumps()
-                except Exception, e:
-                    msg = '[Creating preview] %s: %s'
-                    log_queue.append(msg % (filepath, e))
+                if '.LOG.L.' in file and trace.stats.channel == 'LOG':
+                    # create previews only for non-log files (see issue #400)
                     result['preview'] = None
+                else:
+                    try:
+                        trace = createPreview(trace, 30)
+                        result['preview'] = trace.data.dumps()
+                    except Exception, e:
+                        msg = '[Creating preview] %s: %s'
+                        log_queue.append(msg % (filepath, e))
+                        result['preview'] = None
                 # update dataset
                 dataset.append(result)
             del stream


Test patch:
Repository: obspy/obspy

Issue:
problem with libsignal
Currently there is a problem in libsignal:

```
/home/megies/git/obspy/obspy/signal/../lib/libsignal-Linux-64bit-py26.so: undefined symbol: stalta
```

This problem does not occur in the original merge of the stalta changes (obspy/obspy@f2364718ad3ea6a32c51e63ecceef2fe55c34b10) or the current f2py branch (krischer/obspy@f462a3e16eddb903aa61626e38e7926b6219f018). If the f2py branch gets adapted (obspy#431) this can probably be ignored.



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -491,7 +491,8 @@ def setupLibSignal():
                       sources=[src + 'recstalta.c', src + 'xcorr.c',
                                src + 'coordtrans.c', src + 'pk_mbaer.c',
                                src + 'filt_util.c', src + 'arpicker.c',
-                               src + 'bbfk.c', src_fft + 'fftpack.c',
+                               src + 'bbfk.c', src + 'stalta.c',
+                               src_fft + 'fftpack.c',
                                src_fft + 'fftpack_litemodule.c'],
                       export_symbols=symbols)
     return lib


Test patch:
Repository: obspy/obspy

Issue:
Dead link in obspy.signal.cross_correlation.xcorr docstring
obspy.signal.cross_correlation.xcorr refers to ticket #249 in its docstring (see here: http://docs.obspy.org/packages/autogen/obspy.signal.cross_correlation.xcorr.html)

This is an old trac link. Either it should be updated to https://github.com/obspy/obspy/issues/249 or, better, the relevant parts of this ticket discussion should be included in the docstring.

What do you think?



Discussion:
:+1: link should be updated to https://github.com/obspy/obspy/issues/249 and optionally it would be nice to have relevant info directly in the docstring.


Resolving patch:
diff --git a/obspy/signal/cross_correlation.py b/obspy/signal/cross_correlation.py
--- a/obspy/signal/cross_correlation.py
+++ b/obspy/signal/cross_correlation.py
@@ -65,7 +65,7 @@ def xcorr(tr1, tr2, shift_len, full_xcorr=False):
         `ObsPy-users mailing list
        <http://lists.obspy.org/pipermail/obspy-users/2011-March/000056.html>`_
        and
-       `ticket #249 <https://obspy.org/ticket/249>`_.
+       `issue #249 <https://github.com/obspy/obspy/issues/249>`_.
 
     .. rubric:: Example
 


Test patch:
Repository: obspy/obspy

Issue:
Array analysis matplotlib date conversion bug
From the mailinglist: http://lists.swapbytes.de/archives/obspy-users/2014-August/001478.html

> "Unix Time" to "Rata Die" conversion that takes place here 
> https://github.com/obspy/obspy/blob/master/obspy/signal/array_analysis.py#L1018 
> is wrong because "Rata Die" epoch starts at 1, not at zero. Add one and it is correct. The comment above that line is wrong. Should be days not hours. 
> 
> Below is a python command line session that hopefully explains why this is wrong 

``` python
>>> from time import time 
>>> from datetime import datetime 
>>> from matplotlib.dates import date2num 
>>> t = time() 
>>> t / (24. * 3600) +719162 - date2num(datetime.fromtimestamp(t)) 
-1.0 
```



Discussion:
~~shouldn't be the whole timestamp string (https://github.com/obspy/obspy/blob/master/obspy/signal/array_analysis.py#L886-L891)  an UTCDatetime object too? Would need an `mlabday`extension ...~~

ah my bad -> its only used for plots


Resolving patch:
diff --git a/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_1.py b/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_1.py
--- a/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_1.py
+++ b/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_1.py
@@ -1,4 +1,5 @@
 import matplotlib.pyplot as plt
+import matplotlib.dates as mdates
 
 from obspy.core import AttribDict, UTCDateTime, read
 from obspy.signal import cornFreq2Paz
@@ -90,7 +91,9 @@
     ax.set_xlim(out[0, 0], out[-1, 0])
     ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
 
-
+locator = mdates.AutoDateLocator()
+ax.xaxis.set_major_locator(locator)
+ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
 fig.autofmt_xdate()
 fig.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0)
 plt.show()
diff --git a/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_2.py b/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_2.py
--- a/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_2.py
+++ b/misc/docs/source/tutorial/code_snippets/beamforming_fk_analysis_2.py
@@ -77,7 +77,7 @@
     # frequency properties
     frqlow=1.0, frqhigh=8.0, prewhiten=0,
     # restrict output
-    semb_thres=-1e9, vel_thres=-1e9, timestamp='mlabday',
+    semb_thres=-1e9, vel_thres=-1e9,
     stime=UTCDateTime("20080217110515"), etime=UTCDateTime("20080217110545")
 )
 out = array_processing(st, **kwargs)
diff --git a/obspy/signal/array_analysis.py b/obspy/signal/array_analysis.py
--- a/obspy/signal/array_analysis.py
+++ b/obspy/signal/array_analysis.py
@@ -1016,8 +1016,8 @@ def array_processing(stream, win_len, win_frac, sll_x, slm_x, sll_y, slm_y,
     if timestamp == 'julsec':
         pass
     elif timestamp == 'mlabday':
-        # 719162 == hours between 1970 and 0001
-        res[:, 0] = res[:, 0] / (24. * 3600) + 719162
+        # 719163 == days between 1970 and 0001 + 1
+        res[:, 0] = res[:, 0] / (24. * 3600) + 719163
     else:
         msg = "Option timestamp must be one of 'julsec', or 'mlabday'"
         raise ValueError(msg)


Test patch:
Repository: obspy/obspy

Issue:
.fdsn: add EMSC web service shortcut
This (trivial) PR just adds a shortcut for the EMSC web service.



Discussion:

Resolving patch:
diff --git a/obspy/clients/fdsn/client.py b/obspy/clients/fdsn/client.py
--- a/obspy/clients/fdsn/client.py
+++ b/obspy/clients/fdsn/client.py
@@ -182,6 +182,15 @@ def __init__(self, base_url="IRIS", major_versions=None, user=None,
                    "Please change to 'Client('NIEP')'. This re-routing will "
                    "be removed in a future release.")
             warnings.warn(msg)
+        # Deprecate FDSN URL-shortcut 'NERIES' in favour of 'EMSC', see #1146.
+        # TODO: remove in 0.12.x or 1.x release
+        elif base_url.upper() == "NERIES":
+            base_url = "EMSC"
+            msg = ("FDSN short-URL 'NERIES' has been replaced by 'EMSC'. "
+                   "Please change to 'Client('EMSC')'. This re-routing will "
+                   "be removed in a future release.")
+            warnings.warn(msg)
+
         if base_url.upper() in URL_MAPPINGS:
             base_url = URL_MAPPINGS[base_url.upper()]
 
diff --git a/obspy/clients/fdsn/header.py b/obspy/clients/fdsn/header.py
--- a/obspy/clients/fdsn/header.py
+++ b/obspy/clients/fdsn/header.py
@@ -37,6 +37,7 @@ class FDSNRedirectException(FDSNException):
 URL_MAPPINGS = {
     "BGR": "http://eida.bgr.de",
     "ETH": "http://eida.ethz.ch",
+    "EMSC": "http://www.seismicportal.eu",
     "GEONET": "http://service.geonet.org.nz",
     "GFZ": "http://geofon.gfz-potsdam.de",
     "INGV": "http://webservices.rm.ingv.it",
@@ -47,7 +48,6 @@ class FDSNRedirectException(FDSNException):
     "LMU": "http://erde.geophysik.uni-muenchen.de",
     "NCEDC": "http://service.ncedc.org",
     "NIEP": "http://eida-sc3.infp.ro",
-    "NERIES": "http://www.seismicportal.eu",
     "ODC": "http://www.orfeus-eu.org",
     "ORFEUS": "http://www.orfeus-eu.org",
     "RESIF": "http://ws.resif.fr",


Test patch:
Repository: obspy/obspy

Issue:
Problem reading some TauP model files
I did not look into the details but `obspy.taup` has problems parsing certain files. Others work fine.

Problematic files:
- https://dl.dropboxusercontent.com/u/3866312/taup_models/jb.nd
- https://dl.dropboxusercontent.com/u/3866312/taup_models/pwdk.nd
- https://dl.dropboxusercontent.com/u/3866312/taup_models/jb.nd

Usage:

``` python
from obspy.taup.taup_create import TauP_Create

x = TauP_Create(input_filename='qdt.tvel', output_filename='blub')
x.loadVMod()
x.run()
```

Output:

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/lion/workspace/code/obspy/obspy/taup/taup_create.py", line 119, in run
    self.tMod = self.createTauModel(self.vMod)
  File "/Users/lion/workspace/code/obspy/obspy/taup/taup_create.py", line 85, in createTauModel
    SlownessModel.DEFAULT_SLOWNESS_TOLERANCE)
  File "/Users/lion/workspace/code/obspy/obspy/taup/slowness_model.py", line 76, in __init__
    self.createSample()
  File "/Users/lion/workspace/code/obspy/obspy/taup/slowness_model.py", line 153, in createSample
    self.depthIncCheck()
  File "/Users/lion/workspace/code/obspy/obspy/taup/slowness_model.py", line 1012, in depthIncCheck
    'P')
  File "/Users/lion/workspace/code/obspy/obspy/taup/velocity_model.py", line 185, in evaluateAbove
    layer = self.layers[self.layerNumberAbove(depth)]
  File "/Users/lion/workspace/code/obspy/obspy/taup/velocity_model.py", line 132, in layerNumberAbove
    raise LookupError("No such layer.")
LookupError: No such layer.
```



Discussion:
The problematic files are `.nd`, but the example is `qdt.tvel`?


Resolving patch:
diff --git a/obspy/taup/slowness_model.py b/obspy/taup/slowness_model.py
--- a/obspy/taup/slowness_model.py
+++ b/obspy/taup/slowness_model.py
@@ -1008,8 +1008,10 @@ def depthIncCheck(self):
                     smask = velocity == 0
                     if not self.allowInnerCoreS:
                         smask |= new_depth >= self.vMod.iocbDepth
-                    velocity[smask] = self.vMod.evaluateAbove(new_depth[smask],
-                                                              'P')
+                    if np.any(smask):
+                        velocity[smask] = self.vMod.evaluateAbove(
+                            new_depth[smask],
+                            'P')
 
                     slowness = self.toSlowness(velocity, new_depth)
                 else:
diff --git a/obspy/taup/taup_create.py b/obspy/taup/taup_create.py
--- a/obspy/taup/taup_create.py
+++ b/obspy/taup/taup_create.py
@@ -122,8 +122,9 @@ def run(self):
             if self.debug:
                 print("Done calculating Tau branches.")
 
-            if not os.path.exists(os.path.dirname(self.output_filename)):
-                os.makedirs(os.path.dirname(self.output_filename))
+            dirname = os.path.dirname(self.output_filename)
+            if dirname and not os.path.exists(dirname):
+                os.makedirs(dirname)
             self.tMod.serialize(self.output_filename)
             if self.debug:
                 print("Done Saving " + self.output_filename)


Test patch:
Repository: obspy/obspy

Issue:
Calling "obspy-runtests -v" without basemap or cartopy installed will skip all obspy.imaging tests
see http://tests.obspy.org/48185/#1



Discussion:

Resolving patch:
diff --git a/obspy/scripts/runtests.py b/obspy/scripts/runtests.py
--- a/obspy/scripts/runtests.py
+++ b/obspy/scripts/runtests.py
@@ -326,6 +326,22 @@ def _create_report(ttrs, timetaken, log, server, hostname, sorted_tests,
     result['errors'] = errors
     result['failures'] = failures
     result['skipped'] = skipped
+    # try to append info on skipped tests:
+    result['skipped_tests_details'] = []
+    try:
+        for module, testresult_ in ttrs.items():
+            if testresult_.skipped:
+                for skipped_test, skip_message in testresult_.skipped:
+                    result['skipped_tests_details'].append(
+                        (module, skipped_test.__module__,
+                         skipped_test.__class__.__name__,
+                         skipped_test._testMethodName, skip_message))
+    except:
+        exc_type, exc_value, exc_tb = sys.exc_info()
+        print("\n".join(traceback.format_exception(exc_type, exc_value,
+                                                   exc_tb)))
+        result['skipped_tests_details'] = []
+
     if ci_url is not None:
         result['ciurl'] = ci_url
     if pr_url is not None:
@@ -617,6 +633,9 @@ def run(argv=None, interactive=True):
                         help='verbose mode')
     parser.add_argument('-q', '--quiet', action='store_true',
                         help='quiet mode')
+    parser.add_argument('--raise-all-warnings', action='store_true',
+                        help='All warnings are raised as exceptions when this '
+                             'flag is set. Only for debugging purposes.')
 
     # filter options
     filter = parser.add_argument_group('Module Filter',
@@ -678,9 +697,7 @@ def run(argv=None, interactive=True):
     if args.verbose:
         verbosity = 2
         # raise all NumPy warnings
-        np.seterr(all='raise')
-        # raise user and deprecation warnings
-        warnings.simplefilter("error", UserWarning)
+        np.seterr(all='warn')
     elif args.quiet:
         verbosity = 0
         # ignore user and deprecation warnings
@@ -694,6 +711,12 @@ def run(argv=None, interactive=True):
         np.seterr(all='print')
         # ignore user warnings
         warnings.simplefilter("ignore", UserWarning)
+    # whether to raise any warning that's appearing
+    if args.raise_all_warnings:
+        # raise all NumPy warnings
+        np.seterr(all='raise')
+        # raise user and deprecation warnings
+        warnings.simplefilter("error", UserWarning)
     # check for send report option or environmental settings
     if args.report or 'OBSPY_REPORT' in os.environ.keys():
         report = True


Test patch:
Repository: obspy/obspy

Issue:
Slow retrieval from earthworm wave server
Pulling long segments of continuous data from an earthworm wave server takes a very long time. 

clients.earthworm.waveserver.get_waveforms() makes a copy of the server response for each tracebuf extracted. This causes the time needed for processing the data to grow very quickly as the size of the server response grows.


Discussion:

Resolving patch:
diff --git a/obspy/clients/earthworm/waveserver.py b/obspy/clients/earthworm/waveserver.py
--- a/obspy/clients/earthworm/waveserver.py
+++ b/obspy/clients/earthworm/waveserver.py
@@ -312,11 +312,21 @@ def read_wave_server_v(server, port, scnl, start, end, timeout=None):
     bytesread = 1
     p = 0
     while bytesread and p < len(dat):
-        bytesread = new.read_tb2(dat[p:])
-        if bytesread:
+        if len(dat) > p + 64:
+            head = dat[p:p + 64]
+            p += 64
+            new.parse_header(head)
+            nbytes = new.ndata * new.inputType.itemsize
+
+            if len(dat) < p + nbytes:
+                break   # not enough array to hold data specified in header
+
+            tbd = dat[p:p + nbytes]
+            p += nbytes
+            new.parse_data(tbd)
+
             tbl.append(new)
             new = TraceBuf2()  # empty..filled on next iteration
-            p += bytesread
     return tbl
 
 


Test patch: