Question:
Auto generated seed file.

@return void

public function run()
    {
        if (file_exists(base_path('routes/web.php'))) {
            require base_path('routes/web.php');

            $menu = Menu::where('name', 'admin')->firstOrFail();

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '总览',
                'url'        => route('voyager.dashboard', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-boat',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 1,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '文件',
                'url'        => route('voyager.media.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-images',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 5,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '帖子',
                'url'        => route('voyager.posts.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-news',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 6,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '用户',
                'url'        => route('voyager.users.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-person',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 3,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '分类',
                'url'        => route('voyager.categories.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-categories',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 8,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '页面',
                'url'        => route('voyager.pages.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-file-text',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 7,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '角色',
                'url'        => route('voyager.roles.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-lock',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 2,
                ])->save();
            }

            $toolsMenuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '工具',
                'url'        => '',
            ]);
            if (!$toolsMenuItem->exists) {
                $toolsMenuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-tools',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 9,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '菜单管理',
                'url'        => route('voyager.menus.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-list',
                    'color'      => null,
                    'parent_id'  => $toolsMenuItem->id,
                    'order'      => 10,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '数据库',
                'url'        => route('voyager.database.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-data',
                    'color'      => null,
                    'parent_id'  => $toolsMenuItem->id,
                    'order'      => 11,
                ])->save();
            }

            $menuItem = MenuItem::firstOrNew([
                'menu_id'    => $menu->id,
                'title'      => '设置',
                'url'        => route('voyager.settings.index', [], false),
            ]);
            if (!$menuItem->exists) {
                $menuItem->fill([
                    'target'     => '_self',
                    'icon_class' => 'voyager-settings',
                    'color'      => null,
                    'parent_id'  => null,
                    'order'      => 12,
                ])->save();
            }
        }
    }

def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None):
        '''
        '''
        rows = number_of_rows
        conn = self.database_caller_creator(name)

        if custom:
            self.custom_db_creator(rows, conn, custom)
            conn.close()
            sys.exit(0)

        self.data_filler_simple_registration(rows, conn)
        self.data_filler_detailed_registration(rows, conn)
        self.data_filler_company(rows, conn)
        self.data_filler_user_agent(rows, conn)
        self.data_filler_customer(rows, conn)
        conn.close()

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


Question:
Update the current scope by going back `level` levels.

        Parameters
        ----------
        level : int or None, optional, default None

def update(self, level):

        sl = level + 1

        # add sl frames to the scope starting with the
        # most distant and overwriting with more current
        # makes sure that we can capture variable scope
        stack = inspect.stack()

        try:
            self._get_vars(stack[:sl], scopes=['locals'])
        finally:
            del stack[:], stack

func (p *Params) Bind(dest interface{}, name string) {
	value := reflect.ValueOf(dest)
	if value.Kind() != reflect.Ptr {
		paramsLogger.Panic("Bind: revel/params: non-pointer passed to Bind: " + name)
	}
	value = value.Elem()
	if !value.CanSet() {
		paramsLogger.Panic("Bind: revel/params: non-settable variable passed to Bind: " + name)
	}

	// Remove the json from the Params, this will stop the binder from attempting
	// to use the json data to populate the destination interface. We do not want
	// to do this on a named bind directly against the param, it is ok to happen when
	// the action is invoked.
	jsonData := p.JSON
	p.JSON = nil
	value.Set(Bind(p, name, value.Type()))
	p.JSON = jsonData
}

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


Question: IMPORTANT: Call this function at the beginning of your program.

def initialize():
    """"""
    try:
        requests.get('http://localhost:4242/poll')
        state['connected_to_bot'] = True
    except requests.exceptions.ConnectionError:
        state['connected_to_bot'] = False

    # set up turtle
    state['window'] = turtle.Screen()
    state['window'].setup(width=WCB_WIDTH, height=WCB_HEIGHT)
    state['turtle'] = turtle.Turtle()
    state['turtle'].width(5)
    point_in_direction(0)

    # set up watercolorbot brush
    brush_up()
    wash_brush()
    park()

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

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


Question: The currently-active configuration set.

def active_conf_set(self):
        ''''''
        with self._mutex:
            if not self.conf_sets:
                return None
            if not self._active_conf_set:
                return None
            return self.conf_sets[self._active_conf_set]

public function application(bool $null = true) : array
    {
        $config = $this->appConfig;
        if ($null) {
            $this->appConfig = [];
        }
        return $config;
    }

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


Question: Remove all active connections and query the maximum number of supported connections

def initialize_system_sync(self):

        retval = self._command_task.sync_command(['_query_systemstate'])

        self.maximum_connections = retval['max_connections']

        for conn in retval['active_connections']:
            self._connections[conn] = {'handle': conn, 'connection_id': len(self._connections)}
            self.disconnect_sync(0)

        # If the dongle was previously left in a dirty state while still scanning, it will
        # not allow new scans to be started.  So, forcibly stop any in progress scans.
        # This throws a hardware error if scanning is not in progress which should be ignored.
        try:
            self.stop_scan()
        except HardwareError:
            # If we errored our it is because we were not currently scanning, so make sure
            # we update our self.scanning flag (which would not be updated by stop_scan since
            # it raised an exception.)
            self.scanning = False

        self._command_task.sync_command(['_set_mode', 0, 0]) #Disable advertising

        self._logger.info("BLED112 adapter supports %d connections", self.maximum_connections)

protected synchronized void releaseAllConnectionPools() {

    for (HikariDataSource pool : pools.values()) {

      if (pool != null) {
        logger.info("Releasing pool: {}...", pool.getPoolName());
        pool.close();
      }
    }
  }

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


Question:
Get locked documents for a date range or all documents if no date range is given
@param string $fromDateTime
@param string $tillDateTime
@return array

public function getLockedDocuments($fromDateTime = null , $tillDateTime = null)
    {
        return $this->getDataUpdater()->getLockedDocuments($fromDateTime, $tillDateTime);
    }

public static function get_metadata(collection $collection) : collection {
        $statsuserdaily = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];

        $statsuserweekly = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];

        $statsusermonthly = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];
        $collection->add_database_table('stats_user_daily', $statsuserdaily, 'privacy:metadata:statssummary');
        $collection->add_database_table('stats_user_weekly', $statsuserweekly, 'privacy:metadata:statssummary');
        $collection->add_database_table('stats_user_monthly', $statsusermonthly, 'privacy:metadata:statssummary');
        return $collection;
    }

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


Question:
Build the Huffman tree given an array of vertex degrees
@param vertexDegree vertexDegree[i] = degree of ith vertex

public void buildTree(int[] vertexDegree) {
        PriorityQueue<Node> pq = new PriorityQueue<>();
        for (int i = 0; i < vertexDegree.length; i++)
            pq.add(new Node(i, vertexDegree[i], null, null));

        while (pq.size() > 1) {
            Node left = pq.remove();
            Node right = pq.remove();
            Node newNode = new Node(-1, left.count + right.count, left, right);
            pq.add(newNode);
        }

        //Eventually: only one node left -> full tree
        Node tree = pq.remove();

        //Now: convert tree into binary codes. Traverse tree (preorder traversal) -> record path (left/right) -> code
        int[] innerNodePath = new int[MAX_CODE_LENGTH];
        traverse(tree, 0L, (byte) 0, -1, innerNodePath, 0);
    }

private void createVNodes(VCompound parent,List<Glyph> glyphs)
    {
        for(Glyph glyph: glyphs )
        {
            if (!glyphClazzOneOf(glyph, GlyphClazz.UNIT_OF_INFORMATION, GlyphClazz.STATE_VARIABLE))
            {
//                if(glyph.getClazz().equals(GlyphClazz.PROCESS.getClazz()))
//                {
//                    VCompound v = new VCompound(glyph); //TODO: v is never used; wat's the idea?
//                }

                if(!isChildless(glyph))
                {
                    VCompound v = new VCompound(glyph);
                    idToGLyph.put(glyph.getId(), glyph);
                    glyphToVNode.put(glyph, v);
                    parent.children.add(v);
                    createVNodes(v, glyph.getGlyph());
                }
                else
                {
                    VNode v = new VNode(glyph);
                    idToGLyph.put(glyph.getId(), glyph);
                    glyphToVNode.put(glyph, v);
                    parent.children.add(v);
                }
            }
        }
    }

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


