PyPy 3 generator has a bug that calling `close` caused
    memory leak. Before it is fixed, use `throw` instead
191283
def _close_generator(g):
    
    if isinstance(g, generatorwrapper):
        g.close()
    elif _get_frame(g) is not None:
        try:
            g.throw(GeneratorExit_)
        except (StopIteration, GeneratorExit_):
            return
        else:
            raise RuntimeError("coroutine ignored GeneratorExit")
1016511
def close(self, for_shutdown=False, **_kwargs):
        
        if for_shutdown:
            super(PySOAPyLibMCCache, self).close()
1225081
@Override
  @SuppressWarnings("checkstyle:illegalcatch") // Catch throwable to feed it to error handler
  public void close() {

    LOG.entering(CLASS_NAME, "close");

    try {
      this.clock.close();
    } catch (final Throwable ex) {
      LOG.log(Level.SEVERE, "Error while closing the clock", ex);
      try {
        this.errorHandler.onNext(ex);
      } catch (final Throwable exHandling) {
        LOG.log(Level.SEVERE, "Error while handling the exception " + ex, exHandling);
      }
    } finally {
      try {
        this.errorHandler.close();
      } catch (final Throwable ex) {
        LOG.log(Level.SEVERE, "Error while closing the error handler", ex);
      }
    }

    LOG.exiting(CLASS_NAME, "close");
  }
911627
def close(self):
        
        if callable(getattr(self._file, 'close', None)):
            self._iterator.close()
        self._iterator = None
        self._unconsumed = None
        self.closed = True
993555
void closeImpl()
  {
    ReadStreamOld is = _is;
    _is = null;

    WriteStreamOld os = _os;
    _os = null;

    try {
      if (is != null)
        is.close();
    } catch (Throwable e) {
      log.log(Level.FINER, e.toString(), e);
    }

    try {
      if (os != null)
        os.close();
    } catch (Throwable e) {
      log.log(Level.FINER, e.toString(), e);
    }

    if (is != null) {
      _connProbe.end();

      if (_requestStartTime > 0)
        _requestTimeProbe.end(_requestStartTime);

      if (_isIdle)
        _idleProbe.end();
    }
  }
207430
def _wrapper(func, *args, **kwargs):
        ''

        try:
            if func.__name__ == "init":
                # init may not fail, as its return code is just stored as
                # private_data field of struct fuse_context
                return func(*args, **kwargs) or 0

            else:
                try:
                    return func(*args, **kwargs) or 0

                except OSError as e:
                    if e.errno > 0:
                        log.debug(
                            "FUSE operation %s raised a %s, returning errno %s.",
                            func.__name__, type(e), e.errno, exc_info=True)
                        return -e.errno
                    else:
                        log.error(
                            "FUSE operation %s raised an OSError with negative "
                            "errno %s, returning errno.EINVAL.",
                            func.__name__, e.errno, exc_info=True)
                        return -errno.EINVAL

                except Exception:
                    log.error("Uncaught exception from FUSE operation %s, "
                              "returning errno.EINVAL.",
                              func.__name__, exc_info=True)
                    return -errno.EINVAL

        except BaseException as e:
            self.__critical_exception = e
            log.critical(
                "Uncaught critical exception from FUSE operation %s, aborting.",
                func.__name__, exc_info=True)
            # the raised exception (even SystemExit) will be caught by FUSE
            # potentially causing SIGSEGV, so tell system to stop/interrupt FUSE
            fuse_exit()
            return -errno.EFAULT
39254
def close(self):
        '''
        '''
        if self.closed: return
        for func,arglist in self.callbacks:
            apply(func, arglist)
        self.closed = True
1215624
def close(self):
    """"""
    self.acquire()
    try:
      self.flush()
      try:
        # Do not close the stream if it's sys.stderr|stdout. They may be
        # redirected or overridden to files, which should be managed by users
        # explicitly.
        if self.stream not in (sys.stderr, sys.stdout) and (
            not hasattr(self.stream, 'isatty') or not self.stream.isatty()):
          self.stream.close()
      except ValueError:
        # A ValueError is thrown if we try to run isatty() on a closed file.
        pass
      super(PythonHandler, self).close()
    finally:
      self.release()
