Question:
// trackSyncPtrChangesInCreate makes sure the correct set of refs and
// unrefs, from the syncOps on the unmerged branch, makes it into the
// createOp for a new file.

func trackSyncPtrChangesInCreate(
	mostRecentTargetPtr data.BlockPointer, unmergedChain *crChain,
	unmergedChains *crChains, toName string) {
	targetChain, ok := unmergedChains.byMostRecent[mostRecentTargetPtr]
	var refs, unrefs []data.BlockPointer
	if ok && targetChain.isFile() {
		// The create op also needs to reference the child block ptrs
		// created by any sync ops (and not unreferenced by future
		// ones).
		for _, op := range targetChain.ops {
			syncOp, ok := op.(*syncOp)
			if !ok {
				continue
			}
			for _, ref := range op.Refs() {
				if !unmergedChains.isDeleted(ref) {
					refs = append(refs, ref)
				}
			}
			for _, unref := range op.Unrefs() {
				unrefs = append(unrefs, unref)
			}
			// Account for the file ptr too, if it's the most recent.
			filePtr := syncOp.File.Ref
			_, isMostRecent := unmergedChains.byMostRecent[filePtr]
			if isMostRecent && !unmergedChains.isDeleted(filePtr) {
				refs = append(refs, filePtr)
			}
		}
	}
	if len(refs) > 0 {
		for _, uop := range unmergedChain.ops {
			cop, ok := uop.(*createOp)
			if !ok || cop.NewName != toName {
				continue
			}
			for _, ref := range refs {
				cop.AddRefBlock(ref)
			}
			for _, unref := range unrefs {
				cop.AddUnrefBlock(unref)
			}
			break
		}
	}
}

def create_tar_archive(self):

        #file filter
        EXCLUDE_FILES = glob.glob(os.path.join(self.savefolder, 'cells'))
        EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder,
                                                'populations', 'subsamples'))
        EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder,
                                                'raw_nest_output'))

        def filter_function(tarinfo):
            print(tarinfo.name)
            if len([f for f in EXCLUDE_FILES if os.path.split(tarinfo.name)[-1]
                    in os.path.split(f)[-1]]) > 0 or \
               len([f for f in EXCLUDE_FILES if os.path.split(tarinfo.path)[-1]
                    in os.path.split(f)[-1]]) > 0:
                print('excluding %s' % tarinfo.name)

                return None
            else:
                return tarinfo

        if RANK == 0:
            print('creating archive %s' % (self.savefolder + '.tar'))
            #open file
            f = tarfile.open(self.savefolder + '.tar', 'w')
            #avoid adding files to repo as /scratch/$USER/hybrid_model/...
            arcname = os.path.split(self.savefolder)[-1]

            f.add(name=self.savefolder,
                  arcname=arcname,
                  filter=filter_function)
            f.close()

        #resync
        COMM.Barrier()

Instruction: Given a code description, retrieve the corresponding code.


Question:
java.io thinks that a read at EOF is an error and should return -1, contrary to traditional
Unix practice where you'd read until you got 0 bytes (and any future read would return -1).

public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
        if (byteCount == 0) {
            return 0;
        }
        try {
            int readCount = Libcore.os.read(fd, bytes, byteOffset, byteCount);
            if (readCount == 0) {
                return -1;
            }
            return readCount;
        } catch (ErrnoException errnoException) {
            if (errnoException.errno == EAGAIN) {
                // We return 0 rather than throw if we try to read from an empty non-blocking pipe.
                return 0;
            }
            throw errnoException.rethrowAsIOException();
        }
    }