Question: // Init prepares GRPC netListener for registration of individual service

func (p *Plugin) Init() (err error) {
	// Get GRPC configuration file
	if p.Config == nil {
		p.Config, err = p.getGrpcConfig()
		if err != nil || p.disabled {
			return err
		}
	}

	// Prepare GRPC server
	if p.grpcServer == nil {
		opts := p.Config.getGrpcOptions()
		if p.tlsConfig != nil {
			opts = append(opts, grpc.Creds(credentials.NewTLS(p.tlsConfig)))
		}
		if p.auther != nil {
			p.Log.Info("Token authentication for gRPC enabled")
			opts = append(opts, grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(p.auther.Authenticate)))
			opts = append(opts, grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(p.auther.Authenticate)))
		}
		p.grpcServer = grpc.NewServer(opts...)

		//grpclog.SetLogger(p.Log.NewLogger("grpc-server"))
	}

	return nil
}

func (mr *MockSystemAPIClientMockRecorder) Events(ctx, options interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Events", reflect.TypeOf((*MockSystemAPIClient)(nil).Events), ctx, options)
}

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


Question:
Concatenate an list of arrays of typed-objects
@param empty An empty array of the right type used for cloning
@param arrayList A list of arrays to concatenate.
@return The concatenated mega-array.