307227
function(startIndex) {
    ("production" !== process.env.NODE_ENV ? invariant(
      this.isInTransaction(),
      'Transaction.closeAll(): Cannot close transaction when none are open.'
    ) : invariant(this.isInTransaction()));
    var transactionWrappers = this.transactionWrappers;
    for (var i = startIndex; i < transactionWrappers.length; i++) {
      var wrapper = transactionWrappers[i];
      var initData = this.wrapperInitData[i];
      var errorThrown;
      try {
        // Catching errors makes debugging more difficult, so we start with
        // errorThrown set to true before setting it to false after calling
        // close -- if it's still set to true in the finally block, it means
        // wrapper.close threw.
        errorThrown = true;
        if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
          wrapper.close.call(this, initData);
        }
        errorThrown = false;
      } finally {
        if (errorThrown) {
          // The closer for wrapper i threw an error; close the remaining
          // wrappers but silence any exceptions from them to ensure that the
          // first error is the one to bubble up.
          try {
            this.closeAll(i + 1);
          } catch (e) {
          }
        }
      }
    }
    this.wrapperInitData.length = 0;
  }
300754
function pyPop(obj, prop, defaultValue){
   obj = (obj === undefined) ? {} : obj;

   if(obj.hasOwnProperty(prop)){
       var rv =  obj[prop];
       delete obj[prop];
       return rv;
   } else {
       return defaultValue;
   }
}
288505
def fix_ipython_startup(fn):
    
    BADSTR = 'TPython::Exec( "" )'
    GOODSTR = 'TPython::Exec( "" );'
    if sys.version_info[0] < 3:
        consts = fn.im_func.func_code.co_consts
    else:
        consts = fn.__code__.co_consts
    if BADSTR not in consts:
        return
    idx = consts.index(BADSTR)
    orig_refcount = sys.getrefcount(consts)
    del consts

    PyTuple_SetItem = ctypes.pythonapi.PyTuple_SetItem
    PyTuple_SetItem.argtypes = (ctypes.py_object,
                                ctypes.c_size_t,
                                ctypes.py_object)

    if sys.version_info[0] < 3:
        consts = ctypes.py_object(fn.im_func.func_code.co_consts)
    else:
        consts = ctypes.py_object(fn.im_func.__code__.co_consts)

    for _ in range(orig_refcount - 2):
        ctypes.pythonapi.Py_DecRef(consts)
    try:
        ctypes.pythonapi.Py_IncRef(GOODSTR)
        PyTuple_SetItem(consts, idx, GOODSTR)
    finally:
        for _ in range(orig_refcount - 2):
            ctypes.pythonapi.Py_IncRef(consts)
183077
def _silence():
    """"""

    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = _DummyFile()
    sys.stderr = _DummyFile()
    exception_occurred = False
    try:
        yield
    except:
        exception_occurred = True
        # Go ahead and clean up so that exception handling can work normally
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        raise

    if not exception_occurred:
        sys.stdout = old_stdout
        sys.stderr = old_stderr
