Question:
Returns the column number from the given cell reference (eg. A1).
<P>
eg. A=1, B=2, etc
@param str The cell reference
@return The column number for the cell

private int getColumn(String str)
    {
        int ret = 0;

        // Find the end of the column characters
        int len = 0;
        for(int i = 0;
            i < str.length() && str.charAt(i) >= 'A' && str.charAt(i) <= 'Z';
            i++, len++);

        // Calculate the column number
        int pos = 0;
        for(int i = len-1; i >= 0; i--, pos++)
        {
            char c = str.charAt(i);
            int col = (int)(c - '@');
            if(pos > 0)
                col *= 26*pos;
            ret += col;
        }

        return ret;
    }

func (c *Call) matches(args []interface{}) error {
	if !c.methodType.IsVariadic() {
		if len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}

		for i, m := range c.args {
			if !m.Matches(args[i]) {
				return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
					c.origin, strconv.Itoa(i), args[i], m)
			}
		}
	} else {
		if len(c.args) < c.methodType.NumIn()-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
				c.origin, len(c.args), c.methodType.NumIn()-1)
		}
		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}
		if len(args) < len(c.args)-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
				c.origin, len(args), len(c.args)-1)
		}

		for i, m := range c.args {
			if i < c.methodType.NumIn()-1 {
				// Non-variadic args
				if !m.Matches(args[i]) {
					return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
						c.origin, strconv.Itoa(i), args[i], m)
				}
				continue
			}
			// The last arg has a possibility of a variadic argument, so let it branch

			// sample: Foo(a int, b int, c ...int)
			if i < len(c.args) && i < len(args) {
				if m.Matches(args[i]) {
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
					// Got Foo(a, b) want Foo(matcherA, matcherB)
					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
					continue
				}
			}

			// The number of actual args don't match the number of matchers,
			// or the last matcher is a slice and the last arg is not.
			// If this function still matches it is because the last matcher
			// matches all the remaining arguments or the lack of any.
			// Convert the remaining arguments, if any, into a slice of the
			// expected type.
			vargsType := c.methodType.In(c.methodType.NumIn() - 1)
			vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
			for _, arg := range args[i:] {
				vargs = reflect.Append(vargs, reflect.ValueOf(arg))
			}
			if m.Matches(vargs.Interface()) {
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
				break
			}
			// Wrong number of matchers or not match. Fail.
			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
			return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
				c.origin, strconv.Itoa(i), args[i:], c.args[i])

		}
	}

	// Check that all prerequisite calls have been satisfied.
	for _, preReqCall := range c.preReqs {
		if !preReqCall.satisfied() {
			return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
				c.origin, preReqCall, c)
		}
	}

	// Check that the call is not exhausted.
	if c.exhausted() {
		return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
	}

	return nil
}

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


Question: explicit deletes the object from the singleton reference dictionary. This is mandatory to be able to delete the object using del(). Also, any attempt to reload an object with the same parameters will result un a new instance being created

def unreference(self) :
		""
		try :
			del(self.__class__._instances[makeRabaObjectSingletonKey(self.__class__.__name__, self._raba_namespace, self.raba_id)])
		except KeyError :
			pass

public static function purge_by_definition($component, $area, array $identifiers = array()) {
        // Create the cache.
        $cache = cache::make($component, $area, $identifiers);
        // Initialise, in case of a store.
        if ($cache instanceof cache_store) {
            $factory = cache_factory::instance();
            $definition = $factory->create_definition($component, $area, null);
            $cacheddefinition = clone $definition;
            $cacheddefinition->set_identifiers($identifiers);
            $cache->initialise($cacheddefinition);
        }
        // Purge baby, purge.
        $cache->purge();
        return true;
    }

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


Question: // String returns the string representation of a Multiaddr

func (m *multiaddr) String() string {
	s, err := bytesToString(m.bytes)
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
	}
	return s
}

func Dissect(dissect bool, data []byte) {
	if dissect {
		dissectLock.Lock()
		defer dissectLock.Unlock()

		initParser()
		parser.DecodeLayers(data, &cache.decoded)

		for _, typ := range cache.decoded {
			switch typ {
			case layers.LayerTypeEthernet:
				fmt.Println(gopacket.LayerString(&cache.eth))
			case layers.LayerTypeIPv4:
				fmt.Println(gopacket.LayerString(&cache.ip4))
			case layers.LayerTypeIPv6:
				fmt.Println(gopacket.LayerString(&cache.ip6))
			case layers.LayerTypeTCP:
				fmt.Println(gopacket.LayerString(&cache.tcp))
			case layers.LayerTypeUDP:
				fmt.Println(gopacket.LayerString(&cache.udp))
			case layers.LayerTypeICMPv4:
				fmt.Println(gopacket.LayerString(&cache.icmp4))
			case layers.LayerTypeICMPv6:
				fmt.Println(gopacket.LayerString(&cache.icmp6))
			default:
				fmt.Println("Unknown layer")
			}
		}
		if parser.Truncated {
			fmt.Println("  Packet has been truncated")
		}

	} else {
		fmt.Print(hex.Dump(data))
	}
}

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


Question:
Print the the detail of the given instruction (class, method, etc.)

@param ins Instruction
@param cpg Constant Pool

public static void printOpCode(Instruction ins, ConstantPoolGen cpg) {

        if (ins instanceof InvokeInstruction) {
            InvokeInstruction invokeIns = (InvokeInstruction) ins;
            System.out.println(formatName(ins) + " " + invokeIns.getClassName(cpg).replaceAll("\\.", "/") + "." + invokeIns.getMethodName(cpg) + invokeIns.getSignature(cpg));
        } else if (ins instanceof LDC) {
            LDC i = (LDC) ins;
            System.out.println(formatName(ins) + " \""+i.getValue(cpg).toString()+"\"");
        } else if (ins instanceof NEW) {
            NEW i = (NEW) ins;
            ObjectType type = i.getLoadClassType(cpg);
            System.out.println(formatName(ins) + " " + type.toString());
        } else if (ins instanceof LoadInstruction) {
            LoadInstruction i = (LoadInstruction) ins;
            System.out.println(formatName(ins) +" "+i.getIndex() + " => [stack]");
        } else if (ins instanceof StoreInstruction) {
            StoreInstruction i = (StoreInstruction) ins;
            System.out.println(formatName(ins) +" (objectref) => "+i.getIndex() + "");
        } else if (ins instanceof FieldInstruction) {
            FieldInstruction i = (FieldInstruction) ins;
            System.out.println(formatName(ins) +" "+i.getFieldName(cpg) + "");
        }  else if (ins instanceof IfInstruction) {
            IfInstruction i = (IfInstruction) ins;
            System.out.println(formatName(ins) +" target => "+i.getTarget().toString()+ "");
        } else if (ins instanceof ICONST) {
            ICONST i = (ICONST) ins;
            System.out.println(formatName(ins) +" "+i.getValue()+" ("+i.getType(cpg)+")");
        } else if (ins instanceof GOTO) {
            GOTO i = (GOTO) ins;
            System.out.println(formatName(ins) +" target => "+i.getTarget().toString());
        } else {
            System.out.println(formatName(ins));
        }
    }

public function listCommand($services = [], $table_pattern = '')
    {
        foreach ($services ?: $this->_getDbServices() as $service) {
            /** @var \ManaPHP\DbInterface $db */
            $db = $this->_di->getShared($service);

            $this->console->writeLn(['service: `:service`', 'service' => $service], Console::FC_CYAN);
            foreach ($this->_getTables($service, $table_pattern) as $row => $table) {
                $columns = (array)$db->getMetadata($table)[Db::METADATA_ATTRIBUTES];
                $primaryKey = $db->getMetadata($table)[Db::METADATA_PRIMARY_KEY];
                foreach ($columns as $i => $column) {
                    if (in_array($column, $primaryKey, true)) {
                        $columns[$i] = $this->console->colorize($column, Console::FC_RED);
                    }
                }

                $this->console->writeLn([' :row :table(:columns)',
                    'row' => sprintf('%2d ', $row + 1),
                    'table' => $this->console->colorize($table, Console::FC_GREEN),
                    'columns' => implode(', ', $columns)]);
            }
        }
    }

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