public static <T> T[] concatAll(final T[] empty, Iterable<T[]> arrayList) {
        assert(empty.length == 0);
        if (arrayList.iterator().hasNext() == false) {
            return empty;
        }

        int len = 0;
        for (T[] subArray : arrayList) {
            len += subArray.length;
        }
        int pos = 0;
        T[] result = Arrays.copyOf(empty, len);
        for (T[] subArray : arrayList) {
            System.arraycopy(subArray, 0, result, pos, subArray.length);
            pos += subArray.length;
        }
        return result;
    }

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question:
/*
(non-Javadoc)

@see com.google.inject.AbstractModule#configure()

@Override
    protected void configure() {
        bind(MessagingService.class).to(MessagingServiceImpl.class);

        bind(BounceProxyLifecycleMonitor.class).to(MonitoringServiceClient.class);
        bind(BounceProxyInformation.class).toProvider(BounceProxyInformationProvider.class);
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

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


Question:
Create component controller object by component name...

@param type $cname component name
@return null|\BController controller object

public function component_load($cname){
		//Trying to include component controller file...
		$fn=BCOMPONENTSFRAMEWORKPATH.$cname.DIRECTORY_SEPARATOR.'controller.php';
		if(!file_exists($fn)){
			$fn=BCOMPONENTSAPPLICATIONPATH.$cname.DIRECTORY_SEPARATOR.'controller.php';
			}
		if(!file_exists($fn)){
			BLog::addToLog('[Router]: Could not load component ('.$cname.')!',LL_ERROR);
			return NULL;
			}
		require_once($fn);
		//Trying to create object of controller class...
		$class='Controller_'.$cname;
		if(!class_exists($class)){
			BLog::addToLog('[Router]: Could not find class ('.$class.')!',LL_ERROR);
			return NULL;
			}
		$controller=new $class();
		$controller->componentname=$cname;
		return $controller;
		}

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:
Get the value of the given option as a boolean, or the given default
value if unspecified. If specified, the value is assumed to be
true if given as "true", regardless of case. All other
values are assumed to be false.

public boolean getBooleanValue(String name, boolean defaultValue) {

        String value = getValue(name);

        if (value == null) {
            return defaultValue;
        } else {
            return value.equals("true");
        }
    }

function getOptions () {
  return {
    compress: ('compress' in program) ? program.compress : false,
    debug: ('debug' in program) ? program.debug : false,
    deploy: false,
    grep: ('grep' in program) ? program.grep : false,
    invert: ('invert' in program) ? program.invert : false,
    maps: ('maps' in program) ? program.maps : false,
    reload: ('reload' in program) ? program.reload : false,
    script: ('script' in program) ? program.script : false,
    serve: ('serve' in program) ? program.serve : false,
    watch: false
  };
}

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


Question:
Removes all the cp option values where CPOptionId = ? from the database.

@param CPOptionId the cp option ID

@Override
	public void removeByCPOptionId(long CPOptionId) {
		for (CPOptionValue cpOptionValue : findByCPOptionId(CPOptionId,
				QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(cpOptionValue);
		}
	}

def update_chr(options = {} )
    @opt = {
      :name => ''
    }.merge!(options)
    return false if !@opt[:index]

    @index = @opt[:index].to_i

    # need to create the characters

    raise(NexusParser::ParseError, "Can't update character of index #{@index}, it doesn't exist! This is a problem parsing the character state labels. Check the indices. It may be for this character \"#{@opt[:name]}\".") if !@nf.characters[@index]

    (@nf.characters[@index].name = @opt[:name]) if @opt[:name]

    @opt.delete(:index)
    @opt.delete(:name)

    # the rest have states
    @opt.keys.each do |k|

      if (@nf.characters[@index].states != {}) && @nf.characters[@index].states[k] # state exists

        ## !! ONLY HANDLES NAME, UPDATE TO HANDLE notes etc. when we get them ##
        update_state(@index, :index => k, :name => @opt[k])

      else # doesn't, create it
        @nf.characters[@index].add_state(:label => k.to_s, :name => @opt[k])
      end
    end

  end

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


Question:
Called by remote workers. Useful to populate main module globals()
        for interactive shells. Retrieves the serialized function.

def getFunction(self):
        """"""
        return functionFactory(
            self.code,
            self.name,
            self.defaults,
            self.globals,
            self.imports,
        )

def check_valid_locations(self, locations=None):

        if locations is None:
            locations = self.locations
        for location in locations:
            if (not self.is_server(location) and
                not self.is_ssh_url(location) and
                not self.has_host(location)):
                err_exit('Unknown location: %(location)s' % locals())

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


Question:
Computes the statistical values
@param values
@return

private Map<String, Double> computeStatistics(List<Double> values) {
    Map<String, Double> results = new HashMap<>() ;

    DescriptiveStatistics stats = new DescriptiveStatistics();
    for (Double value : values) {
      stats.addValue(value);
    }

    results.put("mean", stats.getMean()) ;
    results.put("median", stats.getPercentile(50.0)) ;
    results.put("stdDeviation", stats.getStandardDeviation());
    results.put("iqr", stats.getPercentile(75) - stats.getPercentile(25));
    results.put("max", stats.getMax());
    results.put("min", stats.getMean());
    results.put("numberOfElements", (double)values.size()) ;

    return results ;
  }

static function applyOptions(array $input, array $options) {
        $data = array();

        foreach($input as $key => $val) {
            if(!isset($options[$key])) {
                continue;
            }

            if(\is_array($options[$key])) {
                if(!empty($options[$key]['parse'])) {
                    $call = $options[$key]['parse'];
                    $val = $call($val);
                }

                if(!empty($options[$key]['type'])) {
                    $val = self::typecastVariable($val, $options[$key]['type']);
                }

                $key = $options[$key]['key'] ?? $key;
            } elseif(!empty($options[$key])) {
                $key = $options[$key];
            }

            $data[$key] = $val;
        }

        return $data;
    }

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


Question: // GetDigitalWallet is handler for GET /users/{username}/digitalwallet

func (api UsersAPI) GetDigitalWallet(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	userMgr := user.NewManager(r)

	useobj, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	if len(useobj.DigitalWallet) == 0 {
		useobj.DigitalWallet = make([]user.DigitalAssetAddress, 0)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(useobj.DigitalWallet)
}

func WalletAccount(mctx libkb.MetaContext, remoter remote.Remoter, accountID stellar1.AccountID) (stellar1.WalletAccountLocal, error) {
	bundle, err := remote.FetchSecretlessBundle(mctx)
	if err != nil {
		return stellar1.WalletAccountLocal{}, err
	}
	entry, err := bundle.Lookup(accountID)
	if err != nil {
		return stellar1.WalletAccountLocal{}, err
	}

	return accountLocal(mctx, remoter, entry)
}

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


Question: // Get retrieves a value from bolthold and puts it into result.  Result must be a pointer

func (s *Store) Get(key, result interface{}) error {
	return s.Bolt().View(func(tx *bolt.Tx) error {
		return s.TxGet(tx, key, result)
	})
}

func (joy *Joystick) Hat(hat int) byte {
	return (byte)(C.SDL_JoystickGetHat(joy.cptr(), C.int(hat)))
}

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


Question:
Shows user's profile.

@param int $id

@return \yii\web\Response
@throws \yii\web\NotFoundHttpException

public function actionShow($id)
    {
        $profile = $this->finder->findProfileById($id);

        if ($profile === null) {
            throw new NotFoundHttpException();
        }

        return $this->render('show', [
            'profile' => $profile,
        ]);
    }

public static function queryByBaseId( $baseId, $config = [] ) {

		$type	= isset( $config[ 'type' ] ) ? $config[ 'type' ] : self::TYPE_COMMENT;
		$status	= isset( $config[ 'status' ] ) ? $config[ 'status' ] : self::STATUS_APPROVED;

		return self::find()->where( [ 'baseId' => $baseId, 'type' => $type, 'status' => $status ] );
	}

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


Question:
Return the most suitable {@link SQLDialect} for the given {@link DataSource}.
@param dataSource the source {@link DataSource}
@return the most suitable {@link SQLDialect}

public static SQLDialect getDialect(DataSource dataSource) {
		if (dataSource == null) {
			return SQLDialect.DEFAULT;
		}
		try {
			String url = JdbcUtils.extractDatabaseMetaData(dataSource, "getURL");
			SQLDialect sqlDialect = JDBCUtils.dialect(url);
			if (sqlDialect != null) {
				return sqlDialect;
			}
		}
		catch (MetaDataAccessException ex) {
			logger.warn("Unable to determine jdbc url from datasource", ex);
		}
		return SQLDialect.DEFAULT;
	}

public static Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName,
      String tableName, Properties props) {

    Optional<Table> table = Optional.<Table>absent();
    Optional<List<Partition>> partitions = Optional.<List<Partition>>absent();

    try {
      HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(props,
          Optional.fromNullable(props.getProperty(HiveDatasetFinder.HIVE_METASTORE_URI_KEY)));
      try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
        table = Optional.of(client.get().getTable(dbName, tableName));
        if (table.isPresent()) {
          org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(table.get());
          if (HiveUtils.isPartitioned(qlTable)) {
            partitions = Optional.of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent()));
          }
        }
      }
    } catch (NoSuchObjectException e) {
      return ImmutablePair.of(table, partitions);
    } catch (IOException | TException e) {
      throw new RuntimeException("Could not fetch destination table metadata", e);
    }

    return ImmutablePair.of(table, partitions);
  }

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


Question:
Gets range values.

@param AjaxChoiceLoaderInterface $choiceLoader The ajax choice loader

@return int[] The startTo and endTo

protected static function getRangeValues(AjaxChoiceLoaderInterface $choiceLoader)
    {
        $startTo = ($choiceLoader->getPageNumber() - 1) * $choiceLoader->getPageSize();
        $startTo = $startTo < 0 ? 0 : $startTo;
        $endTo = $startTo + $choiceLoader->getPageSize();

        if (0 >= $choiceLoader->getPageSize()) {
            $endTo = $choiceLoader->getSize();
        }

        if ($endTo > $choiceLoader->getSize()) {
            $endTo = $choiceLoader->getSize();
        }

        return [$startTo, $endTo];
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@SuppressWarnings("unchecked")
	public EList<IfcAppliedValue> getReferencingValues() {
		return (EList<IfcAppliedValue>) eGet(
				Ifc2x3tc1Package.Literals.IFC_REFERENCES_VALUE_DOCUMENT__REFERENCING_VALUES, true);
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question: Set the private key fields N, e, d and CRT params from hex strings

function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  var params = {};
  if (typeof N == 'object') {
    params = N;
  } else {
    params.n = N;
    params.e = E;
    params.d = D;
    params.p = P;
    params.q = Q;
    params.dmp1 = DP;
    params.dmq1 = DQ;
    params.coeff = C;
  }
  if(params.n != null && params.e != null && params.n.length > 0 && params.e.length > 0) {
    this.n = parseBigInt(params.n,16);
    this.e = parseInt(params.e,16);
    this.d = parseBigInt(params.d,16);
    this.p = parseBigInt(params.p,16);
    this.q = parseBigInt(params.q,16);
    this.dmp1 = parseBigInt(params.dmp1,16);
    this.dmq1 = parseBigInt(params.dmq1,16);
    this.coeff = parseBigInt(params.coeff,16);
  }
  else
    console.log("Invalid RSA private key");
}

def _tls_auth_encrypt(self, s):

        write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
        self.tls_session.wcs.seq_num += 1
        add_data = (write_seq_num +
                    pkcs_i2osp(self.type, 1) +
                    pkcs_i2osp(self.version, 2) +
                    pkcs_i2osp(len(s), 2))
        return self.tls_session.wcs.cipher.auth_encrypt(s, add_data,
                                                        write_seq_num)

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


Question: // Implementation taken from the Go standard library

func (l *lcowfs) Rel(basepath, targpath string) (string, error) {
	baseVol := ""
	targVol := ""
	base := l.Clean(basepath)
	targ := l.Clean(targpath)
	if sameWord(targ, base) {
		return ".", nil
	}
	base = base[len(baseVol):]
	targ = targ[len(targVol):]
	if base == "." {
		base = ""
	}
	// Can't use IsAbs - `\a` and `a` are both relative in Windows.
	baseSlashed := len(base) > 0 && base[0] == l.Separator()
	targSlashed := len(targ) > 0 && targ[0] == l.Separator()
	if baseSlashed != targSlashed || !sameWord(baseVol, targVol) {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
	bl := len(base)
	tl := len(targ)
	var b0, bi, t0, ti int
	for {
		for bi < bl && base[bi] != l.Separator() {
			bi++
		}
		for ti < tl && targ[ti] != l.Separator() {
			ti++
		}
		if !sameWord(targ[t0:ti], base[b0:bi]) {
			break
		}
		if bi < bl {
			bi++
		}
		if ti < tl {
			ti++
		}
		b0 = bi
		t0 = ti
	}
	if base[b0:bi] == ".." {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	if b0 != bl {
		// Base elements left. Must go up before going down.
		seps := strings.Count(base[b0:bl], string(l.Separator()))
		size := 2 + seps*3
		if tl != t0 {
			size += 1 + tl - t0
		}
		buf := make([]byte, size)
		n := copy(buf, "..")
		for i := 0; i < seps; i++ {
			buf[n] = l.Separator()
			copy(buf[n+1:], "..")
			n += 3
		}
		if t0 != tl {
			buf[n] = l.Separator()
			copy(buf[n+1:], targ[t0:])
		}
		return string(buf), nil
	}
	return targ[t0:], nil
}

func goTime(t C.pn_timestamp_t) time.Time {
	if t == 0 {
		return time.Time{}
	}
	return time.Unix(0, int64(t)*int64(time.Millisecond))
}

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


Question: Returns the value associated with the key, or null.

public V remove (K key) {
		int hashCode = key.hashCode();
		int index = hashCode & mask;
		if (key.equals(keyTable[index])) {
			keyTable[index] = null;
			V oldValue = valueTable[index];
			valueTable[index] = null;
			size--;
			return oldValue;
		}

		index = hash2(hashCode);
		if (key.equals(keyTable[index])) {
			keyTable[index] = null;
			V oldValue = valueTable[index];
			valueTable[index] = null;
			size--;
			return oldValue;
		}

		index = hash3(hashCode);
		if (key.equals(keyTable[index])) {
			keyTable[index] = null;
			V oldValue = valueTable[index];
			valueTable[index] = null;
			size--;
			return oldValue;
		}

		if (bigTable) {
			index = hash4(hashCode);
			if (key.equals(keyTable[index])) {
				keyTable[index] = null;
				V oldValue = valueTable[index];
				valueTable[index] = null;
				size--;
				return oldValue;
			}
		}

		return removeStash(key);
	}

public static <L, R> @NonNull Pair<L, R> of(final Map.Entry<L, R> entry) {
    return of(entry.getKey(), entry.getValue());
  }

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


Question:
JSON encodes data which isn't already a string and cleans up the result

@todo: could maybe do a better job removing slashes

@param mixed $data

@return string|null

public function convertToString($data) {
		if (!is_string($data)) {
			$data = @json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
			// Removing null byte and double slashes from object properties
			$data = str_replace(['\\u0000', '\\\\'], ["", "\\"], $data);
		}

		return $data;
	}

function stringify(values, options) {
  var settings = options || {}
  var left = settings.padLeft === false ? empty : space
  var right = settings.padRight ? space : empty

  /* Ensure the last empty entry is seen. */
  if (values[values.length - 1] === empty) {
    values = values.concat(empty)
  }

  return values.join(right + comma + left).trim()
}

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