317606
def eliot_friendly_generator_function(original):
    
    @wraps(original)
    def wrapper(*a, **kw):
        # Keep track of whether the next value to deliver to the generator is
        # a non-exception or an exception.
        ok = True

        # Keep track of the next value to deliver to the generator.
        value_in = None

        # Create the generator with a call to the generator function.  This
        # happens with whatever Eliot action context happens to be active,
        # which is fine and correct and also irrelevant because no code in the
        # generator function can run until we call send or throw on it.
        gen = original(*a, **kw)

        # Initialize the per-generator context to a copy of the current context.
        context = copy_context()
        while True:
            try:
                # Whichever way we invoke the generator, we will do it
                # with the Eliot action context stack we've saved for it.
                # Then the context manager will re-save it and restore the
                # "outside" stack for us.
                #
                # Regarding the support of Twisted's inlineCallbacks-like
                # functionality (see eliot.twisted.inline_callbacks):
                #
                # The invocation may raise the inlineCallbacks internal
                # control flow exception _DefGen_Return.  It is not wrong to
                # just let that propagate upwards here but inlineCallbacks
                # does think it is wrong.  The behavior triggers a
                # DeprecationWarning to try to get us to fix our code.  We
                # could explicitly handle and re-raise the _DefGen_Return but
                # only at the expense of depending on a private Twisted API.
                # For now, I'm opting to try to encourage Twisted to fix the
                # situation (or at least not worsen it):
                # https://twistedmatrix.com/trac/ticket/9590
                #
                # Alternatively, _DefGen_Return is only required on Python 2.
                # When Python 2 support is dropped, this concern can be
                # eliminated by always using `return value` instead of
                # `returnValue(value)` (and adding the necessary logic to the
                # StopIteration handler below).
                def go():
                    if ok:
                        value_out = gen.send(value_in)
                    else:
                        value_out = gen.throw(*value_in)
                    # We have obtained a value from the generator.  In
                    # giving it to us, it has given up control.  Note this
                    # fact here.  Importantly, this is within the
                    # generator's action context so that we get a good
                    # indication of where the yield occurred.
                    #
                    # This is noisy, enable only for debugging:
                    if wrapper.debug:
                        Message.log(message_type=u"yielded")
                    return value_out

                value_out = context.run(go)
            except StopIteration:
                # When the generator raises this, it is signaling
                # completion.  Leave the loop.
                break
            else:
                try:
                    # Pass the generator's result along to whoever is
                    # driving.  Capture the result as the next value to
                    # send inward.
                    value_in = yield value_out
                except:
                    # Or capture the exception if that's the flavor of the
                    # next value.  This could possibly include GeneratorExit
                    # which turns out to be just fine because throwing it into
                    # the inner generator effectively propagates the close
                    # (and with the right context!) just as you would want.
                    # True, the GeneratorExit does get re-throwing out of the
                    # gen.throw call and hits _the_generator_context's
                    # contextmanager.  But @contextmanager extremely
                    # conveniently eats it for us!  Thanks, @contextmanager!
                    ok = False
                    value_in = exc_info()
                else:
                    ok = True

    wrapper.debug = False
    return wrapper
1299263
function wrapNodeSocket(socket, reportError) {
  // Data traveling from node socket to consumer
  var incoming = makeChannel();
  // Data traveling from consumer to node socket
  var outgoing = makeChannel();

  var onDrain2 = wrapHandler(onReadable, onError);
  onTake = wrapHandler(onTake, onError);

  var paused = false;
  var ended = false;

  outgoing.take(onTake);
  socket.on("error", onError);
  socket.on("drain", wrap(onDrain, onError));
  socket.on("readable", wrap(onReadable, onError));
  socket.on("end", wrap(onEnd, onError));

  function onError(err) {
    if (err.code === "EPIPE" || err.code === "ECONNRESET") {
      return onEnd();
    }
    if (reportError) return reportError(err);
    console.error(err.stack);
  }

  function onTake(data) {
    if (ended) return;
    // console.log("TAKE", data);
    if (data === undefined) {
      ended = true;
      return socket.end();
    }
    if (socket.write(data)) {
      outgoing.take(onTake);
    }
    else {
      if (!paused) paused = true;
    }
  }

  function onDrain() {
    if (paused) {
      paused = false;
      outgoing.take(onTake);
    }
  }

  function onEnd() {
    if (ended) return;
    ended = true;
    incoming.put(undefined);
  }

  function onReadable() {
    if (ended) return;
    while (true) {
      var chunk = socket.read();
      // console.log("READ", chunk);
      if (!chunk) return;
      if (!incoming.put(chunk)) {
        incoming.drain(onDrain2);
        return;
      }
    }
  }

  return {
    put: outgoing.put,
    drain: outgoing.drain,
    take: incoming.take,
  };
}
735978
public void closeJsonStream() throws IOException {
		if (generator == null) {
			return;
		}

		while (!stack.isEmpty()) {
			writeEndComponent();
		}

		if (wrapInArray) {
			generator.writeEndArray();
		}

		if (closeGenerator) {
			generator.close();
		}
	}
749867
def throws_errors(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)

        # if no status code is provided, assume 400
        if isinstance(response, BugZooException):
            err_jsn = flask.jsonify(response.to_dict())
            return err_jsn, 400

        if isinstance(response, tuple) \
           and isinstance(response[0], BugZooException):
            err = response[0] # type: BugZooException
            err_jsn = flask.jsonify(err.to_dict())
            return (err_jsn, *response[1:])

        return response

    return wrapper
350659
def close(*args, **kwargs):
    """
    _, plt, _ = _import_plt()
    plt.close(*args, **kwargs)