public DirContext authenticateByDnForContext(String userDN, char[] pwd)
		throws NamingException
	{
		Hashtable<String,Object>  env = new Hashtable<String,Object> ();

	      setupBasicProperties(env, url);

	      setupSecurityProperties(env, userDN, pwd);

	      return openContext(env);
	}

def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)

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


Question:
Sends a HTTP request to the configured server.

    All exceptions are suppressed but emit a warning message in the log.

def send_webhook(config, payload):

    try:
        response = requests.post(
            config['webhook_url'],
            data=json.dumps(payload, cls=ModelJSONEncoder),
            headers={config['api_key_header_name']: config['api_key']},
        )
    except Exception as e:
        logger.warning('Unable to send webhook: ({1}) {2}'.format(
            e.__class__.__name__,
            e.message,
        ))
    else:
        logger.debug('Webhook response: ({0}) {1}'.format(
            response.status_code,
            response.text,
        ))

public static function run(App $app, ?Config $config = null): void
    {
        \ini_set('display_errors', '0');
        \ini_set('html_errors', '0');

        $k1 = new static($config);
        $k1->runApp($app);
    }

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


Question:
Handle an event.

@param \League\Event\EventInterface $event The triggering event

@return void
@see \League\Event\ListenerInterface::handle()

public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // load the service instance and create the SSL file if not available
            /** @var \AppserverIo\Appserver\Core\Api\ContainerService $service */
            $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\ContainerService');
            $service->createSslCertificate(new \SplFileInfo($service->getConfDir(CreateSslCertificateListener::DEFAULT_CERTIFICATE_NAME)));

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

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


Question:
Calls cb when the app is offline from the backend

TODO: Find a kludge for this, for Firefox. Firefox only triggers offline when
the user sets the browser to "Offline mode"

@param {Function} cb.

function(cb) {
    // If we're inside phonegap use its event.
    if (window.phonegap) {
      return document.addEventListener("offline", cb, false);
    } else if (window.addEventListener) {
      // With the offline HTML5 event from the window
      this.addLocalEventListener(window, "offline", cb);
    } else {
      /*
      Works in IE with the Work Offline option in the
      File menu and pulling the ethernet cable
      Ref: http://robertnyman.com/html5/offline/online-offline-events.html
    */
      document.body.onoffline = cb;
    }
  }

function (cfg) {
            var groupsRe, self = this, fn = cfg.fn, context = cfg.context, currentTarget = self.currentTarget, observers = self.observers, groups = cfg.groups;
            if (!observers.length) {
                return;
            }
            if (groups) {
                groupsRe = Utils.getGroupsRe(groups);
            }
            var i, j, t, observer, observerContext, len = observers.length;    // 移除 fn
            // 移除 fn
            if (fn || groupsRe) {
                context = context || currentTarget;
                for (i = 0, j = 0, t = []; i < len; ++i) {
                    observer = observers[i];
                    observerContext = observer.context || currentTarget;
                    if (context !== observerContext || // 指定了函数，函数不相等，保留
                        fn && fn !== observer.fn || // 指定了删除的某些组，而该 observer 不属于这些组，保留，否则删除
                        groupsRe && !observer.groups.match(groupsRe)) {
                        t[j++] = observer;
                    }
                }
                self.observers = t;
            } else {
                // 全部删除
                self.reset();
            }    // does not need to clear memory if customEvent has no observer
                 // customEvent has defaultFn .....!
                 // self.checkMemory();
        }

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