Question:
applyStreaming.

@param requestContext a {@link javax.ws.rs.container.ContainerRequestContext} object.
@param context a {@link javax.ws.rs.ext.WriterInterceptorContext} object.
@throws java.io.IOException if any.

protected void applyStreaming(ContainerRequestContext requestContext, WriterInterceptorContext context)
            throws IOException {

        Object entity = context.getEntity();
        StreamingProcess<Object> process = MessageHelper.getStreamingProcess(context.getEntity(), manager);

        if (process != null) {
            ContainerResponseContext responseContext =
                    (ContainerResponseContext) requestContext.getProperty(RESP_PROP_N);
            responseContext.setStatusInfo(Response.Status.PARTIAL_CONTENT);
            context.getHeaders().putSingle(ACCEPT_RANGES, BYTES_RANGE);
            context.setType(StreamingOutput.class);
            context.setEntity(new MediaStreaming(
                            entity,
                    requestContext.getHeaderString(MediaStreaming.RANGE),
                            process,
                            context.getMediaType(),
                            context.getHeaders()
                    )
            );
        }
    }

func StreamServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamServerInterceptor {
	o := evaluateServerOpt(opts)
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		startTime := time.Now()
		newCtx := newLoggerForCall(stream.Context(), entry, info.FullMethod, startTime)
		wrapped := grpc_middleware.WrapServerStream(stream)
		wrapped.WrappedContext = newCtx

		err := handler(srv, wrapped)

		if !o.shouldLog(info.FullMethod, err) {
			return err
		}
		code := o.codeFunc(err)
		level := o.levelFunc(code)
		durField, durVal := o.durationFunc(time.Since(startTime))
		fields := logrus.Fields{
			"grpc.code": code.String(),
			durField:    durVal,
		}
		if err != nil {
			fields[logrus.ErrorKey] = err
		}

		levelLogf(
			ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder.
			level,
			"finished streaming call with code "+code.String())

		return err
	}
}

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


Question:
Discover and add to the configuration any properties on disk and on the network

@param classloader
@param config

private static void applyConfigs(final ClassLoader classloader, final GuiceConfig config)
	{
		// Load all the local configs
		for (String configFile : getPropertyFiles(config))
		{
			try
			{
				for (PropertyFile properties : loadConfig(classloader, configFile))
					config.setAll(properties);
			}
			catch (IOException e)
			{
				throw new IllegalArgumentException("Error loading configuration URLs from " + configFile, e);
			}
		}

		// Load the network config (if enabled)
		try
		{
			applyNetworkConfiguration(config);
		}
		catch (Throwable t)
		{
			throw new RuntimeException("Failed to retrieve configuration from network!", t);
		}
	}

public void setLicenseConfigurations(java.util.Collection<LicenseConfiguration> licenseConfigurations) {
        if (licenseConfigurations == null) {
            this.licenseConfigurations = null;
            return;
        }

        this.licenseConfigurations = new java.util.ArrayList<LicenseConfiguration>(licenseConfigurations);
    }

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


Question: Auto Generated Code

def dad_status_output_dad_status_entries_message(self, **kwargs):

        config = ET.Element("config")
        dad_status = ET.Element("dad_status")
        config = dad_status
        output = ET.SubElement(dad_status, "output")
        dad_status_entries = ET.SubElement(output, "dad-status-entries")
        message = ET.SubElement(dad_status_entries, "message")
        message.text = kwargs.pop('message')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Creates a node containing the type cast of
        the given one. If new_type == node.type, then
        nothing is done, and the same node is
        returned.

        Returns None on failure (and calls syntax_error)

def make_node(cls, new_type, node, lineno):

        assert isinstance(new_type, SymbolTYPE)

        # None (null) means the given AST node is empty (usually an error)
        if node is None:
            return None  # Do nothing. Return None

        assert isinstance(node, Symbol), '<%s> is not a Symbol' % node
        # The source and dest types are the same
        if new_type == node.type_:
            return node  # Do nothing. Return as is

        STRTYPE = TYPE.string
        # Typecasting, at the moment, only for number
        if node.type_ == STRTYPE:
            syntax_error(lineno, 'Cannot convert string to a value. '
                                 'Use VAL() function')
            return None

        # Converting from string to number is done by STR
        if new_type == STRTYPE:
            syntax_error(lineno, 'Cannot convert value to string. '
                                 'Use STR() function')
            return None

        # If the given operand is a constant, perform a static typecast
        if is_CONST(node):
            node.expr = cls(new_type, node.expr, lineno)
            return node

        if not is_number(node) and not is_const(node):
            return cls(new_type, node, lineno)

        # It's a number. So let's convert it directly
        if is_const(node):
            node = SymbolNUMBER(node.value, node.lineno, node.type_)

        if new_type.is_basic and not TYPE.is_integral(new_type):  # not an integer
            node.value = float(node.value)
        else:  # It's an integer
            new_val = (int(node.value) & ((1 << (8 * new_type.size)) - 1))  # Mask it

            if node.value >= 0 and node.value != new_val:
                errmsg.warning_conversion_lose_digits(node.lineno)
                node.value = new_val
            elif node.value < 0 and (1 << (new_type.size * 8)) + \
                    node.value != new_val:  # Test for positive to negative coercion
                errmsg.warning_conversion_lose_digits(node.lineno)
                node.value = new_val - (1 << (new_type.size * 8))

        node.type_ = new_type
        return node

def is_soundbar(self):
        """"""
        if self._is_soundbar is None:
            if not self.speaker_info:
                self.get_speaker_info()

            model_name = self.speaker_info['model_name'].lower()
            self._is_soundbar = any(model_name.endswith(s) for s in SOUNDBARS)

        return self._is_soundbar

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


Question:
Generates a random number using the given number of bits and RNG.

@param bits the number of bits for the number.
@param rng the random number generator to use.

@return the random number.

function generateRandom(bits, rng) {
  var num = new BigInteger(bits, rng);
  // force MSB set
  var bits1 = bits - 1;
  if(!num.testBit(bits1)) {
    num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
  }
  // align number on 30k+1 boundary
  num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
  return num;
}

def show_input(self, template_helper, language, seed):

        choices = []
        limit = self._limit
        if limit == 0:
            limit = len(self._choices)  # no limit

        rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed))

        # Ensure that the choices are random
        # we *do* need to copy the choices here
        random_order_choices = list(self._choices)
        rand.shuffle(random_order_choices)

        if self._multiple:
            # take only the valid choices in the first pass
            for entry in random_order_choices:
                if entry['valid']:
                    choices.append(entry)
                    limit = limit - 1
            # take everything else in a second pass
            for entry in random_order_choices:
                if limit == 0:
                    break
                if not entry['valid']:
                    choices.append(entry)
                    limit = limit - 1
        else:
            # need to have ONE valid entry
            for entry in random_order_choices:
                if not entry['valid'] and limit > 1:
                    choices.append(entry)
                    limit = limit - 1
            for entry in random_order_choices:
                if entry['valid'] and limit > 0:
                    choices.append(entry)
                    limit = limit - 1

        rand.shuffle(choices)

        header = ParsableText(self.gettext(language, self._header), "rst",
                              translation=self._translations.get(language, gettext.NullTranslations()))

        return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice(
            self.get_id(), header, self._multiple, choices,
            lambda text: ParsableText(self.gettext(language, text) if text else "", "rst",
                                      translation=self._translations.get(language, gettext.NullTranslations()))))

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