public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value)
    {
        try
        {
            final byte[] filler;
            if (0 != value)
            {
                filler = new byte[BLOCK_SIZE];
                Arrays.fill(filler, value);
            }
            else
            {
                filler = FILLER;
            }

            final ByteBuffer byteBuffer = ByteBuffer.wrap(filler);
            fileChannel.position(position);

            final int blocks = (int)(length / BLOCK_SIZE);
            final int blockRemainder = (int)(length % BLOCK_SIZE);

            for (int i = 0; i < blocks; i++)
            {
                byteBuffer.position(0);
                fileChannel.write(byteBuffer);
            }

            if (blockRemainder > 0)
            {
                byteBuffer.position(0);
                byteBuffer.limit(blockRemainder);
                fileChannel.write(byteBuffer);
            }
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


def chat_show(self, chat_id, **kwargs):
        ""
        api_path = "/api/v2/chats/{chat_id}"
        api_path = api_path.format(chat_id=chat_id)
        return self.call(api_path, **kwargs)

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // NewLocker return new lock

func NewLocker(lockerConfig config.Locker) (*lock, error) {
	c, _, err := zk.Connect(lockerConfig.Address, time.Millisecond*100)
	if err != nil {
		return nil, err
	}
	return &lock{c}, nil
}

public static int copy(Reader reader, Writer writer, boolean closeWriter) {
        if (closeWriter) {
            return write(reader).ensureCloseSink().to(writer);
        } else {
            return write(reader).to(writer);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
A callback function that is invoked by cURL for streaming down.

@param resource $curl_handle (Required) The cURL handle for the request.
@param binary $data (Required) The data to write.
@return integer The number of bytes written.

public function streaming_write_callback($curl_handle, $data)
    {
        $code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);

        if (intval($code) / 100 != 2)
        {
            $this->response_error_body .= $data;
            return strlen($data);
        }

        $length = strlen($data);
        $written_total = 0;
        $written_last = 0;

        while ($written_total < $length) {
            $written_last = fwrite($this->write_stream, substr($data, $written_total));

            if ($written_last === false) {
                return $written_total;
            }

            $written_total += $written_last;
        }

        // Execute callback function
        if ($this->registered_streaming_write_callback) {
            call_user_func($this->registered_streaming_write_callback, $curl_handle, $written_total);
        }

        return $written_total;
    }

func (c *Client) openWriter(resp *Response) stateFunc {
	if !resp.Request.NoCreateDirectories {
		resp.err = mkdirp(resp.Filename)
		if resp.err != nil {
			return c.closeResponse
		}
	}

	// compute write flags
	flag := os.O_CREATE | os.O_WRONLY
	if resp.fi != nil {
		if resp.DidResume {
			flag = os.O_APPEND | os.O_WRONLY
		} else {
			flag = os.O_TRUNC | os.O_WRONLY
		}
	}

	// open file
	f, err := os.OpenFile(resp.Filename, flag, 0644)
	if err != nil {
		resp.err = err
		return c.closeResponse
	}
	resp.writer = f

	// seek to start or end
	whence := os.SEEK_SET
	if resp.bytesResumed > 0 {
		whence = os.SEEK_END
	}
	_, resp.err = f.Seek(0, whence)
	if resp.err != nil {
		return c.closeResponse
	}

	// init transfer
	if resp.bufferSize < 1 {
		resp.bufferSize = 32 * 1024
	}
	b := make([]byte, resp.bufferSize)
	resp.transfer = newTransfer(
		resp.Request.Context(),
		resp.Request.RateLimiter,
		resp.writer,
		resp.HTTPResponse.Body,
		b)

	// next step is copyFile, but this will be called later in another goroutine
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Convert convolution layer from keras to coreml.

    Parameters
    ----------
    keras_layer: layer
        A keras layer object.

    builder: NeuralNetworkBuilder
        A neural network builder object.

def convert_convolution(builder, layer, input_names, output_names, keras_layer):

    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    has_bias = keras_layer.bias
    is_deconv = isinstance(keras_layer, keras.layers.convolutional.Deconvolution2D)

    # Get the weights from keras.
    # Keras stores convolution weights as list of numpy arrays
    weightList = keras_layer.get_weights()
    output_shape = list(filter(None, keras_layer.output_shape))[:-1]

    # Parameter
    height, width, channels, n_filters = weightList[0].shape
    stride_height, stride_width = keras_layer.subsample

    # Weights and bias terms
    W = weightList[0]
    b = weightList[1] if has_bias else None

    # dilation factors
    dilation_factors = [1,1]
    if isinstance(keras_layer, keras.layers.convolutional.AtrousConvolution2D):
        dilation_factors = list(keras_layer.atrous_rate)

    builder.add_convolution(name = layer,
             kernel_channels = channels,
             output_channels = n_filters,
             height = height,
             width = width,
             stride_height = stride_height,
             stride_width = stride_width,
             border_mode = keras_layer.border_mode,
             groups = 1,
             W = W,
             b = b,
             has_bias = has_bias,
             is_deconv = is_deconv,
             output_shape = output_shape,
             input_name = input_name,
             output_name = output_name,
             dilation_factors = dilation_factors)

public function getProfile()
    {
        if (!$this->kernel->getContainer()->has('profiler')) {
            return false;
        }

        return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Don't save Buffer.current.

def save_excursion
      old_point = new_mark
      old_mark = @mark&.dup
      old_column = @goal_column
      begin
        yield
      ensure
        point_to_mark(old_point)
        old_point.delete
        if old_mark
          @mark.location = old_mark.location
          old_mark.delete
        end
        @goal_column = old_column
      end
    end

func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
	// This code assumes that bufio.Writer.buf[:1] is passed to the
	// bufio.Writer's underlying writer.
	var wh writeHook
	bw.Reset(&wh)
	bw.WriteByte(0)
	bw.Flush()

	bw.Reset(originalWriter)

	return wh.p[:cap(wh.p)]
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
register events for elements
@param element

function (element) {
      var id = element.getAttribute('id');

      // on db click show formula
      element.addEventListener('dblclick', function () {
        var item = instance.matrix.getItem(id);

        if (item && item.formula) {
          item.formulaEdit = true;
          element.value = '=' + item.formula;
        }
      });

      element.addEventListener('blur', function () {
        var item = instance.matrix.getItem(id);

        if (item) {
          if (item.formulaEdit) {
            element.value = item.value || item.error;
          }

          item.formulaEdit = false;
        }
      });

      // if pressed ESC restore original value
      element.addEventListener('keyup', function (event) {
        switch (event.keyCode) {
          case 13: // ENTER
          case 27: // ESC
            // leave cell
            listen();
            break;
        }
      });

      // re-calculate formula if ref cells value changed
      element.addEventListener('change', function () {
        // reset and remove item
        instance.matrix.removeItem(id);

        // check if inserted text could be the formula
        var value = element.value;

        if (value[0] === '=') {
          element.setAttribute('data-formula', value.substr(1));
          registerElementInMatrix(element);
        }

        // get ref cells and re-calculate formulas
        recalculateElementDependencies(element);
      });
    }

function() {
	var evt = document.createEvent("MouseEvents");
	evt.initMouseEvent("click", true, true, window,
		0, 0, 0, 0, 0, false, false, false, false, 0, null);

	return !this._node.dispatchEvent(evt);
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Delete file from share
    :param azure.storage.file.FileService client: file client
    :param str fileshare: file share
    :param str name: file name
    :param int timeout: timeout

def delete_file(client, fileshare, name, timeout=None):
    # type: (azure.storage.file.FileService, str, str, int) -> None

    dir, fpath, snapshot = parse_file_path(name)
    if blobxfer.util.is_not_empty(snapshot):
        raise RuntimeError(
            'attempting to delete single file snapshot: {}/{}'.format(
                fileshare, name))
    client.delete_file(
        share_name=fileshare,
        directory_name=dir,
        file_name=fpath,
        timeout=timeout,
    )

public File getLocalFile(URL remoteUri)
    {
        StringBuilder sb = new StringBuilder();

        String host = remoteUri.getHost();
        String query = remoteUri.getQuery();
        String path = remoteUri.getPath();

        if (host != null)
        {
            sb.append(host);
        }
        if (path != null)
        {
            sb.append(path);
        }
        if (query != null)
        {
            sb.append('?');
            sb.append(query);
        }

        String name;

        final int maxLen = 250;

        if (sb.length() < maxLen)
        {
            name = sb.toString();
        }
        else
        {
            name = sb.substring(0, maxLen);
        }

        name = name.replace('?', '$');
        name = name.replace('*', '$');
        name = name.replace(':', '$');
        name = name.replace('<', '$');
        name = name.replace('>', '$');
        name = name.replace('"', '$');

        File f = new File(cacheDir, name);

        return f;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // NewRocRWithSrcLen creates a Rate of Change Ratio Indicator (RocR) for offline usage

func NewRocRWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *RocR, err error) {
	ind, err := NewRocR(timePeriod, selectData)

	// only initialise the storage if there is enough source data to require it
	if sourceLength-uint(ind.GetLookbackPeriod()) > 1 {
		ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))
	}

	return ind, err
}

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

Instruction: Given a code description, retrieve the corresponding code.


Question: Insert HTML theme configurations.

def _insert_html_configs(c, *, project_name, short_project_name):

    # Use the lsst-sphinx-bootstrap-theme
    c['templates_path'] = [
        '_templates',
        lsst_sphinx_bootstrap_theme.get_html_templates_path()]
    c['html_theme'] = 'lsst_sphinx_bootstrap_theme'
    c['html_theme_path'] = [lsst_sphinx_bootstrap_theme.get_html_theme_path()]

    # Theme options are theme-specific and customize the look and feel of a
    # theme further.  For a list of options available for each theme, see the
    # documentation.
    c['html_theme_options'] = {'logotext': short_project_name}

    # The name for this set of Sphinx documents.  If None, it defaults to
    # "<project> v<release> documentation".
    c['html_title'] = project_name

    # A shorter title for the navigation bar.  Default is the same as
    # html_title.
    c['html_short_title'] = short_project_name

    # The name of an image file (relative to this directory) to place at the
    # top of the sidebar.
    c['html_logo'] = None

    # The name of an image file (within the static path) to use as favicon of
    # the docs.  This file should be a Windows icon file (.ico) being 16x16 or
    # 32x32 pixels large.
    c['html_favicon'] = None

    # Add any paths that contain custom static files (such as style sheets)
    # here, relative to this directory. They are copied after the builtin
    # static files, so a file named "default.css" will overwrite the builtin
    # "default.css".
    if os.path.isdir('_static'):
        c['html_static_path'] = ['_static']
    else:
        # If a project does not have a _static/ directory, don't list it
        # so that there isn't a warning.
        c['html_static_path'] = []

    # Add any extra paths that contain custom files (such as robots.txt or
    # .htaccess) here, relative to this directory. These files are copied
    # directly to the root of the documentation.
    # html_extra_path = []

    # If not '', a 'Last updated on:' timestamp is inserted at every page
    # bottom, using the given strftime format.
    c['html_last_updated_fmt'] = '%b %d, %Y'

    # If true, SmartyPants will be used to convert quotes and dashes to
    # typographically correct entities.
    c['html_use_smartypants'] = True

    # If false, no module index is generated.
    c['html_domain_indices'] = False

    # If false, no index is generated.
    c['html_use_index'] = False

    # If true, the index is split into individual pages for each letter.
    c['html_split_index'] = False

    # If true, links to the reST sources are added to the pages.
    c['html_show_sourcelink'] = True

    # If true, "Created using Sphinx" is shown in the HTML footer. Default is
    # True.
    c['html_show_sphinx'] = True

    # If true, "(C) Copyright ..." is shown in the HTML footer. Default is
    # True.
    c['html_show_copyright'] = True

    # If true, an OpenSearch description file will be output, and all pages
    # will contain a <link> tag referring to it.  The value of this option must
    # be the base URL from which the finished HTML is served.
    # html_use_opensearch = ''

    # This is the file name suffix for HTML files (e.g. ".xhtml").
    c['html_file_suffix'] = '.html'

    # Language to be used for generating the HTML full-text search index.
    c['html_search_language'] = 'en'

    # A dictionary with options for the search language support, empty by
    # default.  Now only 'ja' uses this config value
    # html_search_options = {'type': 'default'}

    # The name of a javascript file (relative to the configuration directory)
    # that implements a search results scorer. If empty, the default will be
    # used.
    # html_search_scorer = 'scorer.js'

    return c

public function getHtml($exception)
    {
        if (!$exception instanceof FlattenException) {
            $exception = FlattenException::create($exception);
        }

        return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Check if command can be run

 @return [Boolean]

 @api public

def command?(cmd)
      !!system(cmd, out: ::File::NULL, err: ::File::NULL)
    end

def get_all_published_ships_basic(db_connection):

    if not hasattr(get_all_published_ships_basic, '_results'):
        sql = 'CALL get_all_published_ships_basic();'
        results = execute_sql(sql, db_connection)
        get_all_published_ships_basic._results = results

    return get_all_published_ships_basic._results

Instruction: Given a code description, retrieve the corresponding code.


Question:
// DeleteRelease removes an existing release, if it exists. If it does not exist,
// DeleteRelease returns an error

func (g *GHR) DeleteRelease(ctx context.Context, ID int64, tag string) error {

	err := g.GitHub.DeleteRelease(ctx, ID)
	if err != nil {
		return err
	}

	err = g.GitHub.DeleteTag(ctx, tag)
	if err != nil {
		return err
	}

	// This is because sometimes the process of creating a release on GitHub
	// is faster than deleting a tag.
	time.Sleep(5 * time.Second)

	return nil
}

public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $this->checkOptionsForValidity($options);

        $this->shell->execute('rm -f ' . $options['targetFile'] . '; mkdir -p ' . dirname($options['targetFile']), $node, $deployment);
        $sourcePath = $deployment->getApplicationReleasePath($application);

        $tarOptions = sprintf(' --transform="s,^%s,%s," ', ltrim($sourcePath, '/'), $options['baseDirectory']);
        if (isset($options['exclude']) && is_array($options['exclude'])) {
            foreach ($options['exclude'] as $excludePattern) {
                $tarOptions .= sprintf(' --exclude="%s" ', $excludePattern);
            }
        }

        if (substr($options['targetFile'], -7) === '.tar.gz') {
            $tarOptions .= sprintf(' -czf %s %s', $options['targetFile'], $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
        } elseif (substr($options['targetFile'], -8) === '.tar.bz2') {
            $tarOptions .= sprintf(' -cjf %s %s', $options['targetFile'], $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
        } elseif (substr($options['targetFile'], -4) === '.zip') {
            $temporaryDirectory = sys_get_temp_dir() . '/' . uniqid('f3_deploy');
            $this->shell->execute(sprintf('mkdir -p %s', $temporaryDirectory), $node, $deployment);
            $tarOptions .= sprintf(' -cf %s/out.tar %s', $temporaryDirectory, $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
            $this->shell->execute(sprintf('cd %s; tar -xf out.tar; rm out.tar; zip --quiet -9 -r out %s', $temporaryDirectory, $options['baseDirectory']), $node, $deployment);
            $this->shell->execute(sprintf('mv %s/out.zip %s; rm -Rf %s', $temporaryDirectory, $options['targetFile'], $temporaryDirectory), $node, $deployment);
        } else {
            throw new TaskExecutionException('Unknown target file format', 1314248387);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Unmarshals the given map source into a bean.
@param source the source
@return the plugin

public static PluginBean unmarshallPlugin(Map<String, Object> source) {
        if (source == null) {
            return null;
        }
        PluginBean bean = new PluginBean();
        bean.setId(asLong(source.get("id")));
        bean.setName(asString(source.get("name")));
        bean.setDescription(asString(source.get("description")));
        bean.setCreatedBy(asString(source.get("createdBy")));
        bean.setCreatedOn(asDate(source.get("createdOn")));
        bean.setGroupId(asString(source.get("groupId")));
        bean.setArtifactId(asString(source.get("artifactId")));
        bean.setVersion(asString(source.get("version")));
        bean.setType(asString(source.get("type")));
        bean.setClassifier(asString(source.get("classifier")));
        bean.setDeleted(asBoolean(source.get("deleted")));
        postMarshall(bean);
        return bean;
    }

protected OutputsModel toOutputsModel(Output[] outputs, KnowledgeNamespace knowledgeNamespace) {
        OutputsModel outputsModel = null;
        if (outputs != null) {
            for (Output output : outputs) {
                if (output != null) {
                    OutputModel outputModel = new V1OutputModel(knowledgeNamespace.uri());
                    String from = output.from();
                    if (!UNDEFINED.equals(from)) {
                        outputModel.setFrom(from);
                    }
                    String to = output.to();
                    if (!UNDEFINED.equals(to)) {
                        outputModel.setTo(to);
                    }
                    if (outputsModel == null) {
                        outputsModel = new V1OutputsModel(knowledgeNamespace.uri());
                    }
                    outputsModel.addOutput(outputModel);
                }
            }
        }
        return outputsModel;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Patch applies the patch and returns the patched serviceAccount.

func (c *FakeServiceAccounts) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *corev1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(serviceaccountsResource, c.ns, name, pt, data, subresources...), &corev1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.ServiceAccount), err
}

def create_service( name, git, path )
      ok = create_dir( name )
      ok = clone_service_shell( name, git ) if ok &&   path.nil?
      ok = copy_service_shell( name, path ) if ok && ! path.nil?
      ok = remove_dot_git( name, git )      if ok
      ok = replace_strings( name )          if ok

      if ok
        puts "Success! ./#{name} created."
        Kernel::exit( KERNEL_EXIT_SUCCESS )
      else
        Kernel::exit( KERNEL_EXIT_FAILURE )
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Caches the commerce wish list item in the entity cache if it is enabled.

@param commerceWishListItem the commerce wish list item

@Override
	public void cacheResult(CommerceWishListItem commerceWishListItem) {
		entityCache.putResult(CommerceWishListItemModelImpl.ENTITY_CACHE_ENABLED,
			CommerceWishListItemImpl.class,
			commerceWishListItem.getPrimaryKey(), commerceWishListItem);

		finderCache.putResult(FINDER_PATH_FETCH_BY_CW_CPI_CP,
			new Object[] {
				commerceWishListItem.getCommerceWishListId(),
				commerceWishListItem.getCPInstanceUuid(),
				commerceWishListItem.getCProductId()
			}, commerceWishListItem);

		commerceWishListItem.resetOriginalValues();
	}

public void marshall(ElastiCacheInstanceDetails elastiCacheInstanceDetails, ProtocolMarshaller protocolMarshaller) {

        if (elastiCacheInstanceDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getNodeType(), NODETYPE_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getProductDescription(), PRODUCTDESCRIPTION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Method which converts the object instance, its attributes and children to a string of lilypond code

        :return: str of lilypond code

def toLily(self):
        '''

        '''
        lilystring = ""
        if self.duration > 0:
            lilystring += "r" + str(self.duration)
        return lilystring

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

Instruction: Given a code description, retrieve the corresponding code.


Question:
// You should always use this function to get a new ListSnapshotsParams instance,
// as then you are sure you have configured all required params

func (s *SnapshotService) NewListSnapshotsParams() *ListSnapshotsParams {
	p := &ListSnapshotsParams{}
	p.p = make(map[string]interface{})
	return p
}

def blueprint(self, blueprint, **options):
        '''
        '''
        if blueprint.name in self.blueprints:
            assert self.blueprints[blueprint.name] is blueprint, \
                'A blueprint with the name "%s" is already registered.  ' \
                'Blueprint names must be unique.' % \
                (blueprint.name,)
        else:
            self.blueprints[blueprint.name] = blueprint
            self._blueprint_order.append(blueprint)
        blueprint.register(self, options)

Instruction: Given a code description, retrieve the corresponding code.


Question: Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``.

def _run_formula(self, variable, population, period):

        formula = variable.get_formula(period)
        if formula is None:
            return None

        if self.trace:
            parameters_at = self.trace_parameters_at_instant
        else:
            parameters_at = self.tax_benefit_system.get_parameters_at_instant

        if formula.__code__.co_argcount == 2:
            array = formula(population, period)
        else:
            array = formula(population, period, parameters_at)

        self._check_formula_result(array, variable, population, period)
        return array

public static function extractFromEnvironment()
    {
        $getServerVar = function ($key) {
            return isset($_SERVER[$key]) ? $_SERVER[$key] : null;
        };

        $request = new Request();
        $request->setMethod($getServerVar('REQUEST_METHOD'));
        $request->setRequestUri($getServerVar('REQUEST_URI'));
        $request->setPostData($_POST);
        $request->setQueryData($_GET);
        $request->setEnvironmentData($_SERVER);
        $request->setCookieData($_COOKIE);
        $request->setFileData($_FILES);
        return $request;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OpenshiftAPIServerConfig.

func (in *OpenshiftAPIServerConfig) DeepCopy() *OpenshiftAPIServerConfig {
	if in == nil {
		return nil
	}
	out := new(OpenshiftAPIServerConfig)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetDBParameterGroupFamily sets the DBParameterGroupFamily field's value.

func (s *DescribeEngineDefaultClusterParametersInput) SetDBParameterGroupFamily(v string) *DescribeEngineDefaultClusterParametersInput {
	s.DBParameterGroupFamily = &v
	return s
}

def update_family(self):
        """"""
        self.chain.connection.log("Detecting hw family")
        family = self.driver.get_hw_family(self.version_text)
        if family:
            self.chain.connection.log("HW Family: {}".format(family))
            self.family = family

Instruction: Given a code description, retrieve the corresponding code.


Question:
<p>
The list of pipelines.
</p>

@param pipelines
The list of pipelines.

public void setPipelines(java.util.Collection<PipelineSummary> pipelines) {
        if (pipelines == null) {
            this.pipelines = null;
            return;
        }

        this.pipelines = new java.util.ArrayList<PipelineSummary>(pipelines);
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetDBSecurityGroupMemberships sets the DBSecurityGroupMemberships field's value.

func (s *Option) SetDBSecurityGroupMemberships(v []*DBSecurityGroupMembership) *Option {
	s.DBSecurityGroupMemberships = v
	return s
}

func (s *YubiStore) GetKey(keyID string) (data.PrivateKey, data.RoleName, error) {
	ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader)
	if err != nil {
		logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error())
		if _, ok := err.(errHSMNotPresent); ok {
			err = trustmanager.ErrKeyNotFound{KeyID: keyID}
		}
		return nil, "", err
	}
	defer cleanup(ctx, session)

	key, ok := s.keys[keyID]
	if !ok {
		return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID}
	}

	pubKey, alias, err := getECDSAKey(ctx, session, key.slotID)
	if err != nil {
		logrus.Debugf("Failed to get key from slot %s: %s", key.slotID, err.Error())
		return nil, "", err
	}
	// Check to see if we're returning the intended keyID
	if pubKey.ID() != keyID {
		return nil, "", fmt.Errorf("expected root key: %s, but found: %s", keyID, pubKey.ID())
	}
	privKey := NewYubiPrivateKey(key.slotID, *pubKey, s.passRetriever)
	if privKey == nil {
		return nil, "", errors.New("could not initialize new YubiPrivateKey")
	}

	return privKey, alias, err
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Editace stranky
@return Form

protected function createComponentEditForm(): Form
	{
		$form = $this->formFactory->create();

		$form->addHidden('parent');

		$form->addCheckbox('isLink', 'webManager.web.pages.isLink')
			->setOption('id', 'page-isLink')
			->addCondition($form::EQUAL, false)
			->toggle('page-title')
			->toggle('page-keywords')
			->toggle('page-image')
			->toggle('page-background')
			->toggle('page-description')
			->toggle('page-content')
			->toggle('page-homePage');

		$homePage = $form->addCheckbox('homePage', 'webManager.web.pages.homePage')
			->setOption('id', 'page-homePage')
			->setDisabled(!$this->editHomePage);
		$homePage->addCondition($form::EQUAL, false)
			->toggle('page-name')
			->toggle('page-url')
			->toggle('page-views')
			->toggle('page-isLink');
		if ($homePage->isDisabled()) {
			$homePage->setOption('class', 'hidden');
		}

		$form->addText('name', 'webManager.web.pages.name')
			->setOption('id', 'page-name')
			->addConditionOn($form['homePage'], $form::EQUAL, false)
			->setRequired();

		$form->addText('url', 'default.url')
			->setOption('id', 'page-url')
			->addConditionOn($form['isLink'], $form::EQUAL, true)
			->setRequired();

		$form->addSelectUntranslated('locale', 'webManager.web.pages.locale')
			->setItems($this->localeService->allowed);

		$form->addCheckboxListUntranslated('views', 'webManager.web.pages.views.title')
			->setOption('id', 'page-views')
			->setItems($this->orm->pagesViews->fetchPairsById());

		$form->addText('title', 'webManager.web.pages.pageTitle')
			->setOption('id', 'page-title')
			->setRequired(false)
			->addRule(Form::MAX_LENGTH, null, 150);

		$form->addTextArea('keywords', 'webManager.web.pages.keywords')
			->setOption('id', 'page-keywords')
			->setRequired(false)
			->addRule(Form::MAX_LENGTH, null, 255);

		$form->addImageUpload('image', 'webManager.web.pages.photo', 'webManager.web.pages.photoDelete')
			->setNamespace('pages')
			->setPreview('300x100')
			->setOption('id', 'page-image');

		$form->addColor('background', 'webManager.web.pages.background')
			->setOption('id', 'page-background');

		$form->addTextArea('description', 'webManager.web.pages.description')
			->setOption('id', 'page-description')
			->setRequired(false)
			->addRule(Form::MAX_LENGTH, null, 255);

		$form->addTextEditor('content', 'webManager.web.pages.content')
			->setOption('id', 'page-content');

		$form->addSubmit('save', 'form.save');

		$form->addLink('back', 'form.back', $this->getBacklink());

		$form->onSuccess[] = [$this, 'editFormSucceeded'];

		return $form;
	}

public function getCustomAttribute($blockThis, $block, $attributeCode)
    {
        if($this->isEditForm($blockThis)){
            $attribute = $block->getCustomer()->getCustomAttribute($attributeCode);
            $value = $attribute ? $attribute->getValue() : null;

            return $value;
        } else {
            return $block->getFormData()->getAttribute($attributeCode);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Parse input context string and returns context as dictionary.

def get_parsed_context(context_arg):
    """"""
    if not context_arg:
        logger.debug("pipeline invoked without context arg set. For "
                     "this json parser you're looking for something "
                     "like: "
                     "pypyr pipelinename '{\"key1\":\"value1\","
                     "\"key2\":\"value2\"}'")
        return None

    logger.debug("starting")
    # deserialize the input context string into json
    return json.loads(context_arg)

def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self,
                   'customization_id') and self.customization_id is not None:
            _dict['customization_id'] = self.customization_id
        if hasattr(self, 'name') and self.name is not None:
            _dict['name'] = self.name
        if hasattr(self, 'language') and self.language is not None:
            _dict['language'] = self.language
        if hasattr(self, 'owner') and self.owner is not None:
            _dict['owner'] = self.owner
        if hasattr(self, 'created') and self.created is not None:
            _dict['created'] = self.created
        if hasattr(self, 'last_modified') and self.last_modified is not None:
            _dict['last_modified'] = self.last_modified
        if hasattr(self, 'description') and self.description is not None:
            _dict['description'] = self.description
        if hasattr(self, 'words') and self.words is not None:
            _dict['words'] = [x._to_dict() for x in self.words]
        return _dict

Instruction: Given a code description, retrieve the corresponding code.


Question: due to cast in return

public static <C> C getInstanceOf( Object argument,
                                       Class<C> expectedClass,
                                       String name ) {
        isInstanceOf(argument, expectedClass, name);
        return expectedClass.cast(argument);
    }

def p_statement_draw3(p):

    p[0] = make_sentence('DRAW3',
                         make_typecast(TYPE.integer, p[2], p.lineno(3)),
                         make_typecast(TYPE.integer, p[4], p.lineno(5)),
                         make_typecast(TYPE.float_, p[6], p.lineno(5)))

Instruction: Given a code description, retrieve the corresponding code.


Question: If the cell is a date, format it to MM/DD/YYYY, stripping time.

def format_date(a_cell)
    isdate = true if(nil != (dt = a_cell.match(@date_RE)))
    isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_dashes_RE))) )
    isdate = true if(isdate || (nil != (dt = a_cell.match(@date_with_time_RE))) )
    if isdate
      begin
        mod_dt = DateTime.parse(a_cell)
        cary = "#{mod_dt.month}/#{mod_dt.day}/#{mod_dt.year}"
        if(true == verbose?)
          puts ""
          puts "*** Converted date to #{cary} ***"
          puts ""
        end
        a_cell = cary
      rescue ArgumentError => e
        # Either this is not a date, or the date format is unrecognized,
        # nothing to see here, moving on.
      end
    end
    a_cell
  end

def convertstr2format(col,form):

    if not isstrallowed(col,form):
        col=col.replace(" ","_")
        if not isstrallowed(col,form):
            chars_disallowed=[char for char in col if not isstrallowed(char,form)]
            for char in chars_disallowed:
                col=col.replace(char,"_")
    return col

Instruction: Given a code description, retrieve the corresponding code.


Question:
Make this Path identical to the given one.

@param other
a Path to which this object should be made identical

public void copyFrom(Path other) {
        grow(other.length - 1);
        System.arraycopy(other.blockIdList, 0, this.blockIdList, 0, other.length);
        this.length = other.length;
        this.cachedHashCode = other.cachedHashCode;
    }

public function copy($displayProfileId, $name)
    {
        $this->name = $name;
        $this->displayProfileId = $displayProfileId;

        $this->getLogger()->info('Creating a Copy of Display Profile ' . $name);
        $response = $this->doPost('/displayprofile/' . $displayProfileId . '/copy', [
            'name' => $name
        ]);

        return $this->hydrate($response);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns error message for module inputs from ops with multiple outputs.

def find_signature_inputs_from_multivalued_ops(inputs):
  """"""
  dense_inputs = []  # List of (str, Tensor), with SparseTensors decomposed.
  for name, tensor in sorted(inputs.items()):
    if isinstance(tensor, tf.SparseTensor):
      dense_inputs.extend(("%s.%s" % (name, attr), getattr(tensor, attr))
                          for attr in ("indices", "values", "dense_shape"))
    else:
      dense_inputs.append((name, tensor))
  warnings = [(name, tensor.name) for name, tensor in dense_inputs
              if len(tensor.op.outputs) != 1]
  if warnings:
    return (
        "WARNING: The inputs declared in hub.add_signature() should be tensors "
        "from ops with a single output, or else uses of tf.colocate_with() on "
        "that op can trigger fatal errors when the module is applied and "
        "colocation constraints have to be rewritten.\nAffected inputs: %s" %
        ", ".join("%s='%s'" % pair for pair in warnings))
  return None

def Mux(fs, sel, simplify=True):

    # convert Mux([a, b], x) to Mux([a, b], [x])
    if isinstance(sel, Expression):
        sel = [sel]

    if len(sel) < clog2(len(fs)):
        fstr = "expected at least {} select bits, got {}"
        raise ValueError(fstr.format(clog2(len(fs)), len(sel)))

    it = boolfunc.iter_terms(sel)
    y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)])
                       for f in fs])
    if simplify:
        y = y.simplify()
    return _expr(y)

Instruction: Given a code description, retrieve the corresponding code.


Question:
// InstallLegacyAuthorization this looks like a lot of duplication, but the code in the individual versions is living and may
// change. The code here should never change and needs to allow the other code to move independently.

func InstallInternalLegacyAuthorization(scheme *runtime.Scheme) {
	InstallExternalLegacyAuthorization(scheme)

	schemeBuilder := runtime.NewSchemeBuilder(
		addUngroupifiedInternalAuthorizationTypes,
		core.AddToScheme,
		rbac.AddToScheme,
		corev1conversions.AddToScheme,
		rbacv1conversions.AddToScheme,

		authorizationv1helpers.AddConversionFuncs,
		authorizationv1helpers.AddFieldSelectorKeyConversions,
		authorizationv1helpers.RegisterDefaults,
		authorizationv1helpers.RegisterConversions,
	)
	utilruntime.Must(schemeBuilder.AddToScheme(scheme))
}

def generate_answers
      masterless = @options[:masterless]
      return super if masterless

      dashboard = only_host_with_role(@hosts, 'dashboard')
      database = only_host_with_role(@hosts, 'database')
      master = only_host_with_role(@hosts, 'master')

      the_answers = super
      if dashboard != master
        # in 3.2, dashboard needs the master certname
        the_answers[dashboard.name][:q_puppetmaster_certname] = master.to_s
      end

      # do we want to check for updates?
      pe_check_for_updates = answer_for(@options, :q_pe_check_for_updates, 'n')
      the_answers[dashboard.name][:q_pe_check_for_updates] = pe_check_for_updates
      the_answers[master.name][:q_pe_check_for_updates] = pe_check_for_updates

      if @options[:type] == :upgrade && dashboard != database
        # In a split configuration, there is no way for the upgrader
        # to know how much disk space is available for the database
        # migration. We tell it to continue on, because we're
        # awesome.
        the_answers[dashboard.name][:q_upgrade_with_unknown_disk_space] = 'y'
      end
      @hosts.each do |h|
        h[:answers] = the_answers[h.name]
      end
      return the_answers
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: // DefaultLocalConfigPath returns the local configuration path for settings such as cached authentication tokens.

func DefaultLocalConfigPath() (string, error) {
	dir, err := DefaultConfigDir()
	if err != nil {
		return "", err
	}
	return path.Join(dir, "config"), nil
}

func (o Output) ConfigSets() []ConfigSet {
	names := make([]string, 0, len(o.Roots))
	for name := range o.Roots {
		names = append(names, name)
	}
	sort.Strings(names) // order is important for logs

	cs := make([]ConfigSet, len(names))
	for i, nm := range names {
		root := o.Roots[nm]

		// Normalize in preparation for prefix matching.
		root = path.Clean(root)
		if root == "." {
			root = "" // match EVERYTHING
		} else {
			root = root + "/" // match only what's under 'root/...'
		}

		files := map[string][]byte{}
		for f, body := range o.Data {
			f = path.Clean(f)
			if strings.HasPrefix(f, root) {
				files[f[len(root):]] = body
			}
		}

		cs[i] = ConfigSet{Name: nm, Data: files}
	}

	return cs
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// SetCallCode sets the code of the contract and address of the backing data
// object

func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) {
	c.Code = code
	c.CodeHash = hash
	c.CodeAddr = addr
}

func (client *Client) TargetCF(settings TargetSettings) (Warnings, error) {
	client.cloudControllerURL = settings.URL

	client.connection = cloudcontroller.NewConnection(cloudcontroller.Config{
		DialTimeout:       settings.DialTimeout,
		SkipSSLValidation: settings.SkipSSLValidation,
	})

	for _, wrapper := range client.wrappers {
		client.connection = wrapper.Wrap(client.connection)
	}

	apiInfo, resourceLinks, warnings, err := client.GetInfo()
	if err != nil {
		return warnings, err
	}

	client.Info = apiInfo

	resources := map[string]string{}
	for resource, link := range resourceLinks {
		resources[resource] = link.HREF
	}
	client.router = internal.NewRouter(internal.APIRoutes, resources)

	return warnings, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Marshall the given parameter object.

public void marshall(GlacierJobDescription glacierJobDescription, ProtocolMarshaller protocolMarshaller) {

        if (glacierJobDescription == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(glacierJobDescription.getJobId(), JOBID_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getJobDescription(), JOBDESCRIPTION_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getAction(), ACTION_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getArchiveId(), ARCHIVEID_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getVaultARN(), VAULTARN_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getCreationDate(), CREATIONDATE_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getCompleted(), COMPLETED_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getStatusCode(), STATUSCODE_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getStatusMessage(), STATUSMESSAGE_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getArchiveSizeInBytes(), ARCHIVESIZEINBYTES_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getInventorySizeInBytes(), INVENTORYSIZEINBYTES_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getSNSTopic(), SNSTOPIC_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getCompletionDate(), COMPLETIONDATE_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getSHA256TreeHash(), SHA256TREEHASH_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getArchiveSHA256TreeHash(), ARCHIVESHA256TREEHASH_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getRetrievalByteRange(), RETRIEVALBYTERANGE_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getTier(), TIER_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getInventoryRetrievalParameters(), INVENTORYRETRIEVALPARAMETERS_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getJobOutputPath(), JOBOUTPUTPATH_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getSelectParameters(), SELECTPARAMETERS_BINDING);
            protocolMarshaller.marshall(glacierJobDescription.getOutputLocation(), OUTPUTLOCATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Pre block starts
    start 0-indexted, end 1-indexted

 :param filename: filename
 :type filename: string
 :return: 0-index start and 1-index end
 :rtype: array of arrays with the [start end] of each block

def get_block_bounds(filename):

 bs = []
 with open(filename,'rb') as inf:
  while True:
   bytes1 = inf.read(12)
   if len(bytes1) < 12: break
   bs.append([inf.tell()-12])
   gzip_id1,gzip_id2,compression_method,flag,mtime,xfl,osval,xlen=struct.unpack('<BBBBIBBH',bytes1)
   # ready to look in extra field
   bytes2 = inf.read(xlen) # all the extra field stuff
   s = StringIO.StringIO(bytes2)
   obsslen = 0
   blocksize = 0
   while True:
     v1 = s.read(4)
     if len(v1) == 0:
       break
     if len(v1) < 4:
       sys.stderr.write("lack header values ERROR\n")
       return False
     s1,s2,slen = struct.unpack('<BBH',v1)
     if s1 == 66 and s2 == 67:
       has_id = True
       obsslen = slen
       blocksize = struct.unpack('<H',s.read(slen))[0]
     else:
       v = s.read(slen)
   chunk = inf.read(blocksize-1-xlen-19)
   inf.read(9)
   bs[-1].append(inf.tell())
 return bs

func ListPlugins() map[string][]string {
	p := make(map[string][]string)

	// server type plugins
	for name := range serverTypes {
		p["server_types"] = append(p["server_types"], name)
	}

	// caddyfile loaders in registration order
	for _, loader := range caddyfileLoaders {
		p["caddyfile_loaders"] = append(p["caddyfile_loaders"], loader.name)
	}
	if defaultCaddyfileLoader.name != "" {
		p["caddyfile_loaders"] = append(p["caddyfile_loaders"], defaultCaddyfileLoader.name)
	}

	// List the event hook plugins
	eventHooks.Range(func(k, _ interface{}) bool {
		p["event_hooks"] = append(p["event_hooks"], k.(string))
		return true
	})

	// alphabetize the rest of the plugins
	var others []string
	for stype, stypePlugins := range plugins {
		for name := range stypePlugins {
			var s string
			if stype != "" {
				s = stype + "."
			}
			s += name
			others = append(others, s)
		}
	}

	sort.Strings(others)
	for _, name := range others {
		p["others"] = append(p["others"], name)
	}

	return p
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Stripe Webhook coupon.created

function (coupon, cb) {

		Coupon.findOrCreate(coupon.id, coupon)
	    .exec(function (err, foundCoupon){
	      if (err) return cb(err);
	      if (foundCoupon.lastStripeEvent > coupon.lastStripeEvent) return cb(null, foundCoupon);
	      if (foundCoupon.lastStripeEvent == coupon.lastStripeEvent) return Coupon.afterStripeCouponCreated(foundCoupon, function(err, coupon){ return cb(err, coupon)});
	      Coupon.update(foundCoupon.id, coupon)
	      .exec(function(err, updatedCoupons){
	      	if (err) return cb(err);
	      	Coupon.afterStripeCouponCreated(updatedCoupons[0], function(err, coupon){
	      		cb(err, coupon);
	      	});
	      });
	    });
	}

public function disable(string $code, string $cardId = '')
    {
        $params = [
            'code' => $code,
            'card_id' => $cardId,
        ];

        return $this->httpPostJson('card/code/unavailable', $params);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Remove exclusion rule

def remove_inclusion(self, role, value=None):
        """"""
        self._remove_rule(self.includes, role, value)

protected function getExportModel()
    {
        $model = parent::getExportModel();
        $model->del('parents', 'formatFunction');
        $model->del('allowed', 'formatFunction');
        $model->del('inherited', 'formatFunction');

        return $model;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetSkillGroupArn sets the SkillGroupArn field's value.

func (s *CreateSkillGroupOutput) SetSkillGroupArn(v string) *CreateSkillGroupOutput {
	s.SkillGroupArn = &v
	return s
}

@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.MMT__RG:
				getRG().clear();
				getRG().addAll((Collection<? extends MMTRG>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the list of assets owned by an address owner.

        :param address: ethereum account address, hex str
        :return:

def get_owner_asset_ids(self, address):

        block_filter = self._get_event_filter(owner=address)
        log_items = block_filter.get_all_entries(max_tries=5)
        did_list = []
        for log_i in log_items:
            did_list.append(id_to_did(log_i.args['_did']))

        return did_list

def get_neighbors( self, peer_hostport, con=None, path=None, peer_table=None ):

        if path is None:
            path = self.atlasdb_path

        if self.neighbors_timeout is None:
            self.neighbors_timeout = atlas_neighbors_timeout()

        peer_hostport = self.canonical_peer( peer_hostport )

        neighbors = None
        if peer_hostport == self.my_hostport:
            neighbors = atlas_get_live_neighbors( None, peer_table=peer_table )
        else:
            neighbors = atlas_peer_get_neighbors( self.my_hostport, peer_hostport, timeout=self.neighbors_timeout, peer_table=peer_table, path=path, con=con )

        if neighbors is not None:
            log.debug("%s: neighbors of %s are (%s): %s" % (self.my_hostport, peer_hostport, len(neighbors), ",".join(neighbors)))
        else:
            log.error("%s: failed to ask %s for neighbors" % (self.my_hostport, peer_hostport))

        return neighbors

Instruction: Given a code description, retrieve the corresponding code.


Question:
Activate user accounts
    :param server_context: A LabKey server context. See utils.create_server_context.
    :param target_ids:
    :param container_path:
    :return:

def activate_users(server_context, target_ids, container_path=None):

    return __make_user_api_request(server_context, target_ids=target_ids, api='activateUsers.api',
                                   container_path=container_path)

def datalab(line, cell=None):

  parser = google.datalab.utils.commands.CommandParser(
      prog='%datalab',
      description="""
Execute operations that apply to multiple Datalab APIs.

Use "%datalab <command> -h" for help on a specific command.
""")

  config_parser = parser.subcommand(
      'config', help='List or set API-specific configurations.')
  config_sub_commands = config_parser.add_subparsers(dest='command')

  # %%datalab config list
  config_list_parser = config_sub_commands.add_parser(
      'list', help='List configurations')
  config_list_parser.set_defaults(func=_config_list_fn)

  # %%datalab config set -n <NAME> -v <VALUE>
  config_set_parser = config_sub_commands.add_parser(
      'set', help='Set configurations')
  config_set_parser.add_argument(
      '-n', '--name',
      help='The name of the configuration value', required=True)
  config_set_parser.add_argument(
      '-v', '--value', help='The value to set', required=True)
  config_set_parser.set_defaults(func=_config_set_fn)

  project_parser = parser.subcommand(
      'project', help='Get or set the default project ID')
  project_sub_commands = project_parser.add_subparsers(dest='command')

  # %%datalab project get
  project_get_parser = project_sub_commands.add_parser(
      'get', help='Get the default project ID')
  project_get_parser.set_defaults(func=_project_get_fn)

  # %%datalab project set -p <PROJECT_ID>
  project_set_parser = project_sub_commands.add_parser(
      'set', help='Set the default project ID')
  project_set_parser.add_argument(
      '-p', '--project', help='The default project ID', required=True)
  project_set_parser.set_defaults(func=_project_set_fn)

  return google.datalab.utils.commands.handle_magic_line(line, cell, parser)

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Environment variables required within the remote environment are uploaded
// within a PS script and then enabled by 'dot sourcing' the script
// immediately prior to execution of the main command

func (p *Provisioner) prepareEnvVars(elevated bool) (err error) {
	// Collate all required env vars into a plain string with required
	// formatting applied
	flattenedEnvVars := p.createFlattenedEnvVars(elevated)
	// Create a powershell script on the target build fs containing the
	// flattened env vars
	err = p.uploadEnvVars(flattenedEnvVars)
	if err != nil {
		return err
	}
	return
}

def in_venv():

    global _in_venv
    if _in_venv is not None:
        return _in_venv

    if not (os.path.isfile(ORIG_PREFIX_TXT) or os.path.isfile(PY_VENV_CFG)):
        logger.debug("in_venv no orig_prefix_txt [%s]", ORIG_PREFIX_TXT)
        logger.debug("in_venv no py_venv_cfg [%s]", PY_VENV_CFG)
        # TODO - check this is actually valid !
        _in_venv = False
        return _in_venv

    if 'VIRTUAL_ENV' in os.environ:
        logger.debug("in_venv VIRTUAL_ENV set.")
        _in_venv = True
    else:
        # Find first python in path ... if its not this one,
        # ...we are in a different python
        python = basename(sys.executable)
        for p in os.environ['PATH'].split(os.pathsep):
            py_path = join(p, python)
            if isfile(py_path):
                logger.debug("in_venv py_at [%s] return: %s", (py_path, sys.executable != py_path))
                _in_venv = sys.executable != py_path
                break

    return _in_venv

Instruction: Given a code description, retrieve the corresponding code.


Question:
在Config字句中增加自定义的参数。

@param String $key 设定自定义参数名。
@param Mixed $value 设定自定义参数值。
@return void

public function setCustomConfig($key, $value) {
        if ($this->searchParams->config->customConfig == null) {
            $this->searchParams->config->customConfig = array();
        }

        $this->searchParams->config->customConfig[$key] = $value;
    }

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Convert an array of WSDL-style {@link RelationshipTuple}s into a list of
local {@link RelationshipInfo} objects.

public static List<RelationshipInfo> convertGenRelsTupleArrayToRelationshipInfoList(RelationshipTuple[] array) {
        if (array == null) {
            return Collections.emptyList();
        }

        List<RelationshipInfo> list =
                new ArrayList<RelationshipInfo>(array.length);
        for (RelationshipTuple genTuple : array) {
            list.add(convertGenRelsTupleToRelationshipInfo(genTuple));
        }
        return list;
    }

def _serialize(self, value, key, obj):

        param_values = {}
        for name, attr_tpl in iteritems(self.params):
            attr_name = _tpl(str(attr_tpl))
            if attr_name:
                attribute_value = _get_value(obj, attr_name, default=missing)
                if attribute_value is None:
                    return None
                if attribute_value is not missing:
                    param_values[name] = attribute_value
                else:
                    raise AttributeError(
                        "{attr_name!r} is not a valid "
                        "attribute of {obj!r}".format(attr_name=attr_name, obj=obj)
                    )
            else:
                param_values[name] = attr_tpl
        return url_for(self.endpoint, **param_values)

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetStatus sets the Status field's value.

func (s *ResourceShare) SetStatus(v string) *ResourceShare {
	s.Status = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the greeting message.
@return the greeting message.

public String greeting() {
    int current = counter.getAndAdd(1);

    if (current % 2 != 0) {
      return format("Hello Rollbar number %d", current);
    }
    throw new RuntimeException("Fatal error at greeting number: " + current);
  }

def push(self, code, msg=None):
        """"""
        if msg is None:
            msg = str(code)
        else:
            msg = '%s %s' % (code, msg)

        if not msg.endswith(self.LINE_TERMINATOR):
            msg += self.LINE_TERMINATOR
        self._channel.write(msg)

Instruction: Given a code description, retrieve the corresponding code.


Question:
(non-PHPdoc)
@see Generator/Admingenerator\GeneratorBundle\Generator.GeneratorInterface::build()

public function build()
    {
        if ($this->cacheProvider->fetch($this->getCacheKey())) {
            return;
        }

        $this->doBuild();
        $this->cacheProvider->save($this->getCacheKey(), true);
    }

public function getRepository($name)
    {
        $storeConfig = $this->config[$name];
        $driver = isset($storeConfig['driver']) ? $storeConfig['driver'] : $name;
        if ($driver instanceof \Closure) {
            $connection = $driver($storeConfig);
        } elseif (method_exists($this, "create" . ucfirst($driver) . 'Store')) {
            $method = "create" . ucfirst($driver) . 'Store';
            $connection = $this->$method($storeConfig);
        } elseif (class_exists($driver)) {
            $connection = new $driver($storeConfig);
        } else {
            throw new \InvalidArgumentException(sprintf(
                'Invalid Cache driver "%s"; must be an defined driver(redis|file) or classname or \Closure',
                $driver
            ));
        }
        return new Repository($connection, $this->config['prefix']);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get list of Tango classes for a device server

        :param argin: device server process name
        :type: tango.DevString
        :return: list of classes for this device server
        :rtype: tango.DevVarStringArray

def DbGetDeviceServerClassList(self, argin):

        self._log.debug("In DbGetDeviceServerClassList()")
        argin = replace_wildcard(argin)
        return self.db.get_server_class_list(argin)

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

Instruction: Given a code description, retrieve the corresponding code.


Question:
// dropDisabledProcMountField removes disabled fields from PodSpec related
// to ProcMount only if it is not already used by the old spec

func dropDisabledProcMountField(podSpec, oldPodSpec *api.PodSpec) {
	if !utilfeature.DefaultFeatureGate.Enabled(features.ProcMountType) && !procMountInUse(oldPodSpec) {
		defaultProcMount := api.DefaultProcMount
		for i := range podSpec.Containers {
			if podSpec.Containers[i].SecurityContext != nil {
				podSpec.Containers[i].SecurityContext.ProcMount = &defaultProcMount
			}
		}
		for i := range podSpec.InitContainers {
			if podSpec.InitContainers[i].SecurityContext != nil {
				podSpec.InitContainers[i].SecurityContext.ProcMount = &defaultProcMount
			}
		}
	}
}

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

Instruction: Given a code description, retrieve the corresponding code.


Question:
We are given a UDF CFUNCTYPE and want to call it in python

    :param f: SpiceUDFUNS
    :type f: CFUNCTYPE
    :param x: some scalar
    :type x: float
    :return: value
    :rtype: float

def CallUDFUNS(f, x):

    value = c_double()
    f(x, byref(value))
    return value.value

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Handle packet from queue

 === Parameters
 queue(String):: Name of queue from which message was received
 packet(Packet):: Packet received
 header(AMQP::Frame::Header):: Packet header containing ack control

 === Return
 true:: Always return true

def handle_packet(queue, packet, header)
      begin
        # Continue to dispatch/ack requests even when terminating otherwise will block results
        # Ideally would reject requests when terminating but broker client does not yet support that
        case packet
        when Push, Request then dispatch_request(packet, queue)
        when Result        then deliver_response(packet)
        end
        @sender.message_received
      rescue Exception => e
        ErrorTracker.log(self, "#{queue} queue processing error", e)
      ensure
        # Relying on fact that all dispatches/deliveries are synchronous and therefore
        # need to have completed or failed by now, thus allowing packet acknowledgement
        header.ack
      end
      true
    end

public void marshall(MatchmakingTicket matchmakingTicket, ProtocolMarshaller protocolMarshaller) {

        if (matchmakingTicket == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(matchmakingTicket.getTicketId(), TICKETID_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getConfigurationName(), CONFIGURATIONNAME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatusReason(), STATUSREASON_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatusMessage(), STATUSMESSAGE_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getEndTime(), ENDTIME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getPlayers(), PLAYERS_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getGameSessionConnectionInfo(), GAMESESSIONCONNECTIONINFO_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getEstimatedWaitTime(), ESTIMATEDWAITTIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Remove empty lines. <br>
And CR is removed.
@param str The target string. (NotNull)
@return The filtered string. (NotNull)

public static String removeEmptyLine(String str) {
        assertStringNotNull(str);
        final StringBuilder sb = new StringBuilder();
        final List<String> lineList = splitList(str, "\n");
        for (String line : lineList) {
            if (is_Null_or_TrimmedEmpty(line)) {
                continue; // skip
            }
            sb.append(removeCR(line)).append("\n");
        }
        final String filtered = sb.toString();
        return filtered.substring(0, filtered.length() - "\n".length());
    }

function(attrs) {
            if (_.isEmpty(attrs)) return [];
            return this.filter(function(model) {
                for (var key in attrs) {
                  if (attrs[key] !== model.get(key)) return false;
                }
                return true;
            });
        }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Register the root Tenant instance

@return void

protected function registerBaseTenantBindings()
    {
        $this->singleton(TenantContract::class, function ($app) {
            return new Tenant(new NullUser(), new NullTenant(), new NullTenant());
        });

        $this->alias(TenantContract::class, 'auth.tenant');
    }

def rest_name(cls):

        if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
            return "Not Implemented"

        if cls.__rest_name__ is None:
            raise NotImplementedError('%s has no defined name. Implement rest_name property first.' % cls)

        return cls.__rest_name__

Instruction: Given a code description, retrieve the corresponding code.


Question:
Attach the {@code listener} to this manager and enqueue the task if it isn't pending or
running.

@param task     the task will be enqueue if it isn't running.
@param listener the listener will be attach to this manager.

public synchronized void attachAndEnqueueIfNotRun(@NonNull DownloadTask task,
                                                      @NonNull DownloadListener listener) {
        attachListener(task, listener);

        if (!isTaskPendingOrRunning(task)) {
            task.enqueue(hostListener);
        }
    }

def check_spinning_children(self):
        ''''''
        child_jobs = self.task_master.get_child_work_units(self.worker_id)
        # We will kill off any jobs that are due before "now".  This
        # isn't really now now, but now plus a grace period to make
        # sure spinning jobs don't get retried.
        now = time.time() + self.stop_jobs_early
        for child, wul in child_jobs.iteritems():
            if not isinstance(wul, (list, tuple)):
                # Support old style get_child_work_units which returns
                # single WorkUnit objects instead of list of them.
                wul = [wul]
            if not wul:
                # This worker is idle, but oddly, still present; it should
                # clean up after itself
                continue
            # filter on those actually assigned to the child worker
            wul = filter(lambda wu: wu.worker_id == child, wul)
            # check for any still active not-overdue job
            if any(filter(lambda wu: wu.expires > now, wul)):
                continue
            # So either someone else is doing its work or it's just overdue
            environment = self.task_master.get_heartbeat(child)
            if not environment:
                continue  # derp
            if 'pid' not in environment:
                continue  # derp
            if environment['pid'] not in self.children:
                continue  # derp
            os.kill(environment['pid'], signal.SIGTERM)
            # This will cause the child to die, and do_some_work will
            # reap it; but we'd also like the job to fail if possible
            for wu in wul:
                if wu.data is None:
                    logger.critical('how did wu.data become: %r' % wu.data)
                else:
                    wu.data['traceback'] = 'job expired'
                wu.fail(exc=Exception('job expired'))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Traverses the type hierarchy of a type up until a certain stop class is found.

@param t type for which a hierarchy need to be created
@return type of the immediate child of the stop class

public static Type getTypeHierarchy(List<Type> typeHierarchy, Type t, Class<?> stopAtClass) {
		while (!(isClassType(t) && typeToClass(t).equals(stopAtClass))) {
			typeHierarchy.add(t);
			t = typeToClass(t).getGenericSuperclass();

			if (t == null) {
				break;
			}
		}
		return t;
	}

def _match_parent(self, match, yield_parent):

        ret = super(Chain, self)._match_parent(match, yield_parent)
        original_children = Matches(match.children)
        original_end = match.end
        while not ret and match.children:
            last_pattern = match.children[-1].pattern
            last_pattern_children = [child for child in match.children if child.pattern == last_pattern]
            last_pattern_groups_iter = itertools.groupby(last_pattern_children, lambda child: child.match_index)
            last_pattern_groups = {}
            for index, matches in last_pattern_groups_iter:
                last_pattern_groups[index] = list(matches)

            for index in reversed(list(last_pattern_groups)):
                last_matches = list(last_pattern_groups[index])
                for last_match in last_matches:
                    match.children.remove(last_match)
                match.end = match.children[-1].end if match.children else match.start
                ret = super(Chain, self)._match_parent(match, yield_parent)
                if ret:
                    return True
        match.children = original_children
        match.end = original_end
        return ret

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set background color of the cell.

@param mixed $color either a string (like 'blue'), or an integer (range is [8...63])

public function set_bg_color($color) {
        if (!isset($this->format['fill']['type'])) {
            $this->format['fill']['type'] = PHPExcel_Style_Fill::FILL_SOLID;
        }
        $this->format['fill']['color']['rgb'] = $this->parse_color($color);
    }

public void setOutRGB(IntRange outRGB) {
        this.outRed = outRGB;
        this.outGreen = outRGB;
        this.outBlue = outRGB;

        CalculateMap(inRed, outRGB, mapRed);
        CalculateMap(inGreen, outRGB, mapGreen);
        CalculateMap(inBlue, outRGB, mapBlue);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a new spliterator that will not return entries that have expired.
@param spliterator the spliterator to filter expired entries out of
@return new spliterator with expired entries filtered

protected Spliterator<InternalCacheEntry<K, V>> filterExpiredEntries(Spliterator<InternalCacheEntry<K, V>> spliterator) {
      // This way we only read the wall clock time at the beginning
      long accessTime = timeService.wallClockTime();
      return new FilterSpliterator<>(spliterator, expiredIterationPredicate(accessTime));
   }

private function parseRuleDefinition($key, $definition): Rule
    {
        if (is_string($definition)) {

            $parts = preg_split('/:/', $definition, 2);

            $factory_name = $parts[0];
            $parameters = $parts[1] ?? null;

            $parameters = ! is_null($parameters)
                ? explode(',', $parameters)
                : [];

            $factory_name = trim($factory_name);
            $parameters = array_map('trim', $parameters);

            $factory = $this->getRuleFactory($factory_name);

            $name = is_string($key) ? $key : $factory_name;
            $validate = $factory($parameters);

            return new Rule($name, $validate);

        }

        // is_callable must be AFTER is_string, otherwise factories named like a
        // php function can't be used (ex: date).
        if (is_callable($definition)) {

            return new Rule((string) $key, $definition);

        }

        throw new InvalidRuleFormatException($definition);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Given a FASTA database, proteins are trypsinized and resulting peptides
    stored in a database or dict for lookups

def create_searchspace(lookup, fastafn, proline_cut=False,
                       reverse_seqs=True, do_trypsinize=True):
    """"""
    allpeps = []
    for record in SeqIO.parse(fastafn, 'fasta'):
        if do_trypsinize:
            pepseqs = trypsinize(record.seq, proline_cut)
        else:
            pepseqs = [record.seq]
        # Exchange all leucines to isoleucines because MS can't differ
        pepseqs = [(str(pep).replace('L', 'I'),) for pep in pepseqs]
        allpeps.extend(pepseqs)
        if len(allpeps) > 1000000:  # more than x peps, write to SQLite
            lookup.write_peps(allpeps, reverse_seqs)
            allpeps = []
    # write remaining peps to sqlite
    lookup.write_peps(allpeps, reverse_seqs)
    lookup.index_peps(reverse_seqs)
    lookup.close_connection()

def download_message(self):
    """"""

    print('Failed to find any ImageNet %s files'% self.subset)
    print('')
    print('If you have already downloaded and processed the data, then make '
          'sure to set --data_dir to point to the directory containing the '
          'location of the sharded TFRecords.\n')
    print('If you have not downloaded and prepared the ImageNet data in the '
          'TFRecord format, you will need to do this at least once. This '
          'process could take several hours depending on the speed of your '
          'computer and network connection\n')
    print('Please see README.md for instructions on how to build '
          'the ImageNet dataset using download_and_preprocess_imagenet.\n')
    print('Note that the raw data size is 300 GB and the processed data size '
          'is 150 GB. Please ensure you have at least 500GB disk space.')

Instruction: Given a code description, retrieve the corresponding code.


Question: // OnStop implements cmn.Service by unsubscribing remoteAddr from all subscriptions.

func (wsc *wsConnection) OnStop() {
	// Both read and write loops close the websocket connection when they exit their loops.
	// The writeChan is never closed, to allow WriteRPCResponse() to fail.

	if wsc.onDisconnect != nil {
		wsc.onDisconnect(wsc.remoteAddr)
	}

	if wsc.ctx != nil {
		wsc.cancel()
	}
}

def close &on_disconnect
      @heartbeat_timer.cancel if @heartbeat_timer
      @heartbeat_timer = nil
      if on_disconnect
        @closing = true
        @on_disconnect = proc{
          on_disconnect.call
          @closing = false
        }
      end

      callback{ |c|
        if c.channels.any?
          c.channels.each do |ch, mq|
            mq.close
          end
        else
          send Protocol::Connection::Close.new(:reply_code => 200,
                                               :reply_text => 'Goodbye',
                                               :class_id => 0,
                                               :method_id => 0)
        end
      }
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: Render of widget

def drawImage(self, image):

        padding = image.width() % 4
        for i in range(0, image.height()):
            tmp = image.copy(0, i, image.width() + padding, 1)
            #in RDP image or bottom top encoded
            ptr = tmp.bits()
            ptr.setsize(tmp.byteCount())
            self._controller.sendUpdate(self._dx, i + self._dy, image.width() + self._dx - 1, i + self._dy, tmp.width(), tmp.height(), self._colorDepth, False, ptr.asstring())

def start(self, plugin_name=None, kwargs=None):
        """"""
        self.output = [] # Start basically resets the output data
        super(WorkbenchRenderer, self).start(plugin_name=plugin_name)
        return self

Instruction: Given a code description, retrieve the corresponding code.


Question: Acquire all segment locks and return an array with the lock stamps.

private long[] lockAll() {
    OptimisticLock[] _locks = locks;
    int sn = _locks.length;
    long[] _stamps = new long[locks.length];
    for (int i = 0; i < sn; i++) {
      OptimisticLock l = _locks[i];
      _stamps[i] = l.writeLock();
    }
    return _stamps;
  }

func (r *ForwardRecorder) Write(data []byte) (int, error) {
	// we are copying buffer to prevent data corruption:
	// io.Copy allocates single buffer and calls multiple writes in a loop
	// our PostSessionSlice is async and sends reader wrapping buffer
	// to the channel. This can lead to cases when the buffer is re-used
	// and data is corrupted unless we copy the data buffer in the first place
	dataCopy := make([]byte, len(data))
	copy(dataCopy, data)
	// post the chunk of bytes to the audit log:
	chunk := &SessionChunk{
		EventType: SessionPrintEvent,
		Data:      dataCopy,
		Time:      time.Now().UTC().UnixNano(),
	}
	if err := r.AuditLog.PostSessionSlice(SessionSlice{
		Namespace: r.Namespace,
		SessionID: string(r.SessionID),
		Chunks:    []*SessionChunk{chunk},
	}); err != nil {
		r.Error(trace.DebugReport(err))
	}
	return len(data), nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Destroy deletes a given entry from the database

func (c *Connection) Destroy(model interface{}) error {
	sm := &Model{Value: model}
	return sm.iterate(func(m *Model) error {
		return c.timeFunc("Destroy", func() error {
			var err error

			if err = m.beforeDestroy(c); err != nil {
				return err
			}
			if err = c.Dialect.Destroy(c.Store, m); err != nil {
				return err
			}

			return m.afterDestroy(c)
		})
	})
}

public function hDel($key, $field) {
        return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Add percent combined to general stats table

def stats_table(self, data):
        """"""
        headers = OrderedDict()
        headers['combopairs'] = {
            'title': 'Combined pairs',
            'description': 'Num read pairs combined',
            'shared_key': 'read_count',
            'hidden': True,
            'scale': False
        }
        headers['perccombo'] = {
            'title': '% Combined',
            'description': '% read pairs combined',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'PiYG'
        }
        self.general_stats_addcols(data, headers)

func New64(total int64) *ProgressBar {
	pb := &ProgressBar{
		Total:           total,
		RefreshRate:     DEFAULT_REFRESH_RATE,
		ShowPercent:     true,
		ShowCounters:    true,
		ShowBar:         true,
		ShowTimeLeft:    true,
		ShowElapsedTime: false,
		ShowFinalTime:   true,
		Units:           U_NO,
		ManualUpdate:    false,
		finish:          make(chan struct{}),
	}
	return pb.Format(FORMAT)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*
(non-Javadoc)

@see java.util.Hashtable#isEmpty()

@Override
	public boolean isEmpty() {
		lock.readLock().lock();
		try {
			return entrySet().isEmpty();
		} finally {
			lock.readLock().unlock();
		}
	}

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns an array containing the data from the nodes in the list

def to_a
      current = @first
      array = []
      while !current.nil?
        array << current.data
        current = current.next
      end
      array
    end

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Output returns the output generated by the previously added command
// execution.

func Output(tempdir string) string {
	p := path.Join(tempdir, ".out")
	b, err := ioutil.ReadFile(p)
	if err != nil {
		return ""
	}
	return string(b)
}

def run(cmd, descr=None, data=None, checks=None, region=None, log_error=True,
        log_stdout=False, env=None):

    if descr:
      descr = _descr_str(descr, data, region)
      logger.debug(descr)
    cmd_id = diagnostics.start_cmd(cmd, descr or "", data)
    try:
        logger_cl.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, six.string_types) else cmd)
        _do_run(cmd, checks, log_stdout, env=env)
    except:
        diagnostics.end_cmd(cmd_id, False)
        if log_error:
            logger.exception()
        raise
    finally:
        diagnostics.end_cmd(cmd_id)

Instruction: Given a code description, retrieve the corresponding code.


Question: // getGroupKind is used to determine if a group and kind combination is supported.

func (m *model) getGroupKind() schema.GroupKind {
	return schema.GroupKind{Group: m.group, Kind: m.kind}
}

def check_bucket_exists(self, bucket: str) -> bool:

        bucket_obj = self.gcp_client.bucket(bucket)  # type: Bucket
        return bucket_obj.exists()

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Fields list the non-key fields users want to fetch.
// PrimaryKey fields are always fetched.

func (s *ScanOp) Fields(fields []string) *ScanOp {
	s.fieldsToRead = fields
	return s
}

def prepare_notes(self, *notes, **keyword_notes):
        """"""
        __partial = keyword_notes.pop('__partial', False)
        args = tuple(self.get(note) for note in notes)
        kwargs = {}
        for arg in keyword_notes:
            note = keyword_notes[arg]
            if isinstance(note, tuple) and len(note) == 2 and note[0] == MAYBE:
                try:
                    kwargs[arg] = self.get(note[1])
                except LookupError:
                    continue
            elif __partial:
                try:
                    kwargs[arg] = self.get(note)
                except LookupError:
                    continue
            else:
                kwargs[arg] = self.get(note)
        return args, kwargs

Instruction: Given a code description, retrieve the corresponding code.


Question:
will write tag bytesWritten counter will be increased by the number of bytes actually written

@param tag
- tag to be written
@throws IOException
- in case of any IO errors

public void writeTag(Tag tag) throws IOException {
        byte[] hb = tag.encode();
        bytesWritten += hb.length;
        dataFile.write(hb);
    }

private void CheckCIELab(IfdTags metadata, int n) {
    // BitsPerSample
    if (!metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) {
      validation.addErrorLoc("Missing BitsPerSample", "IFD" + n);
    } else {
      for (abstractTiffType vi : metadata.get(TiffTags.getTagId("BitsPerSample")).getValue()) {
        if (vi.toInt() != 8) {
          validation.addError("Invalid BitsPerSample", "IFD" + n, vi.toInt());
          break;
        }
      }
    }
  }

Instruction: Given a code description, retrieve the corresponding code.