Question:
/*
(non-Javadoc)

@see
edu.umd.cs.findbugs.classfile.IAnalysisEngine#analyze(edu.umd.cs.findbugs
.classfile.IAnalysisCache, java.lang.Object)

@Override
    public ClassContext analyze(IAnalysisCache analysisCache, ClassDescriptor descriptor) throws CheckedAnalysisException {

        JavaClass javaClass = analysisCache.getClassAnalysis(JavaClass.class, descriptor);
        ClassContext classContext = new ClassContext(javaClass, AnalysisContext.currentAnalysisContext());
        return classContext;
    }

public synchronized ClassInfo loadClassInfo(ClassReader reader)
        throws IOException
    {
        infoVisitor.reset();
        reader.accept(infoVisitor, 0);
        return infoVisitor.getClassInfo();
    }

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


Question: // getInboundCall returns the inbound call on this context or nil.

func getInboundCall(ctx context.Context) (*InboundCall, bool) {
	call, ok := ctx.Value(inboundCallKey{}).(*InboundCall)
	return call, ok
}

function determineContext( scope ) {
   let current = scope;
   while( !current.hasOwnProperty( 'widget' ) && current !== current.$root ) {
      current = current.$parent;
   }

   const isInWidget = !!current.widget;

   return {
      widgetName: isInWidget ? current.widget.path : '',
      widgetId: isInWidget ? current.widget.id : '',
      widgetScopeId: isInWidget ? current.$id : null,
      scopeId: scope.$id
   };
}

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


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

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

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

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

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

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

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

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

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

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


Question: Returns the DN for the given CN attribute

def lookup_dn(cn)
      service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn
    end

function(layerContext, node) {
        layerContext.version = node.getAttribute("version");
         layerContext.url = this.getOnlineResource_href(node);
         layerContext.metadata.servertitle = node.getAttribute("title");
    }

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


Question:
add object (as occurence) if it doesn't exist
 return object or nil

def add_object object , level
      # see if we we came accross this before
      if( occurence = @objects[object.object_id] )
        #puts "reset level #{level} at #{occurence.level}" if occurence.referenced #== 19
        if occurence.level > level
          #always store the most shallow level
          occurence.level = level
        end
        # and only one Occurence for each object, create a reference for the second occurence
        unless occurence.referenced
#          puts "referencing #{@counter} #{occurence.object.name}, at level #{level}/#{occurence.level} " if @counter == 23
#          puts "referencing #{@counter} #{occurence.object.name}, at level #{level}/#{occurence.level} " if @counter == 19
          if object.respond_to? :rxf_reference_name
            reference = object.rxf_reference_name
            reference = reference.to_s.gsub(/\s|\W/ , "") #remove space and stuff
            if( @references.include?(reference) or reference.empty?)
              reference = "#{reference}-#{@counter}"
              @counter = @counter + 1
            end
          else
            reference = @counter.to_s
            @counter = @counter + 1
          end
          occurence.set_reference(reference)
          @references << reference
        end
        return nil
      end
      # if first time see, create and store Occurence
      @objects[object.object_id] =  Occurence.new( object , level )
      return object
    end

def get_experiments
      @experiments ||= begin
        # fetch our data from the cache
        data = Gxapi.with_error_handling do
          # handle caching
          self.list_experiments_from_cache
        end
        # turn into Gxapi::Ostructs
        (data || []).collect{|data| Ostruct.new(data)}
      end
    end

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


Question:
@param       $to
@param null  $data
@param array $gateways

@return bool

public function send($to, $data = [], array $gateways = [])
	{
		try {
			$flag = false;

			$this->setKey($to);

			//1. get code from storage.
			$code = $this->getCodeFromStorage();

			if ($this->needNewCode($code)) {
				$code = $this->getNewCode($to);
			}

			$validMinutes = (int) config('ibrand.sms.code.validMinutes', 5);

			if (!($data instanceof MessageInterface)) {
				$message = new CodeMessage($code->code, $validMinutes, $data);
			} else {
				$message = $data;
			}

			$results = $this->easySms->send($to, $message, $gateways);

			foreach ($results as $key => $value) {
				if ('success' == $value['status']) {
					$code->put('sent', true);
					$code->put('sentAt', Carbon::now());
					$this->storage->set($this->key, $code);
					$flag = true;
				}
			}
		} catch (NoGatewayAvailableException $noGatewayAvailableException) {
			$results = $noGatewayAvailableException->results;
			$flag    = false;
		} catch (\Exception $exception) {
			$results = $exception->getMessage();
			$flag    = false;
		}

		DbLogger::dispatch($code, json_encode($results), $flag);

		return $flag;
	}

func (t *Template) GetAllAWSEC2TransitGatewayRouteTableAssociationResources() map[string]*resources.AWSEC2TransitGatewayRouteTableAssociation {
	results := map[string]*resources.AWSEC2TransitGatewayRouteTableAssociation{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSEC2TransitGatewayRouteTableAssociation:
			results[name] = resource
		}
	}
	return results
}

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


Question:
Checks to see if the Rows, in XML Tables exceed the maximum number of columns.

@param doc The XML DOM Document to be validated.
@return True if the XML is valid, otherwise false.

public static boolean validateTables(final Document doc) {
        final NodeList tables = doc.getElementsByTagName("table");
        for (int i = 0; i < tables.getLength(); i++) {
            final Element table = (Element) tables.item(i);
            if (!validateTableRows(table)) {
                return false;
            }
        }

        final NodeList informalTables = doc.getElementsByTagName("informaltable");
        for (int i = 0; i < informalTables.getLength(); i++) {
            final Element informalTable = (Element) informalTables.item(i);
            if (!validateTableRows(informalTable)) {
                return false;
            }
        }

        return true;
    }

def _isvalid(self, datatype):
        ''''''
        if datatype in self.meta:
            return bool(Dap._meta_valid[datatype].match(self.meta[datatype]))
        else:
            return datatype in Dap._optional_meta

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


Question: // SetVersionId sets the VersionId field's value.

func (s *TableVersionError) SetVersionId(v string) *TableVersionError {
	s.VersionId = &v
	return s
}

func (s *Finding) SetUpdatedAt(v string) *Finding {
	s.UpdatedAt = &v
	return s
}

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


Question:
// ConfigureArgs takes the basic template arguments generated from the command
// arguments and environment and modifies them according to the BootstrapConfig.

func (c *BootstrapConfig) ConfigureArgs(args *BootstrapTplArgs) error {

	// Attempt to setup sink(s) from high-level config. Note the args are passed
	// by ref and modified in place.
	if err := c.generateStatsSinks(args); err != nil {
		return err
	}

	if c.StatsConfigJSON != "" {
		// StatsConfig overridden explicitly
		args.StatsConfigJSON = c.StatsConfigJSON
	} else {
		// Attempt to setup tags from high-level config. Note the args are passed by
		// ref and modified in place.
		if err := c.generateStatsConfig(args); err != nil {
			return err
		}
	}

	if c.StaticClustersJSON != "" {
		args.StaticClustersJSON = c.StaticClustersJSON
	}
	if c.StaticListenersJSON != "" {
		args.StaticListenersJSON = c.StaticListenersJSON
	}
	// Setup prometheus if needed. This MUST happen after the Static*JSON is set above
	if c.PrometheusBindAddr != "" {
		if err := c.generatePrometheusConfig(args); err != nil {
			return err
		}
	}

	if c.TracingConfigJSON != "" {
		args.TracingConfigJSON = c.TracingConfigJSON
	}

	if c.StatsFlushInterval != "" {
		args.StatsFlushInterval = c.StatsFlushInterval
	}

	return nil
}

func GetParameters() (logToConsole bool, logID string, logLevel string, logFormat string, compressedTagsVersion claimsheader.CompressionType) {

	logLevel = os.Getenv(constants.EnvLogLevel)
	if logLevel == "" {
		logLevel = "info"
	}

	logFormat = os.Getenv(constants.EnvLogFormat)
	if logLevel == "" {
		logFormat = "json"
	}

	if console := os.Getenv(constants.EnvLogToConsole); console == constants.EnvLogToConsoleEnable {
		logToConsole = true
	}

	logID = os.Getenv(constants.EnvLogID)

	compressedTagsVersion = claimsheader.CompressionTypeNone
	if console := os.Getenv(constants.EnvCompressedTags); console != string(claimsheader.CompressionTypeNone) {
		if console == string(claimsheader.CompressionTypeV1) {
			compressedTagsVersion = claimsheader.CompressionTypeV1
		} else if console == string(claimsheader.CompressionTypeV2) {
			compressedTagsVersion = claimsheader.CompressionTypeV2
		}
	}

	return
}

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


Question:
Fetch target entity or entities.

@param Entity $entity
@return mixed

public function solveFetch(Entity &$entity)
    {
        // We need to find all target entities with the ID defined in the current entity source column
        $column = $this->relation->join->column;

        $value = $entity->{$column};
        $where = array($this->relation->join->targetColumn => $value);

        $query = EntityManager::find($this->relation->targetEntity);
        return $query->where($where)->all();
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question:
>>> diff_info([5,5,10,10,5,5,10,10])
    (0, 15)
    >>> diff_info([5,10,10,5,5,10,10,5])
    (15, 0)

def diff_info(data):

    def get_diff(l):
        diff = 0
        for no1, no2 in iter_steps(l, steps=2):
            diff += abs(no1 - no2)
        return diff

    data1 = data[2:]
    diff1 = get_diff(data1)

    data2 = data[1:-1]
    diff2 = get_diff(data2)

    return diff1, diff2

def main(args=None):
    """"""

    if args is None:
        parser = get_argument_parser()
        args = parser.parse_args()

    input_file = args.annotation_file
    output_file = args.output_file
    species = args.species
    chrom_pat = args.chromosome_pattern
    field_name = args.field_name

    log_file = args.log_file
    quiet = args.quiet
    verbose = args.verbose

    # configure root logger
    log_stream = sys.stdout
    if output_file == '-':
        # if we print output to stdout, redirect log messages to stderr
        log_stream = sys.stderr

    logger = misc.get_logger(log_stream = log_stream, log_file = log_file,
            quiet = quiet, verbose = verbose)

    if chrom_pat is None:
        chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species])
    else:
        chrom_pat = re.compile(chrom_pat)

    logger.info('Regular expression used for filtering chromosome names: "%s"',
            chrom_pat.pattern)

    chromosomes = set()
    excluded_chromosomes = set()
    i = 0
    exons = 0
    logger.info('Parsing data...')
    if input_file == '-':
        input_file = None
    with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
            misc.smart_open_write(output_file) as ofh:
        #if i >= 500000: break
        reader = csv.reader(fh, dialect = 'excel-tab')
        writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
                quoting = csv.QUOTE_NONE , quotechar = '|')
        for l in reader:
            i += 1
            #if i % int(1e5) == 0:
            #   print '\r%d...' %(i), ; sys.stdout.flush() # report progress
            if len(l) > 1 and l[2] == field_name:
                attr = parse_attributes(l[8])
                type_ = attr['gene_biotype']
                if type_ in ['protein_coding','polymorphic_pseudogene']:

                    # test whether chromosome is valid
                    chrom = l[0]
                    m = chrom_pat.match(chrom)
                    if m is None:
                        excluded_chromosomes.add(chrom)
                        continue

                    chromosomes.add(chrom)
                    writer.writerow(l)
                    exons += 1

    logger.info('Done! (Parsed %d lines.)', i)

    logger.info('')
    logger.info('Gene chromosomes (%d):', len(chromosomes))
    logger.info('\t' + ', '.join(sorted(chromosomes)))
    logger.info('')
    logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
    logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
    logger.info('')
    logger.info('Total no. of exons: %d' %(exons))

    return 0

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


Question:
Compile a template.

@param string $fileName Template to compile.

protected function compileTemplate($fileName)
    {
        try {
            $this->
                twigView->
                getTwig()->
                loadTemplate($fileName);
            $this->out('<success>' . $fileName . '</success>');
        } catch (\Exception $exception) {
            $this->out('<error>' . $fileName . '</error>');
            $this->out('<error>' . $exception->getMessage() . '</error>');
        }
    }

private function getJobs()
    {
        if ($this->hasParameter('profile')) {
            $this->fetchJobs($this->getParameter('profile'));

            return;
        }

        $this->buildJobs([$this->getParameter('job')]);
    }

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


Question:
// extractBlockMatches fetches the target block from the network, and filters
// out any relevant transactions found within the block.

func extractBlockMatches(chain ChainSource, ro *rescanOptions,
	curStamp *waddrmgr.BlockStamp) ([]*btcutil.Tx, error) {

	// We've matched. Now we actually get the block and cycle through the
	// transactions to see which ones are relevant.
	block, err := chain.GetBlock(curStamp.Hash, ro.queryOptions...)
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, fmt.Errorf("Couldn't get block %d (%s) from "+
			"network", curStamp.Height, curStamp.Hash)
	}

	blockHeader := block.MsgBlock().Header
	blockDetails := btcjson.BlockDetails{
		Height: block.Height(),
		Hash:   block.Hash().String(),
		Time:   blockHeader.Timestamp.Unix(),
	}

	relevantTxs := make([]*btcutil.Tx, 0, len(block.Transactions()))
	for txIdx, tx := range block.Transactions() {
		txDetails := blockDetails
		txDetails.Index = txIdx

		var relevant bool

		if ro.spendsWatchedInput(tx) {
			relevant = true
			if ro.ntfn.OnRedeemingTx != nil {
				ro.ntfn.OnRedeemingTx(tx, &txDetails)
			}
		}

		// Even though the transaction may already be known as relevant
		// and there might not be a notification callback, we need to
		// call paysWatchedAddr anyway as it updates the rescan
		// options.
		pays, err := ro.paysWatchedAddr(tx)
		if err != nil {
			return nil, err
		}

		if pays {
			relevant = true
			if ro.ntfn.OnRecvTx != nil {
				ro.ntfn.OnRecvTx(tx, &txDetails)
			}
		}

		if relevant {
			relevantTxs = append(relevantTxs, tx)
		}
	}

	return relevantTxs, nil
}

def _process_touch_batch(self):
        ''''''
        if not self._touch_batch:
            return

        _time = self._temp_status_time
        changed = False

        for (_time, _device, _type, _code, _value) in self._touch_batch:
            if _code == 'ABS_MT_TRACKING_ID':
                if _value == 0xffffffff:
                    self._temp_status[self._curr_slot] = -INF
                    changed = True
                else:
                    pass
            elif _code == 'ABS_MT_SLOT':
                self._curr_slot = _value
            else:
                if _code == 'ABS_MT_POSITION_X':
                    self._temp_status[self._curr_slot,_X] = _value
                    changed = True
                elif _code == 'ABS_MT_POSITION_Y':
                    self._temp_status[self._curr_slot,_Y] = _value
                    changed = True
                elif _code == 'ABS_MT_PRESSURE':
                    self._temp_status[self._curr_slot,_PR] = _value
                elif _code == 'ABS_MT_TOUCH_MAJOR':
                    self._temp_status[self._curr_slot,_MJ] = _value
                else:
                    print 'Unknown code', _code

        self._temp_status_time = _time
        self._touch_batch = []
        if not changed:
            return

        # check differences, if position changes are big enough then emit events
        diff = self._temp_status - self._status
        dt = self._temp_status_time - self._status_time
        emitted = False
        for i in range(SLOT_NUM):
            arr = self._temp_status[i]
            oldarr = self._status[i]
            dx, dy = diff[i,_X], diff[i,_Y]
            if dx > INF or dy > INF:
                # touch begin
                event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
                self.emit_touch_event(event)
                emitted = True
            elif dx < -INF or dy < -INF:
                # touch end
                event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
                self.emit_touch_event(event)
                emitted = True
            else:
                r, a = radang(float(dx), float(dy))
                if r > self._move_radius:
                    v = r / dt
                    event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
                    self.emit_touch_event(event)
                    emitted = True

        if not emitted:
            return
        self._status = self._temp_status.copy()
        self._status_time = self._temp_status_time

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


Question:
// InterpretMessageRange creates a SequenceRange from the given string in the
// IMAP format.

func InterpretMessageRange(imapMessageRange string) (seqRange SequenceRange, err error) {
	result := rangeRegexp.FindStringSubmatch(imapMessageRange)
	if len(result) == 0 {
		return SequenceRange{}, errInvalidRangeString(imapMessageRange)
	}

	first := SequenceNumber(result[1])
	second := SequenceNumber(result[2])

	// Reduce *:* to *
	if first.Last() && second.Last() {
		return SequenceRange{Min: SequenceNumber("*"), Max: SequenceNumber("")}, nil
	}

	// Ensure "*" is always placed in 'Max'
	if first.Last() && !second.Nil() {
		return SequenceRange{Min: second, Max: first}, nil
	}

	// If both sequence numbers are integer values, we need to sort them
	if first.IsValue() && second.IsValue() {
		firstVal, _ := first.Value()
		secondVal, _ := second.Value()
		if firstVal > secondVal {
			return SequenceRange{Min: second, Max: first}, nil
		}
	}

	return SequenceRange{Min: first, Max: second}, nil
}

protected function initQueue($ipc_filename, $msg_type)
    {
        $this->key_t = $this->getIpcKey($ipc_filename, $msg_type);
        $this->queue = \msg_get_queue($this->key_t);
        if (!$this->queue) throw new \RuntimeException('msg_get_queue failed');
    }

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


Question:
@return $this|null

This method must be called in conditionally chainable methods.

public function validateMethodCall()
    {
        if (-1 !== $this->currentElement && (in_array(false, $this->conditionStack, true) || in_array(2, $this->conditionStack, true))) {
            return $this;
        }

        return;
    }

public function getNullableFields(Table $table)
    {
        return $table->getFields()->filter(function (Field $field) {
            return $field->isNullable();
        });
    }

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


Question: // syncRequest takes a reviewRequest and determines if it should update the caches supplied, it is not thread-safe

func (ac *AuthorizationCache) syncRequest(request *reviewRequest, userSubjectRecordStore cache.Store, groupSubjectRecordStore cache.Store, reviewRecordStore cache.Store) error {

	lastKnownValue, err := lastKnown(reviewRecordStore, request.namespace)
	if err != nil {
		return err
	}

	if skipReview(request, lastKnownValue) {
		return nil
	}

	namespace := request.namespace
	review, err := ac.reviewer.Review(namespace)
	if err != nil {
		return err
	}

	usersToRemove := sets.NewString()
	groupsToRemove := sets.NewString()
	if lastKnownValue != nil {
		usersToRemove.Insert(lastKnownValue.users...)
		usersToRemove.Delete(review.Users()...)
		groupsToRemove.Insert(lastKnownValue.groups...)
		groupsToRemove.Delete(review.Groups()...)
	}

	deleteNamespaceFromSubjects(userSubjectRecordStore, usersToRemove.List(), namespace)
	deleteNamespaceFromSubjects(groupSubjectRecordStore, groupsToRemove.List(), namespace)
	addSubjectsToNamespace(userSubjectRecordStore, review.Users(), namespace)
	addSubjectsToNamespace(groupSubjectRecordStore, review.Groups(), namespace)
	cacheReviewRecord(request, lastKnownValue, review, reviewRecordStore)
	ac.notifyWatchers(namespace, lastKnownValue, sets.NewString(review.Users()...), sets.NewString(review.Groups()...))

	if errMsg := review.EvaluationError(); len(errMsg) > 0 {
		klog.V(5).Info(errMsg)
	}
	return nil
}

def _flush(self):

        # Upload segment with workers
        name = self._segment_name % self._seek
        response = self._workers.submit(
            self._client.put_object, self._container, name,
            self._get_buffer())

        # Save segment information in manifest
        self._write_futures.append(dict(
            etag=response, path='/'.join((self._container, name))))

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


Question:
Execute the python code and returns the global dict.
        kwargs can contain extra dependencies that get only used
        at compile time.

def compile(self, **kwargs):

        code = compile(str(self), "<string>", "exec")
        global_dict = dict(self._deps)
        global_dict.update(kwargs)
        _compat.exec_(code, global_dict)
        return global_dict

def kitchen_config(backend, kitchen, add, get, unset, listall):

    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))

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


Question:
Updates app.<p>
@param role to be set

protected void updateApp(CmsRole role) {

        m_app.update(m_parentOU, CmsOuTreeType.ROLE, role.getId(), "");
    }

func (up UnitPayloads) SetStatus(name, status string) error {
	if err := payload.ValidateState(status); err != nil {
		return errors.Trace(err)
	}

	change := payloadSetStatusChange{
		Unit:   up.unit,
		Name:   name,
		Status: status,
	}
	if err := Apply(up.db, change); err != nil {
		return errors.Trace(err)
	}
	return nil
}

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


Question: Return first document from :meth:`query`, with same parameters.

def query_one(self, *args, **kwargs):

        for r in self.query(*args, **kwargs):
            return r
        return None

public function createPersonalSiteEnque(){
        $qry = new InvokePostMethodQuery(
            $this->getResourcePath(),
            "createpersonalsiteenque",
            array(false)
        );
        $this->getContext()->addQuery($qry);
    }

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


Question: Get the error messages.

private function getErrorMessage()
    {
        $directivesMessage = '';
        $domainsMessage = '';

        if (!empty($this->invalidValues['directives'])) {
            $directivesMessage = "The following directives are invalid:\n- ";
            $directivesMessage .= implode("\n- ", $this->invalidValues['directives']);
        }

        if (!empty($this->invalidValues['domain'])) {
            $domainsMessage = "The following domains are invalid:\n- ";
            $domainsMessage .= implode("\n- ", $this->invalidValues['domain']);
        }

        return $domainsMessage . "\n" . $directivesMessage;
    }

func (e ServerErrorBlockNonExistent) ToStatus() (s keybase1.Status) {
	s.Code = StatusCodeServerErrorBlockNonExistent
	s.Name = "BLOCK_NONEXISTENT"
	s.Desc = e.Msg
	return
}

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


Question:
Try to convert to plaintext

@param   string  $source
@return  string  Plaintext string

protected function _decode($source)
    {
        // entity decode
        $trans_tbl = get_html_translation_table(HTML_ENTITIES);
        foreach ($trans_tbl as $k => $v) {
            $ttr[$v] = utf8_encode($k);
        }
        $source = strtr($source, $ttr);

        // convert decimal
        //$source = preg_replace('/&#(\d+);/me', "chr(\\1)", $source); // decimal notation
        $source = preg_replace_callback(
                       '/&#(\d+);/m',
                       function ($m) {
                           return chr($m[1]);
                       },
                       $source
        );

        // convert hex
        //$source = preg_replace('/&#x([a-f0-9]+);/mei', "chr(0x\\1)", $source); // hex notation

        $source = preg_replace_callback(
                       '/&#x([a-f0-9]+);/mi',
                       function ($m) {
                           return chr('0x'.$m[1]);
                       },
                       $source
        );

        return $source;
    }

def step_it_should_fail_with(context):
    '''

    '''
    assert context.text is not None, "ENSURE: multiline text is provided."
    step_command_output_should_contain(context)
    assert_that(context.command_result.returncode, is_not(equal_to(0)))

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


Question: // HandleMeasures satisfies the Handler interface.

func (b *Buffer) HandleMeasures(time time.Time, measures ...Measure) {
	if len(measures) == 0 {
		return
	}

	size := b.bufferSize()
	b.prepare(size)

	buffer := b.acquireBuffer()
	length := buffer.len()
	buffer.append(b.Serializer, time, measures...)

	if buffer.len() >= size {
		if length == 0 {
			// When there were no data in the buffer prior to writing the set of
			// measures we unfortunately have to overflow the configured buffer
			// size, but the Serializer documentation mentions that this corner
			// case has to be handled.
			length = buffer.len()
		}
		buffer.flush(b.Serializer, length)
	}

	buffer.release()
}

Stream<String> writeMeter(Meter m) {
        List<Field> fields = new ArrayList<>();
        for (Measurement measurement : m.measure()) {
            double value = measurement.getValue();
            if (!Double.isFinite(value)) {
                continue;
            }
            String fieldKey = measurement.getStatistic().getTagValueRepresentation()
                    .replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase();
            fields.add(new Field(fieldKey, value));
        }
        if (fields.isEmpty()) {
            return Stream.empty();
        }
        return Stream.of(influxLineProtocol(m.getId(), "unknown", fields.stream()));
    }

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


Question:
Add limit
I.E.

@param  int  $limit
@param  int  $offset
@return self

public function limit($limit, $offset = null)
    {
        if ($offset) {
            $this->getLimit()->setParams(array($limit, $offset));
        } else {
            $this->getLimit()->setParams(array($limit));
        }

        return $this;
    }

def keys(options = { })
      if options.include? :range
        warn "range supersedes prefix" if options[:prefix]
        range = options[:range]
        unless range.respond_to?(:first) and range.respond_to?(:last)
          fail ArgumentError, "Range or two element Array expected"
        end
        start          = cast_key_in(range.first)
        include_start  = !options.fetch(:exclude_start, false)
        finish         = cast_key_in(range.last)
        include_finish = !( range.respond_to?(:exclude_end?) ?
                            range.exclude_end?               :
                            options.fetch(:exclude_end, false) )
      else
        fail ArgumentError, "prefix not supported" if options[:prefix]
        start          = cast_key_in(:min)
        include_start  = true
        finish         = cast_key_in(:max)
        include_finish = true
      end
      limit = options.fetch(:limit, -1)
      Utilities.temp_int do |count|
        begin
          list  = lib.range(@db, start, finish, limit, count)
          array = list.get_array_of_uint64(0, count.get_int(0))
          array.shift if array.first == start  and not include_start
          array.pop   if array.last  == finish and not include_finish
          array  # cast not needed:  already Integer
        ensure
          Utilities.free(list) if list
        end
      end
    end

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


Question:
seeks to the provided offset of the stream.

@param int $offset
@throws StreamException when the stream is not longer available.
@throws StreamException when the stream position can not be reached.
@return StreamInterface

public function seek(int $offset): StreamInterface
    {
        if ( ! is_resource($this->stream) ) {
            throw new StreamException('Stream is not longer available');
        }

        if ( ! $this->seekable ) {
            throw new StreamException('Stream is not seekable');
        }

        $position = fseek($this->stream, $offset, SEEK_SET);

        if ( $position === -1 ) {
            throw new StreamException('Unable to seek to stream position');
        }

        return $this;
    }

def put_stream(self, rel_path, metadata=None, cb=None):

        from io import IOBase

        if not isinstance(rel_path, basestring):
            rel_path = rel_path.cache_key

        repo_path = os.path.join(self.cache_dir, rel_path.strip("/"))

        if not os.path.isdir(os.path.dirname(repo_path)):
            os.makedirs(os.path.dirname(repo_path))

        if os.path.exists(repo_path):
            os.remove(repo_path)

        sink = open(repo_path, 'wb')

        upstream = self.upstream

        class flo(IOBase):

            '''This File-Like-Object class ensures that the file is also
            sent to the upstream after it is stored in the FSCache. '''

            def __init__(self, sink, upstream, repo_path, rel_path):

                self._sink = sink
                self._upstream = upstream
                self._repo_path = repo_path
                self._rel_path = rel_path

            @property
            def rel_path(self):
                return self._rel_path

            def write(self, str_):
                self._sink.write(str_)

            def close(self):
                if not self._sink.closed:
                    # print "Closing put_stream.flo {}
                    # is_closed={}!".format(self._repo_path, self._sink.closed)

                    self._sink.close()

                    if self._upstream and not self._upstream.readonly and not self._upstream.usreadonly:
                        self._upstream.put(
                            self._repo_path,
                            self._rel_path,
                            metadata=metadata)

            def __enter__(self): # Can be used as a context!
                return self

            def __exit__(self, type_, value, traceback):
                if type_:
                    return False

                self.close()

        self.put_metadata(rel_path, metadata)

        return flo(sink, upstream, repo_path, rel_path)

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


Question:
Taken from Mink\BrowserKitDriver

@param Response $response

@return \Symfony\Component\BrowserKit\Response

protected function createResponse(Response $response)
    {
        $contentType = $response->getHeader('Content-Type');

        if (!$contentType) {
            $contentType = 'text/html';
        }

        if (strpos($contentType, 'charset=') === false) {
            $body = $response->getBody(true);
            if (preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9]+)/i', $body, $matches)) {
                $contentType .= ';charset=' . $matches[1];
            }
            $response->setHeader('Content-Type', $contentType);
        }

        $headers = $response->getHeaders();
        $status = $response->getStatusCode();
        if ($status < 300 || $status >= 400) {
            $matches = [];

            $matchesMeta = preg_match(
                '/\<meta[^\>]+http-equiv="refresh" content="\s*(\d*)\s*;\s*url=(.*?)"/i',
                $response->getBody(true),
                $matches
            );

            if (!$matchesMeta) {
                // match by header
                preg_match(
                    '/^\s*(\d*)\s*;\s*url=(.*)/i',
                    (string)$response->getHeader('Refresh'),
                    $matches
                );
            }

            if ((!empty($matches)) && (empty($matches[1]) || $matches[1] < $this->refreshMaxInterval)) {
                $uri = $this->getAbsoluteUri($matches[2]);
                $partsUri = parse_url($uri);
                $partsCur = parse_url($this->getHistory()->current()->getUri());
                foreach ($partsCur as $key => $part) {
                    if ($key === 'fragment') {
                        continue;
                    }
                    if (!isset($partsUri[$key]) || $partsUri[$key] !== $part) {
                        $status = 302;
                        $headers['Location'] = $matchesMeta ? htmlspecialchars_decode($uri) : $uri;
                        break;
                    }
                }
            }
        }

        return new BrowserKitResponse($response->getBody(), $status, $headers);
    }

def get_page(self, url, *args, **kwds):

        contextFactory = None
        scheme, host, port, path = parse(url)
        data = kwds.get('postdata', None)
        self._method = method = kwds.get('method', 'GET')
        self.request_headers = self._headers(kwds.get('headers', {}))
        if (self.body_producer is None) and (data is not None):
            self.body_producer = FileBodyProducer(StringIO(data))
        if self.endpoint.ssl_hostname_verification:
            contextFactory = None
        else:
            contextFactory = WebClientContextFactory()
        agent = _get_agent(scheme, host, self.reactor, contextFactory)
        if scheme == "https":
            self.client.url = url
        d = agent.request(method, url, self.request_headers, self.body_producer)
        d.addCallback(self._handle_response)
        return d

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


Question:
Return a human-readable string representation of this object.

        Kwargs:
            indent (int): The amount of spaces to use as indentation.

def pretty_str(self, indent=0):

        indent = ' ' * indent
        if self.value is not None:
            return '{}{} {}'.format(indent, self.name, pretty_str(self.value))
        return indent + self.name

def health_indicator(self, health_indicator):

        allowed_values = ["ok", "warning", "error"]
        if health_indicator not in allowed_values:
            raise ValueError(
                "Invalid value for `health_indicator` ({0}), must be one of {1}"
                .format(health_indicator, allowed_values)
            )

        self._health_indicator = health_indicator

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


Question:
get electricity info

            :param apart_id: 栋数
            :param meter_room: 宿舍号

def get_electricity_info(self, apart_id, meter_room):

        apart_id = str(apart_id)
        meter_room = str(meter_room)
        try:
            content = LifeService._get_electricity_info_html(apart_id, meter_room)
        except KeyError as e:
            _.d(e.message)
            result = {
                'response': None
            }
            return _.to_json_string(result)
        soup = BeautifulSoup(content)
        tags = soup.find_all(name='span', class_='STYLE7')
        result = {
            'response': {
                'apart': _.trim(tags[0].string),
                'apart_id': _.trim(tags[1].string),
                'used': _.trim(tags[2].string),
                'left': _.trim(tags[3].string),
                'update_time': _.trim(tags[4].string)
            }
        }
        return _.to_json_string(result)

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question:
Write data to socket

@param   string  $cmd
@param   boolean $result     Need result/response
@return  mixed

protected function writeSocket($cmd, $result = false)
    {
        if (is_null($this->socket)) {
            return false;
        }

        fwrite($this->socket, $cmd . "\r\n");

        if (true == $result) {
            return $this->readSocket();
        }

        return true;
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end

      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end

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


Question:
Resize image to all configured sizes
@param $pathToImage

public function resize($pathToImage)
    {
        $file = $this->storage->get($pathToImage);

        $this->sizes->each(function ($size, $key) use ($pathToImage, $file) {
            $img = app(ImageManager::class)->make($file);
            $path = $this->createThumbPath($pathToImage, $key);

            switch ($size[2]) {
                case 'width':
                    // resize the image to a width of $sizes[ 0 ] and constrain aspect ratio (auto height)
                    $img->resize($size[0], null, function ($constraint) {
                        $constraint->aspectRatio();
                    });
                    break;
                case 'height':
                    // resize the image to a height of $sizes[ 1 ] and constrain aspect ratio (auto width)
                    $img->resize(null, $size[1], function ($constraint) {
                        $constraint->aspectRatio();
                    });
                    break;
                // 'resize' or any other fullbacks to this
                default:
                    $img->fit($size[0], $size[1]);
                    break;
            }

            $this->storage->put($path, $img->stream()->__toString());
        });
    }

public function setFiles(array $files)
    {
        foreach ($files as $file) {
            if (is_file($file)) {
                $file = new SplFileInfo($file, $file, $file);
            }

            if (!($file instanceof SplFileInfo)) {
                throw new InvalidArgumentException("File $file not exists.");
            }

            $this->files[$file->getRealPath()] = $file;
        }

        return $this;
    }

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


Question: // Get gets a value by key in the current or parent context

func (c *Context) Get(key interface{}) interface{} {
	store := c.getStore()
	if store == nil {
		return store
	}
	if value, ok := store[key]; ok {
		return value
	}
	if c.Parent != nil {
		return c.Parent.Get(key)
	}
	return nil
}

func (e *Bootstrap) signedUp(m libkb.MetaContext) bool {
	cr := m.G().Env.GetConfig()
	if cr == nil {
		return false
	}
	if uid := cr.GetUID(); uid.Exists() {
		return true
	}
	return false
}

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


Question: end checkState  ## CHANGESTATE ## Modifies the private variable my.state. Used in async.chain which takes a callback with single error argument.

function changeState ( item, type, cb) {
    var i
    switch (type) {
    case 'add':
      my.state.trackedfiles[item] = true;
      break
    case 'rm':
      for (i in my.state.trackedfiles) {
        if (path.basename(i) === path.basename(item)) {
          delete my.state.trackedfiles[i];
        }
      }
      break
    default:
      throw new Error('Wrong arguments for function changeState')
    }
    return cb(null)
  }

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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


Question: Provide a Site filter

public function updateSearchForm($form){
		if($this->modelIsMultiSitesAware()) {
			$managedSites = Multisites::inst()->sitesManagedByMember();

			$source = Site::get()->filter('ID', Multisites::inst()->sitesManagedByMember())->map('ID', 'Title')->toArray();
			$plural = singleton($this->owner->modelClass)->plural_name();
			if(count($source)){
				$activeSite = $this->getActiveSite();
				$form->Fields()->push(DropdownField::create(
					'SiteID',
					"Site: ",
					$source,
					$activeSite ? $activeSite->ID : null
				));
			}
		}
	}

public static boolean arrayFilter(String type) {

        int lastIndex = type.lastIndexOf(ARRAY_PREFIX);
        if (lastIndex == -1) {
            return false;
        }

        String arrayType = type.substring(lastIndex + 1);

        return nameFilter(arrayType);
    }

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


Question: Mark this unit as having failed. May attempt a retry.

def fail(output, time_taken)
      tries = self.attempts + 1
      return try_again if tries < CloudCrowd.config[:work_unit_retries]
      update_attributes({
        :status         => FAILED,
        :node_record    => nil,
        :worker_pid     => nil,
        :attempts       => tries,
        :output         => output,
        :time           => time_taken
      })
      job && job.check_for_completion
    end

protected boolean trigger(List<InteractionListener> listeners, Type type, Throwable e) {
        if (listeners.isEmpty())
            return false;
        InteractionEvent event = createInteractionEvent(type, e);
        for (InteractionListener listener : listeners) {
            listener.onEvent(event);
        }
        if (event instanceof AfterFailInteractionEvent)
            return ((AfterFailInteractionEvent) event).isRetry();
        return false;
    }

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


Question:
Get value that will be stored to database

@return string

public function getDbValue()
    {
        $value = $this->getValue();
        if (is_null($value)) {
            // Process default value
            $value = $this->getDefaultValue();
            if ($this->isInstanceOf($value, AbstractEntity::class)) {
                if (!$value->exists()) {
                    $value->save();
                }

                $value = $value->id;
            }

            return $this->processToDbValue($value);
        }

        // Save if new or if updating is allowed
        if (!$value->exists() || $this->getUpdateExisting()) {
            $value->save();
        }

        return $this->processToDbValue($value->id);
    }

public void writeSuccessResult(int line) {
        logger.debug("Write Success result => line:{}", line);
        writeValue(resultColumnName, line, Messages.getMessage(Messages.SUCCESS_MESSAGE));
    }

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


Question:
增加嵌套插

@param boolQuery
@param where
@param subQuery

private void addSubQuery(BoolQueryBuilder boolQuery, Where where, QueryBuilder subQuery) {
        if(where instanceof Condition){
            Condition condition = (Condition) where;

			if (condition.isNested()) {
				boolean isNestedQuery = subQuery instanceof NestedQueryBuilder;
				InnerHitBuilder ihb = null;
				if (condition.getInnerHits() != null) {
                    try (JsonXContentParser parser = new JsonXContentParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, new JsonFactory().createParser(condition.getInnerHits()))) {
                        ihb = InnerHitBuilder.fromXContent(parser);
                    } catch (IOException e) {
                        throw new IllegalArgumentException("couldn't parse inner_hits: " + e.getMessage(), e);
                    }
                }

                // bugfix #628
                if ("missing".equalsIgnoreCase(String.valueOf(condition.getValue())) && (condition.getOpear() == Condition.OPEAR.IS || condition.getOpear() == Condition.OPEAR.EQ)) {
                    NestedQueryBuilder q = isNestedQuery ? (NestedQueryBuilder) subQuery : QueryBuilders.nestedQuery(condition.getNestedPath(), QueryBuilders.boolQuery().mustNot(subQuery), ScoreMode.None);
					if (ihb != null) {
						q.innerHit(ihb);
                    }
                    boolQuery.mustNot(q);
                    return;
                }

                if (!isNestedQuery) {
					subQuery = QueryBuilders.nestedQuery(condition.getNestedPath(), subQuery, ScoreMode.None);
				}
                if (ihb != null) {
                    ((NestedQueryBuilder) subQuery).innerHit(ihb);
                }
            } else if(condition.isChildren()) {
            	subQuery = JoinQueryBuilders.hasChildQuery(condition.getChildType(), subQuery, ScoreMode.None);
            }
        }

		//zhongshu-comment 将subQuery对象纳入到boolQuery中，即boolQuery是上一级，subQuery是下一级
		if (where.getConn() == CONN.AND) {
			boolQuery.must(subQuery);
		} else {
			boolQuery.should(subQuery);
		}
	}

public function buildUpdateSQL($table = null, $data = array())
	{
		$sql = 'update ' . $this->parseTable($table) . ' set ';
		if(is_string($data))
		{
			$sql .= $data . ' ';
		}
		else
		{
			$data = $this->parseParams($data);
			foreach($data as $key => $value)
			{
				$sql .= $this->parseKeyword($key) . '=:' . $this->parseParamName($key) . ',';
			}
		}
		$where = $this->parseCondition(isset($this->operationOption['where']) ? $this->operationOption['where'] : '');
		if ('' !== $where)
		{
			$where = 'where ' . $where . ' ';
		}
		return substr($sql,0,-1) . ' '
				. $where
				. $this->parseOrder()
				. $this->parseLimit()
				. $this->parseLock()
				;
	}

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


Question:
{@linkplain CrosstabBuilder#addRow(DJCrosstabRow)}
@param title
@param property
@param className
@param showTotal
@return

public CrosstabBuilder addRow(String title, String property, String className, boolean showTotal) {
		DJCrosstabRow row = new CrosstabRowBuilder()
			.setProperty(property,className)
			.setShowTotals(showTotal)
			.setTitle(title)
			.build();
		addRow(row);
		return this;
	}

func (rb *route) BuildColName(index int) (*sqlparser.ColName, error) {
	alias := rb.resultColumns[index].alias
	if alias.IsEmpty() {
		return nil, errors.New("cannot reference a complex expression")
	}
	for i, rc := range rb.resultColumns {
		if i == index {
			continue
		}
		if rc.alias.Equal(alias) {
			return nil, fmt.Errorf("ambiguous symbol reference: %v", alias)
		}
	}
	return &sqlparser.ColName{
		Metadata: rb.resultColumns[index].column,
		Name:     alias,
	}, nil
}

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


Question:
Adds a new operation to the Stream class.

@param  string $name
@param  string $signature
@param  callable $fn
@return void

public static function operation($name, $signatures, $fn = null)
    {
        if (! is_array($signatures)) {
            $signatures = [$signatures];
        }
        foreach ($signatures as $signature) {
            self::$operations[] = _stream_operation($name, $signature, $fn);
        }
    }

func (s *SigningProfile) SetSigningParameters(v map[string]*string) *SigningProfile {
	s.SigningParameters = v
	return s
}

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


Question:
// interpolationFuncIndex implements the "index" function that allows one to
// find the index of a specific element in a list

func interpolationFuncIndex() ast.Function {
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeList, ast.TypeString},
		ReturnType: ast.TypeInt,
		Callback: func(args []interface{}) (interface{}, error) {
			haystack := args[0].([]ast.Variable)
			needle := args[1].(string)
			for index, element := range haystack {
				if needle == element.Value {
					return index, nil
				}
			}
			return nil, fmt.Errorf("Could not find '%s' in '%s'", needle, haystack)
		},
	}
}

public static <IV, K, V> IV injectIntoIf(
            IV initialValue,
            Map<K, V> map,
            final Predicate<? super V> predicate,
            final Function2<? super IV, ? super V, ? extends IV> function)
    {
        Function2<IV, ? super V, IV> ifFunction = new Function2<IV, V, IV>()
        {
            public IV value(IV accumulator, V item)
            {
                if (predicate.accept(item))
                {
                    return function.value(accumulator, item);
                }
                return accumulator;
            }
        };
        return Iterate.injectInto(initialValue, map.values(), ifFunction);
    }

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


Question:
The list of clause indices in ``words`` layer.
        The indices are unique only in the boundary of a single sentence.

def clause_indices(self):

        if not self.is_tagged(CLAUSE_ANNOTATION):
            self.tag_clause_annotations()
        return [word.get(CLAUSE_IDX, None) for word in self[WORDS]]

def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ):

    subdomain_index = server_state['subdomains']
    atlas_state = server_state['atlas']

    # make this usable even if we haven't explicitly configured virtualchain
    impl = sys.modules[__name__]
    log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))

    # NOTE: this is the only place where a read-write handle should be created,
    # since this is the only place where the db should be modified.
    new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)

    # propagate runtime state to virtualchain callbacks
    new_db.subdomain_index = subdomain_index
    new_db.atlas_state = atlas_state

    rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)

    BlockstackDB.release_readwrite_instance(new_db, last_block)

    return rc

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


Question: Get a secret from Custodia

def getsecret(self, section, option, **kwargs):

        # keyword-only arguments, vars and fallback are directly passed through
        raw = kwargs.get('raw', False)
        value = self.get(section, option, **kwargs)
        if raw:
            return value
        return self.custodia_client.get_secret(value)

public function conceal($org, $user)
	{
		// Build the request path.
		$path = '/orgs/' . $org . '/public_members/' . $user;

		return $this->processResponse(
			$this->client->delete($this->fetchUrl($path)),
			204
		);
	}

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


Question: Marshall the given parameter object.

public void marshall(GetGroupVersionRequest getGroupVersionRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getGroupVersionRequest.getGroupId(), GROUPID_BINDING);
            protocolMarshaller.marshall(getGroupVersionRequest.getGroupVersionId(), GROUPVERSIONID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Send data row to the next destinations

@param array $data An associate array epresenting a row of data

@return null

public function next($data)
    {
        if ($this->destinations!=null) {
            foreach ($this->destinations as $node) {
                $node->input($data, $this);
            }
        }
    }

protected function detail_pair($key, $value, $class ='') {
        $html = html_writer::start_div('detail-pair row yui3-g '.preg_replace('#[^a-zA-Z0-9_\-]#', '-', $class));
        $html .= html_writer::div(html_writer::span($key), 'pair-key col-md-3 yui3-u-1-4 font-weight-bold');
        $html .= html_writer::div(html_writer::span($value), 'pair-value col-md-8 yui3-u-3-4');
        $html .= html_writer::end_div();
        return $html;
    }

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


Question:
getter for physicalContact - gets yes, no, unknown
@generated
@return value of the feature

public String getPhysicalContact() {
    if (RegulationOfGeneExpression_Type.featOkTst && ((RegulationOfGeneExpression_Type)jcasType).casFeat_physicalContact == null)
      jcasType.jcas.throwFeatMissing("physicalContact", "de.julielab.jules.types.bootstrep.RegulationOfGeneExpression");
    return jcasType.ll_cas.ll_getStringValue(addr, ((RegulationOfGeneExpression_Type)jcasType).casFeatCode_physicalContact);}

public function run()
    {
        $this->extractInteractions();

        $this->data = $line = [];

        foreach ($this->interactions as $interaction) {
            foreach ($this->columns as $column => $config) {
                if (isset($config['callback'])
                    && method_exists($this, $config['callback']))
                {
                    $params = [];
                    if (isset($config['callbackParameters'])) {
                        $params = $config['callbackParameters'];
                    }
                    $functionCall = $config['callback'];
                    $callbackValue = call_user_func(array($this, $functionCall), $interaction, $params);
                    if (isset($config['valuesAsColumns'])) {
                        $line[$interaction['id']] = array_merge($line[$interaction['id']], $callbackValue);
                    } else {
                        $line[$interaction['id']][$column] = $callbackValue;
                    }
                }
            }
        }
        $this->data = $line;
        $this->columns = $this->interactions = [];
        return $this;
    }

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


Question:
Get y

If no "y" value has been set, this method will
set and return a default "y" value,
if any such value is available

@see getDefaultY()

@return int|null y or null if no y has been set

public function getY() : ?int
    {
        if ( ! $this->hasY()) {
            $this->setY($this->getDefaultY());
        }
        return $this->y;
    }

protected void setValue(int newPosition, T1[] values, int number,
      boolean currentExisting) {
    if (number > 0) {
      T1 valueSum = null;
      T2 valueSumOfLogs = null;
      T1 valueSumOfSquares = null;
      T1 valueMin = null;
      T1 valueMax = null;
      for (int i = 0; i < number; i++) {
        valueSum = (i == 0) ? values[i] : operations.add11(valueSum, values[i]);
        valueSumOfLogs = (i == 0) ? operations.log1(values[i])
            : operations.add22(valueSumOfLogs, operations.log1(values[i]));
        valueSumOfSquares = (i == 0)
            ? operations.product11(values[i], values[i])
            : operations.add11(valueSumOfSquares,
                operations.product11(values[i], values[i]));
        valueMin = (i == 0) ? values[i] : operations.min11(valueMin, values[i]);
        valueMax = (i == 0) ? values[i] : operations.max11(valueMax, values[i]);
      }
      setValue(newPosition, valueSum, valueSumOfLogs, valueSumOfSquares,
          valueMin, valueMax, number, currentExisting);
    }
  }

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


Question:
// ParsePrevResult parses a prevResult in a NetConf structure and sets
// the NetConf's PrevResult member to the parsed Result object.

func ParsePrevResult(conf *types.NetConf) error {
	if conf.RawPrevResult == nil {
		return nil
	}

	resultBytes, err := json.Marshal(conf.RawPrevResult)
	if err != nil {
		return fmt.Errorf("could not serialize prevResult: %v", err)
	}

	conf.RawPrevResult = nil
	conf.PrevResult, err = NewResult(conf.CNIVersion, resultBytes)
	if err != nil {
		return fmt.Errorf("could not parse prevResult: %v", err)
	}

	return nil
}

def get_account_history_page(address, page, hostport=None, proxy=None):

    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    page_schema = {
        'type': 'object',
        'properties': {
            'history': {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': ACCOUNT_SCHEMA_PROPERTIES,
                    'required': ACCOUNT_SCHEMA_REQUIRED,
                },
            },
        },
        'required': [
            'history'
        ],
    }

    schema = json_response_schema(page_schema)

    try:
        resp = proxy.get_account_history(address, page)
        resp = json_validate(schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    return resp['history']

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


Question:
Open, parse, and return the template file.
@param string $file the template file name
@return string

public function fetch($file)
    {
        $templateFile = $this->findTemplateFile($file);

        if (empty($templateFile)) {
            throw new Exception("Template file does not exists: $file");
        }

        extract($this->vars);
        ob_start();
        include $templateFile;
        $buffer = ob_get_contents();
        ob_end_clean();
        return $buffer;
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
Dispatch Request to controller or method.

@throw  Exception
@param  array                $route
@param  Friday\Http\Request  $request
@return void

public function dispatch($route, $request)
    {
        $request->setParam('Closure', $route[4]);

        if(isset($route[3]) && is_string($route[3])) {
            $view = $route[3];
            $data = $route[4];
            return ['view' => [$view, $data]];
        }
        elseif(isset($route[2]) && is_string($route[2])) {
            list($controller, $method) = explode('@', $route[2]);
            return ['controller' => [$controller, $method]];
        }
        elseif(isset($route[2]) && ($route[2] instanceof Closure || get_class($route[2]) === "Closure")) {
            $function = $route[2];
            $reflectionFunction = new ReflectionFunction($function);
            $numReqParam = $reflectionFunction->getNumberOfRequiredParameters();
            if($numReqParam > count($request->getParam('Closure'))) {
                throw new Exception('Invaliding number of required parameter passed in route\'s callable function: '.$route[1]);
            }
            ob_start();
            if($request->getParam('Closure') !== false && is_array($request->getParam('Closure')) ) {
                $return = call_user_func_array($route[2], $request->getParam('Closure'));
            }
            else {
                //$function();
                throw new Exception('Invaliding parameter passed in route\'s callable function: '.$route[1]);
            }
            $output = ob_get_clean();
            return ['output' => [$output, $return]];
        }
        else {
            throw new Exception('Invaliding route is registered for: '.$route[1]);
        }
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question: // CreateUnderlay creates a new child Underlay under the Me

func (o *Me) CreateUnderlay(child *Underlay) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

public function addSubfield (\HAB\Pica\Record\Subfield $subfield)
    {
        if (in_array($subfield, $this->getSubfields(), true)) {
            throw new InvalidArgumentException("Cannot add subfield: Subfield already part of the subfield list");
        }
        $this->_subfields []= $subfield;
    }

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


Question:
// Delete removes a certificate data from the cache under the specified key.
// If there's no such key in the cache, Delete returns nil.

func (ng *etcdv2AutoCertCache) Delete(ctx context.Context, rawKey string) error {
	key := ng.normalized(rawKey)
	_, err := ng.kapi.Delete(ctx, key, &etcd.DeleteOptions{})
	return err
}

func NewDashboardHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, userService platform.UserService) *DashboardHandler {
	h := &DashboardHandler{
		Router:                     NewRouter(),
		Logger:                     zap.NewNop(),
		UserResourceMappingService: mappingService,
		LabelService:               labelService,
		UserService:                userService,
	}

	h.HandlerFunc("POST", dashboardsPath, h.handlePostDashboard)
	h.HandlerFunc("GET", dashboardsPath, h.handleGetDashboards)
	h.HandlerFunc("GET", dashboardsIDPath, h.handleGetDashboard)
	h.HandlerFunc("GET", dashboardsIDLogPath, h.handleGetDashboardLog)
	h.HandlerFunc("DELETE", dashboardsIDPath, h.handleDeleteDashboard)
	h.HandlerFunc("PATCH", dashboardsIDPath, h.handlePatchDashboard)

	h.HandlerFunc("PUT", dashboardsIDCellsPath, h.handlePutDashboardCells)
	h.HandlerFunc("POST", dashboardsIDCellsPath, h.handlePostDashboardCell)
	h.HandlerFunc("DELETE", dashboardsIDCellsIDPath, h.handleDeleteDashboardCell)
	h.HandlerFunc("PATCH", dashboardsIDCellsIDPath, h.handlePatchDashboardCell)

	h.HandlerFunc("GET", dashboardsIDCellsIDViewPath, h.handleGetDashboardCellView)
	h.HandlerFunc("PATCH", dashboardsIDCellsIDViewPath, h.handlePatchDashboardCellView)

	h.HandlerFunc("POST", dashboardsIDMembersPath, newPostMemberHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Member))
	h.HandlerFunc("GET", dashboardsIDMembersPath, newGetMembersHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Member))
	h.HandlerFunc("DELETE", dashboardsIDMembersIDPath, newDeleteMemberHandler(h.UserResourceMappingService, platform.Member))

	h.HandlerFunc("POST", dashboardsIDOwnersPath, newPostMemberHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Owner))
	h.HandlerFunc("GET", dashboardsIDOwnersPath, newGetMembersHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Owner))
	h.HandlerFunc("DELETE", dashboardsIDOwnersIDPath, newDeleteMemberHandler(h.UserResourceMappingService, platform.Owner))

	h.HandlerFunc("GET", dashboardsIDLabelsPath, newGetLabelsHandler(h.LabelService))
	h.HandlerFunc("POST", dashboardsIDLabelsPath, newPostLabelHandler(h.LabelService))
	h.HandlerFunc("DELETE", dashboardsIDLabelsNamePath, newDeleteLabelHandler(h.LabelService))
	h.HandlerFunc("PATCH", dashboardsIDLabelsNamePath, newPatchLabelHandler(h.LabelService))

	return h
}

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