Question:
Get the field informations.
@param {string} fieldName - name or path of the field.
@param {object} complementaryInformation - Additional informations to extend the domain informations.
@return {object} - The builded field informations.

function getFieldInformations(fieldName, complementaryInformation) {
    checkIsString('fieldName', fieldName);
    checkIsObject('complementaryInformation', complementaryInformation);
    const fieldPath = fieldName.split(SEPARATOR);
    if (computedEntityContainer.hasIn(fieldPath)) {
        return computedEntityContainer.getIn(fieldPath).toJS();
    }
    return _buildFieldInformation(fieldPath).mergeDeep(complementaryInformation).toJS();
}

private function completeDefinition($id, Definition $definition)
    {
        if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
            return;
        }

        if ($this->container->isTrackingResources()) {
            $this->container->addResource(static::createResourceForClass($reflectionClass));
        }

        if (!$constructor = $reflectionClass->getConstructor()) {
            return;
        }

        $arguments = $definition->getArguments();
        foreach ($constructor->getParameters() as $index => $parameter) {
            if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
                continue;
            }

            try {
                if (!$typeHint = $parameter->getClass()) {
                    // no default value? Then fail
                    if (!$parameter->isOptional()) {
                        throw new RuntimeException(sprintf('Unable to autowire argument index %d ($%s) for the service "%s". If this is an object, give it a type-hint. Otherwise, specify this argument\'s value explicitly.', $index, $parameter->name, $id));
                    }

                    if (!array_key_exists($index, $arguments)) {
                        // specifically pass the default value
                        $arguments[$index] = $parameter->getDefaultValue();
                    }

                    continue;
                }

                if (null === $this->types) {
                    $this->populateAvailableTypes();
                }

                if (isset($this->types[$typeHint->name])) {
                    $value = new Reference($this->types[$typeHint->name]);
                } else {
                    try {
                        $value = $this->createAutowiredDefinition($typeHint, $id);
                    } catch (RuntimeException $e) {
                        if ($parameter->allowsNull()) {
                            $value = null;
                        } elseif ($parameter->isDefaultValueAvailable()) {
                            $value = $parameter->getDefaultValue();
                        } else {
                            throw $e;
                        }
                    }
                }
            } catch (\ReflectionException $e) {
                // Typehint against a non-existing class

                if (!$parameter->isDefaultValueAvailable()) {
                    throw new RuntimeException(sprintf('Cannot autowire argument %s for %s because the type-hinted class does not exist (%s).', $index + 1, $definition->getClass(), $e->getMessage()), 0, $e);
                }

                $value = $parameter->getDefaultValue();
            }

            $arguments[$index] = $value;
        }

        // it's possible index 1 was set, then index 0, then 2, etc
        // make sure that we re-order so they're injected as expected
        ksort($arguments);
        $definition->setArguments($arguments);
    }

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


Question:
Returns set of nth-farthest input tensors and labels.

    Returns:
      1. tf.Tensor (`batch_size`, `num_objects`,
                     (`num_features` + 3 * `num_objects`)).
      2. tf.Tensor (`batch_size`). Output object reference label.

def get_batch(self):

    params = [self._batch_size, self._num_objects, self._num_features]
    inputs, labels = tf.py_func(self._get_batch_data, params,
                                [tf.float32, tf.float32])
    inputs = tf.reshape(inputs, [self._batch_size, self._num_objects,
                                 self._num_features + self._num_objects * 3])
    labels = tf.reshape(labels, [-1])
    return inputs, labels

def es2et(
        es_fo,
        et_fo,
    ):

        et_fo.write("# Mapping information for read tuples" + os.linesep)
        et_fo.write("#" + os.linesep)
        et_fo.write("# RN:   read name" + os.linesep)
        et_fo.write("# I:    intervals with asigned categories" + os.linesep)
        et_fo.write("#" + os.linesep)
        et_fo.write("# RN	I" + os.linesep)

        last_rname = ""
        for line in es_fo:
            line = line.strip()
            if line == "" or line[0] == "#":
                continue
            else:
                (rname, mapped, ref, direction, left, right, category, nb_of_segments) = line.split("\t")
                nb_of_segments = int(nb_of_segments)

                # print(rname,last_rname,mapped)
                # new read
                if rname != last_rname:
                    # update
                    if last_rname != "":
                        voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
                        et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
                        et_fo.write(os.linesep)

                    # nulling
                    single_reads_statistics = [
                        {
                            "U": 0,
                            "u": 0,
                            "M": [],
                            "m": 0,
                            "w": 0,
                            "T": 0,
                            "t": 0,
                        } for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)
                    ]
                    last_rname = rname

                ####################
                # Unmapped segment #
                ####################

                #####
                # U #
                #####
                if category == "U":
                    for q in range(len(single_reads_statistics)):
                        single_reads_statistics[q]["U"] += 1

                #####
                # u #
                #####
                elif category == "u":
                    for q in range(len(single_reads_statistics)):
                        single_reads_statistics[q]["u"] += 1

                ##################
                # Mapped segment #
                ##################

                else:
                    mapping_quality = int(mapped.replace("mapped_", ""))
                    assert 0 <= mapping_quality and mapping_quality <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY, mapping_quality

                    #####
                    # m #
                    #####
                    if category == "m":
                        for q in range(mapping_quality + 1):
                            single_reads_statistics[q]["m"] += 1
                        for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
                            single_reads_statistics[q]["T"] += 1

                    #####
                    # w #
                    #####
                    elif category == "w":
                        for q in range(mapping_quality + 1):
                            single_reads_statistics[q]["w"] += 1
                        for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
                            single_reads_statistics[q]["t"] += 1

                    #####
                    # M #
                    #####
                    else:
                        assert category[0] == "M", category
                        segment_id = int(category.replace("M_", ""))
                        for q in range(mapping_quality + 1):
                            single_reads_statistics[q]["M"].append(segment_id)
                        for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
                            single_reads_statistics[q]["t"] += 1

        # last read
        voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
        et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
        et_fo.write(os.linesep)

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


Question: // SetAssignPublicIp sets the AssignPublicIp field's value.

func (s *AwsVpcConfiguration) SetAssignPublicIp(v string) *AwsVpcConfiguration {
	s.AssignPublicIp = &v
	return s
}

def _create_network_interface(
        self, ip_config_name, nic_name, public_ip, region,
        resource_group_name, subnet, accelerated_networking=False
    ):

        nic_config = {
            'location': region,
            'ip_configurations': [{
                'name': ip_config_name,
                'private_ip_allocation_method': 'Dynamic',
                'subnet': {
                    'id': subnet.id
                },
                'public_ip_address': {
                    'id': public_ip.id
                },
            }]
        }

        if accelerated_networking:
            nic_config['enable_accelerated_networking'] = True

        try:
            nic_setup = self.network.network_interfaces.create_or_update(
                resource_group_name, nic_name, nic_config
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to create network interface: {0}.'.format(
                    error
                )
            )

        return nic_setup.result()

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


Question:
Build a fresh configuration.

    :params defaults: a nested dictionary of keys and their default values
    :params metadata: the graph metadata
    :params loader: a configuration loader

def configure(defaults, metadata, loader):

    config = Configuration(defaults)
    config.merge(loader(metadata))
    validate(defaults, metadata, config)
    return config

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
Collect statistics on nanopub file

    input_fn can be json, jsonl or yaml and additionally gzipped

def nanopub_stats(ctx, input_fn):

    counts = {
        "nanopubs": 0,
        "assertions": {"total": 0, "subject_only": 0, "nested": 0, "relations": {}},
    }

    for np in bnf.read_nanopubs(input_fn):
        if "nanopub" in np:
            counts["nanopubs"] += 1
            counts["assertions"]["total"] += len(np["nanopub"]["assertions"])
            for assertion in np["nanopub"]["assertions"]:
                if assertion["relation"] is None:
                    counts["assertions"]["subject_only"] += 1
                else:
                    if re.match("\s*\(", assertion["object"]):
                        counts["assertions"]["nested"] += 1

                    if (
                        not assertion.get("relation")
                        in counts["assertions"]["relations"]
                    ):
                        counts["assertions"]["relations"][assertion.get("relation")] = 1
                    else:
                        counts["assertions"]["relations"][
                            assertion.get("relation")
                        ] += 1

    counts["assertions"]["relations"] = sorted(counts["assertions"]["relations"])

    print("DumpVar:\n", json.dumps(counts, indent=4))

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:
Rewrites paths in requirejs.config. Adds path names from namespaces and aliases to filenames with hashes.

@param string $realPath The filename of the main.js file.

@return string

private function getMainWithHashedPaths(string $realPath): string
  {
    $main_js_file = self::getMainJsFileName($realPath);
    // Read the main file.
    $js = file_get_contents($main_js_file);
    if ($js===false) $this->logError("Unable to read file '%s'.", $realPath);

    // Extract paths from main.
    preg_match('/^(.*paths:[^{]*)({[^}]*})(.*)$/sm', $js, $matches);
    if (!isset($matches[2])) $this->logError("Unable to find paths in '%s'.", $realPath);

    // @todo Remove from paths files already combined.

    // Lookup table as paths in requirejs.config, however, keys and values are flipped.
    $paths = [];
    // Replace aliases to paths with aliases to paths with hashes (i.e. paths to minimized files).
    list($base_url, $aliases) = $this->extractPaths($main_js_file);
    if (isset($base_url) && isset($paths))
    {
      foreach ($aliases as $alias => $path)
      {
        $path_with_hash = $this->getPathInResourcesWithHash($base_url, $path);
        if (isset($path_with_hash))
        {
          $paths[$this->removeJsExtension($path_with_hash)] = $alias;
        }
      }
    }

    // Add paths from modules that conform to ADM naming convention to paths with hashes (i.e. path to minimized files).
    foreach ($this->getResourcesInfo() as $info)
    {
      // @todo Skip *.main.js files.

      // Test JS file is not already in paths, e.g. 'jquery': 'jquery/jquery'.
      if (!isset($paths[$this->removeJsExtension($info['path_name_in_sources_with_hash'])]))
      {
        if (isset($info['path_name_in_sources']))
        {
          $module                 = $this->getNamespaceFromResourceFilename($info['full_path_name']);
          $path_with_hash         = $this->getNamespaceFromResourceFilename($info['full_path_name_with_hash']);
          $paths[$path_with_hash] = $module;
        }
      }
    }

    // Convert the paths to proper JS code.
    $matches[2] = json_encode(array_flip($paths), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    array_shift($matches);
    $js = implode('', $matches);

    return $js;
  }

private function parseRewriteRule( $match, $query ) {
        $matches = [ ];
        $request_match = $this->request;
        if ( ! empty( $this->request ) && strpos( $match, $this->request ) === 0 ) {
            $request_match = $this->request . '/' . $this->request;
        }
        if (
            preg_match( "#^{$match}#", $request_match, $matches )
            || preg_match( "#^{$match}#", urldecode( $request_match ), $matches )
        ) {
            $varmatch = NULL;
            if ( $this->resolver->isVerbose() && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
                $page = get_page_by_path( $matches[ $varmatch[1] ] );
                if ( ! $page ) {
                    return;
                }
            }
            $this->matched_rule = $match;
        }
        return $matches;
    }

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


Question:
TransformationCallback method
@param transform

@Override
  public void getTransform(Matrix transform) {
    super.getTransform(transform);
    if (mDrawMatrix != null) {
      transform.preConcat(mDrawMatrix);
    }
  }

func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope)) {
	log.Printf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum())
	cp.name = callbackName
	cp.processor = &callback
	cp.replace = true
	cp.parent.processors = append(cp.parent.processors, cp)
	cp.parent.reorder()
}

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


Question:
Notifies the change listeners that values have been added.
<p>
Note that the specified map of values will be wrapped in an unmodifiable map before being passed to the
listeners.

@param newValues Newly added values.

protected void doNotifyListenersOfAddedValues(Map<K, R> newValues) {
        List<MapValueChangeListener<K, R>> listenersCopy = new ArrayList<MapValueChangeListener<K, R>>(listeners);
        Map<K, R> unmodifiable = Collections.unmodifiableMap(newValues);
        for (MapValueChangeListener<K, R> listener : listenersCopy) {
            listener.valuesAdded(this, unmodifiable);
        }
    }

@Override
    public ConcurrentMap<String, Object> deserializeAttributes(final byte[] in ) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream( in );
            ois = createObjectInputStream( bis );

            final ConcurrentMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
            final int n = ( (Integer) ois.readObject() ).intValue();
            for ( int i = 0; i < n; i++ ) {
                final String name = (String) ois.readObject();
                final Object value = ois.readObject();
                if ( ( value instanceof String ) && ( value.equals( NOT_SERIALIZED ) ) ) {
                    continue;
                }
                if ( LOG.isDebugEnabled() ) {
                    LOG.debug( "  loading attribute '" + name + "' with value '" + value + "'" );
                }
                attributes.put( name, value );
            }

            return attributes;
        } catch ( final ClassNotFoundException e ) {
            LOG.warn( "Caught CNFE decoding "+ in.length +" bytes of data", e );
            throw new TranscoderDeserializationException( "Caught CNFE decoding data", e );
        } catch ( final IOException e ) {
            LOG.warn( "Caught IOException decoding "+ in.length +" bytes of data", e );
            throw new TranscoderDeserializationException( "Caught IOException decoding data", e );
        } finally {
            closeSilently( bis );
            closeSilently( ois );
        }
    }

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


Question: Register a loader for an extension.

function registerExtension(ext) {
  var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];

  var loader = normalLoader;
  if (process.env.running_under_istanbul) loader = istanbulLoader;

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
}

public function add(RendererInterface $item, $overWrite = false)
    {
        $uid = sha1(get_class($item).'_'.sha1(json_encode($item->supportedExtensions())));

        foreach ($item->supportedExtensions() as $ext) {
            if ($this->has($ext) && ! $overWrite) {
                throw new Exception('The collection ['. 1 .'] already collects for the path ['. 1 .']');
            }
        }

        $this->items[$uid] = $item;

        foreach ($item->supportedExtensions() as $ext) {
            $this->lookupTable[$ext] = $uid;
        }
    }

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


Question: Set Userdata[13] and Userdata[14] to the CRC value.

def set_crc(self):
        """"""
        data = self.bytes[6:20]
        crc = int(0)
        for b in data:
            # pylint: disable=unused-variable
            for bit in range(0, 8):
                fb = b & 0x01
                fb = fb ^ 0x01 if (crc & 0x8000) else fb
                fb = fb ^ 0x01 if (crc & 0x4000) else fb
                fb = fb ^ 0x01 if (crc & 0x1000) else fb
                fb = fb ^ 0x01 if (crc & 0x0008) else fb
                crc = ((crc << 1) | fb) & 0xffff
                b = b >> 1
        self._userdata['d13'] = (crc >> 8) & 0xff
        self._userdata['d14'] = crc & 0xff

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question:
@param string          $type
@param SchemaInterface $provider

@return void

protected function setCreatedProvider(string $type, SchemaInterface $provider): void
    {
        $this->createdProviders[$type] = $provider;
    }

func (s *RDSDataSpec) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RDSDataSpec"}
	if s.DatabaseCredentials == nil {
		invalidParams.Add(request.NewErrParamRequired("DatabaseCredentials"))
	}
	if s.DatabaseInformation == nil {
		invalidParams.Add(request.NewErrParamRequired("DatabaseInformation"))
	}
	if s.ResourceRole == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceRole"))
	}
	if s.ResourceRole != nil && len(*s.ResourceRole) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ResourceRole", 1))
	}
	if s.S3StagingLocation == nil {
		invalidParams.Add(request.NewErrParamRequired("S3StagingLocation"))
	}
	if s.SecurityGroupIds == nil {
		invalidParams.Add(request.NewErrParamRequired("SecurityGroupIds"))
	}
	if s.SelectSqlQuery == nil {
		invalidParams.Add(request.NewErrParamRequired("SelectSqlQuery"))
	}
	if s.SelectSqlQuery != nil && len(*s.SelectSqlQuery) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("SelectSqlQuery", 1))
	}
	if s.ServiceRole == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceRole"))
	}
	if s.ServiceRole != nil && len(*s.ServiceRole) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ServiceRole", 1))
	}
	if s.SubnetId == nil {
		invalidParams.Add(request.NewErrParamRequired("SubnetId"))
	}
	if s.SubnetId != nil && len(*s.SubnetId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("SubnetId", 1))
	}
	if s.DatabaseCredentials != nil {
		if err := s.DatabaseCredentials.Validate(); err != nil {
			invalidParams.AddNested("DatabaseCredentials", err.(request.ErrInvalidParams))
		}
	}
	if s.DatabaseInformation != nil {
		if err := s.DatabaseInformation.Validate(); err != nil {
			invalidParams.AddNested("DatabaseInformation", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

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


Question: 删除哈希表 key 中的一个或多个指定域，不存在的域将被忽略。

public Long hdel(Object key, Object... fields) {
		Jedis jedis = getJedis();
		try {
			return jedis.hdel(keyToBytes(key), fieldsToBytesArray(fields));
		}
		finally {close(jedis);}
	}

public final void mTABLE() throws RecognitionException {
		try {
			int _type = TABLE;
			int _channel = DEFAULT_TOKEN_CHANNEL;
			// druidG.g:595:17: ( ( 'TABLE' | 'table' ) )
			// druidG.g:595:18: ( 'TABLE' | 'table' )
			{
			// druidG.g:595:18: ( 'TABLE' | 'table' )
			int alt11=2;
			int LA11_0 = input.LA(1);
			if ( (LA11_0=='T') ) {
				alt11=1;
			}
			else if ( (LA11_0=='t') ) {
				alt11=2;
			}

			else {
				NoViableAltException nvae =
					new NoViableAltException("", 11, 0, input);
				throw nvae;
			}

			switch (alt11) {
				case 1 :
					// druidG.g:595:19: 'TABLE'
					{
					match("TABLE");

					}
					break;
				case 2 :
					// druidG.g:595:27: 'table'
					{
					match("table");

					}
					break;

			}

			}

			state.type = _type;
			state.channel = _channel;
		}
		finally {
			// do for sure before leaving
		}
	}

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


Question:
Determine if the given module has been loaded.

@param  string $namespace
@param  string $group
@param  string $locale
@return bool

protected function isModuleLoaded($author, $name, $locale)
    {
        return isset($this->loaded['Modules'][$author][$name][$locale]);
    }

func (p *Package) HasImport(packageName string) bool {
	_, has := p.Imports[packageName]
	return has
}

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


Question:
// NewCharmResourcesCommand returns a new command that lists resources defined
// by a charm.

func NewCharmResourcesCommand(resourceLister ResourceLister) modelcmd.ModelCommand {
	var c CharmResourcesCommand
	c.setResourceLister(resourceLister)
	return modelcmd.Wrap(&c)
}

def lookup(topic)
      if @cache.has_key? topic
        @cache[topic]
      else
        require_frontend

        etopic = case @shell_escape
        when :unix
          Tools.shell_escape(topic)
        when :windows
          Tools.win_shell_escape(topic)
        else
          topic
        end

        cmd = @frontend % etopic
        ##p "cmd", cmd
        content = `#{cmd} 2>&1`
        ##p "content", content

        # NOTES:
        # * Windows' ri always returns 0 even if article is not found. Work around it with a hack.
        # * Unix's ri sometimes returns 0 when it offers suggestions. Try `ri Object#is_ax?`.
        @cache[topic] = if $?.exitstatus != 0 or content.lines.count < 4
          nil
        else
          content
        end
      end
    end

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


Question:
Sets the number of bits in this response.

@param count the number of response bits as int.

public void setBitCount(int count) {
        bitCount = count;
        discretes = new BitVector(count);
        //set correct length, without counting unitid and fc
        setDataLength(discretes.byteSize() + 1);
    }

private RegisterDocumentResponse registerDocument(RegisterDocumentRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, DOC);
        internalRequest.addParameter("register", null);
        String strJson = JsonUtils.toJsonString(request);
        byte[] requestJson = null;
        try {
            requestJson = strJson.getBytes(DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new BceClientException("Unsupported encode.", e);
        }

        internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(requestJson.length));
        internalRequest.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        internalRequest.setContent(RestartableInputStream.wrap(requestJson));
        return invokeHttpClient(internalRequest, RegisterDocumentResponse.class);
    }

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


Question:
Get all user role permissions.

@return array|null

public function getPermissions()
    {
        $permissions = [[], []];

        foreach ($this->roles as $role) {
            $permissions[] = $role->getPermissions();
        }

        return call_user_func_array('array_merge', $permissions);
    }

def allowed_params_for(resource, params, controller=nil)
      controller  = set_controller(resource, controller)
      resource    = set_resource(resource)

      current_permission = load_permission(controller)

      if current_permission && current_permission.allowed_params
        params.require(resource).permit *current_permission.allowed_params
      end
    end

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


Question:
Internal function to initialise the command store, this allows the store to be lazy loaded only when needed.

@return  void

@since   __DEPLOY_VERSION__

private function initCommands()
	{
		if ($this->initialised)
		{
			return;
		}

		$this->initialised = true;

		foreach ($this->getDefaultCommands() as $command)
		{
			$this->addCommand($command);
		}
	}

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

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


Question:
/*
Rules are sorted in descending order of "specificity".
So we order first by SURT, exact-match,
then group, then policy.

public int compareTo(Rule o) {

    	int i;

        i = doCompare(this.getSurt(), o.getSurt());

        if (i != 0) {
        	return i;
        }

        // exact matches come after non-exact
    	i = doCompare(this.getExactMatch(), o.getExactMatch());

        if (i != 0) {
        	return i;
        }

    	// Compare by accessGroup, specific accessGroups take precedence
    	i = doCompare(this.getWho(), o.getWho());

        if (i != 0) {
        	return i;
        }

        // if we're still equal try capture date start
    	i = doCompare(this.getCaptureStart(), o.getCaptureStart());

        if (i != 0) {
        	return i;
        }

        // and retrieval date
    	i = doCompare(this.getRetrievalStart(), o.getRetrievalStart());

        if (i != 0) {
        	return i;
        }

    	i = doCompare(this.getSecondsSinceCapture(), o.getSecondsSinceCapture());

        return i;
    }

function getBaseUrl (hostUrl, psaDoc, relType, desc) {
  assert(psaDoc && typeof psaDoc === 'object', 'Invalid PSA service description document')
  assert(psaDoc.links && Array.isArray(psaDoc.links), 'Invalid PSA service description document (no links array)')
  var link = psaDoc.links.find(link => {
    var rel = link.rel
    return rel && typeof rel === 'string' && rel.indexOf(relType) !== -1
  })
  if (!link) {
    throw new Error(`Service does not provide the pinning-service ${desc} API (rel ${relType})`)
  }
  var href = link.href
  assert(href && typeof href === 'string', 'Invalid PSA service description document (no href on API link)')
  if (href.startsWith('/')) {
    href = hostUrl + link.href
  }
  return href
}

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


Question: // Timestamp sets the value for optional timestamp parameter

func (c *ReactionsAddCall) Timestamp(timestamp string) *ReactionsAddCall {
	c.timestamp = timestamp
	return c
}

protected static function define_properties() {
        return array(
            'name' => array(
                'type' => PARAM_TEXT,
                'description' => 'The purpose name.',
            ),
            'description' => array(
                'type' => PARAM_RAW,
                'description' => 'The purpose description.',
                'null' => NULL_ALLOWED,
                'default' => '',
            ),
            'descriptionformat' => array(
                'choices' => array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN),
                'type' => PARAM_INT,
                'default' => FORMAT_HTML
            ),
            'lawfulbases' => array(
                'type' => PARAM_TEXT,
                'description' => 'Comma-separated IDs matching records in tool_dataprivacy_lawfulbasis.',
            ),
            'sensitivedatareasons' => array(
                'type' => PARAM_TEXT,
                'description' => 'Comma-separated IDs matching records in tool_dataprivacy_sensitive',
                'null' => NULL_ALLOWED,
                'default' => ''
            ),
            'retentionperiod' => array(
                'type' => PARAM_ALPHANUM,
                'description' => 'Retention period. ISO_8601 durations format (as in DateInterval format).',
                'default' => '',
            ),
            'protected' => array(
                'type' => PARAM_INT,
                'description' => 'Data retention with higher precedent over user\'s request to be forgotten.',
                'default' => '0',
            ),
        );
    }

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


Question:
Writes the encoded TLV element to the specified output stream.

@param out
the output stream to which to write the TLV element data.

@throws TLVParserException
when I/O error occurred or TLV encoding failed.

public void writeTo(OutputStream out) throws TLVParserException {
        Util.notNull(out, "Output stream");
        try {
            assertActualContentLengthIsInTLVLimits(getContentLength());
            out.write(encodeHeader());
            out.write(getContent());
        } catch (IOException e) {
            throw new TLVParserException("Writing TLV element (" + convertHeader() + ")  to output stream failed", e);
        }
    }

def load_from_file(swag_path, swag_type='yml', root_path=None):

    if swag_type not in ('yaml', 'yml'):
        raise AttributeError("Currently only yaml or yml supported")
        # TODO: support JSON

    try:
        enc = detect_by_bom(swag_path)
        with codecs.open(swag_path, encoding=enc) as yaml_file:
            return yaml_file.read()
    except IOError:
        # not in the same dir, add dirname
        swag_path = os.path.join(
            root_path or os.path.dirname(__file__), swag_path
        )
        try:
            enc = detect_by_bom(swag_path)
            with codecs.open(swag_path, encoding=enc) as yaml_file:
                return yaml_file.read()
        except IOError:  # pragma: no cover
            # if package dir
            # see https://github.com/rochacbruno/flasgger/pull/104
            # Still not able to reproduce this case
            # test are in examples/package_example
            # need more detail on how to reproduce IOError here
            swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep)
            path = swag_path.replace(
                (root_path or os.path.dirname(__file__)), ''
            ).split(os.sep)[1:]
            site_package = imp.find_module(path[0])[1]
            swag_path = os.path.join(site_package, os.sep.join(path[1:]))
            with open(swag_path) as yaml_file:
                return yaml_file.read()

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


Question: // newSession returns a new session from sessionid

func (p *provider) newSession(sid string, expires time.Duration) *Session {
	onExpire := func() {
		p.Destroy(sid)
	}

	lifetime := p.db.Acquire(sid, expires)

	// simple and straight:
	if !lifetime.IsZero() {
		// if stored time is not zero
		// start a timer based on the stored time, if not expired.
		lifetime.Revive(onExpire)
	} else {
		// Remember:  if db not exist or it has been expired
		// then the stored time will be zero(see loadSessionFromDB) and the values will be empty.
		//
		// Even if the database has an unlimited session (possible by a previous app run)
		// priority to the "expires" is given,
		// again if <=0 then it does nothing.
		lifetime.Begin(expires, onExpire)
	}

	sess := &Session{
		sid:      sid,
		provider: p,
		flashes:  make(map[string]*flashMessage),
		Lifetime: lifetime,
	}

	return sess
}

func (db *Database) Len(sid string) (n int) {
	db.Service.View(func(tx *bolt.Tx) error {
		b := db.getBucketForSession(tx, sid)
		if b == nil {
			return nil
		}

		n = b.Stats().KeyN
		return nil
	})

	return
}

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


Question:
Modify this content.

@param string $content Content data.
@param string|null $plainText Plain text version of this content.

public function modify(string $content, string $plainText = null)
    {
        $this->html = $content;
        $this->text = $plainText;
    }

def _get_elements_property(parent_to_parse, element_path, prop_name):

    parent_element = get_element(parent_to_parse)

    if parent_element is None:
        return []

    if element_path and not element_exists(parent_element, element_path):
        return []

    if not element_path:
        texts = getattr(parent_element, prop_name)
        texts = texts.strip() if isinstance(texts, string_types) else texts
        texts = [texts] if texts else []
    else:
        texts = [t for t in (
            prop.strip() if isinstance(prop, string_types) else prop
            for prop in (getattr(node, prop_name) for node in parent_element.findall(element_path)) if prop
        ) if t]

    return texts

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


Question:
// kademlias returns all Kademlia instances that are set
// in simulation bucket.

func (s *Simulation) kademlias() (ks map[enode.ID]*network.Kademlia) {
	items := s.UpNodesItems(BucketKeyKademlia)
	log.Debug("kademlia len items", "len", len(items))
	ks = make(map[enode.ID]*network.Kademlia, len(items))
	for id, v := range items {
		k, ok := v.(*network.Kademlia)
		if !ok {
			continue
		}
		ks[id] = k
	}
	return ks
}

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
Process text.

@param Request $request
@param FormInterface $form

@return bool

public function process(Request $request, FormInterface $form)
    {
        if ($request->isMethod('POST')) {
            $form->submit($request);
            if ($form->isValid()) {
                /** @var TextInterface $text */
                $text = $form->getData();
                foreach ($text->getTranslations() as $translation) {
                    $translation->setText($text);
                }
                $this->textManager->add($form->getData());

                return true;
            }
        }

        return false;
    }

public function GetActiveSettingAsHiddenInputField()
    {
        $sInput = '';
        if (false !== $this->GetActiveStartValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_START_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveStartValue()).'" />';
        }
        if (false !== $this->GetActiveEndValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_END_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveEndValue()).'" />';
        }

        return $sInput;
    }

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


Question: Given a track, force scrape it.

def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''):

    hard_track_url = get_hard_track_url(track['id'])

    # We have no info on this track whatsoever.
    if not 'title' in track:
        return None

    if not keep_previews:
        if (track.get('duration', 0) < track.get('full_duration', 0)):
            puts_safe(colored.yellow("Skipping preview track") + colored.white(": " + track['title']))
            return None

    # May not have a "full name"
    name = track['user'].get('full_name', '')
    if name == '':
        name = track['user']['username']

    filename = sanitize_filename(name + ' - ' + track['title'] + '.mp3')

    if folders:
        name_path = join(custom_path, name)
        if not exists(name_path):
            mkdir(name_path)
        filename = join(name_path, filename)
    else:
        filename = join(custom_path, filename)

    if exists(filename):
        puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track['title']))
        return None

    # Skip already downloaded track.
    if filename in filenames:
        return None

    if hard_track_url:
        puts_safe(colored.green("Scraping") + colored.white(": " + track['title']))
    else:
        # Region coded?
        puts_safe(colored.yellow("Unable to download") + colored.white(": " + track['title']))
        return None

    filename = download_file(hard_track_url, filename)
    tagged = tag_file(filename,
             artist=name,
             title=track['title'],
             year=track['created_at'][:4],
             genre=track['genre'],
             album=album_name,
             artwork_url=track['artwork_url'])
    if not tagged:
        wav_filename = filename[:-3] + 'wav'
        os.rename(filename, wav_filename)
        filename = wav_filename

    return filename

@Override
	int compare(Treap treap, int left, int node) {
		// Compares two segments on a sweep line passing through m_sweep_y,
		// m_sweep_x.
		if (m_b_intersection_detected)
			return -1;

		int right = treap.getElement(node);
		m_current_node = node;
		return compareSegments(left, left, right, right);
	}

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


Question:
Set vertical align for images with fit mode CONTAIN and COVER
@param int $verticalAlign
@return $this
@throws \InvalidArgumentException

public function setVerticalAlign($verticalAlign) {
        if (!in_array($verticalAlign, [static::TOP, static::CENTER, static::BOTTOM], true)) {
            throw new \InvalidArgumentException(
                '$verticalAlign argument must be one of: ImagesGroupConfig::TOP, ImagesGroupConfig::CENTER, ImagesGroupConfig::BOTTOM'
            );
        }
        $this->verticalAlign = $verticalAlign;
        return $this;
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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