anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
GetComponentOk returns a tuple with the Component field value if set, nil otherwise and a boolean to check if the value has been set. | func (o *ReportingTaskEntity) GetComponentOk() (*ReportingTaskDTO, bool) {
if o == nil || o.Component == nil {
return nil, false
}
return o.Component, true
} |
GetDNSAdsBlocking obtains if ads hostnames/IPs should be blocked from being resolved by Unbound, using the environment variable BLOCK_ADS | func (r *reader) GetDNSAdsBlocking() (blocking bool, err error) {
return r.envParams.GetOnOff("BLOCK_ADS", libparams.Default("off"))
} |
NewBackendService creates a new BackendService stack from a manifest file. | func NewBackendService(mft *manifest.BackendService, env, app string, rc RuntimeConfig) (*BackendService, error) {
parser := template.New()
addons, err := addon.New(aws.StringValue(mft.Name))
if err != nil {
return nil, fmt.Errorf("new addons: %w", err)
}
envManifest, err := mft.ApplyEnv(env) // Apply environmen... |
Warning is alias of Warn | func Warning(args ...interface{}) {
Warn(args...)
} |
Value implements the database/sql/driver Valuer interface. | func (src Macaddr) Value() (driver.Value, error) {
return EncodeValueText(src)
} |
RemoveSource removes an audio Source from the Selector. | func (s *DefaultSelector) RemoveSource(name string) error {
s.Lock()
defer s.Unlock()
if _, ok := s.sources[name]; !ok {
return fmt.Errorf("unknown source %s", name)
}
delete(s.sources, name)
return nil
} |
Run runs the pacemaker which will beat when the previous QC is completed | func (p FixedLeader) Run(ctx context.Context) {
notify := p.GetNotifier()
if p.GetID() == p.leader {
go p.Propose()
}
var n hotstuff.Notification
var ok bool
for {
select {
case n, ok = <-notify:
if !ok {
return
}
case <-ctx.Done():
return
}
switch n.Event {
case hotstuff.QCFinish:
i... |
NewController creates a new instance of Controller | func NewController(betValidator BetValidator, betService BetService) *Controller {
return &Controller{
betValidator: betValidator,
betService: betService,
}
} |
SendDataOrion sends the data to Orion | func SendDataOrion(header http.Header, body map[string]interface{}, hashString string) error {
// Copy the body into a new variable.
// This will be the body of the http request to Orion
var bodyOrion = body
// Add the field hash to the metadata that will be send to Orion
var hash = make(map[string]interface{})
... |
Match matches input kv with kv, value will be wildcard matched depending on the user input | func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
} |
LoadFromOnline is the option to download the emoji data from online instead of the local offline data | func LoadFromOnline(value bool) Option {
return loadFromOnline(value)
} |
SetField sets the value of a field with the given name. It returns an error if the field is not defined in the schema, or if the type mismatched the field type. | func (m *OrgUnitMutation) SetField(name string, value ent.Value) error {
switch name {
case orgunit.FieldCreateByUser:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreateByUser(v)
return nil
case orgunit.FieldUpdateByUser:
v, ok := value.(int)
... |
UpdateByCleared reports if the "update_by" edge to the User entity was cleared. | func (m *OrgUnitPositionMutation) UpdateByCleared() bool {
return m.UpdateByUserCleared() || m.clearedupdate_by
} |
Execute the command or return a humanfriendly error. | func (c *Authorize) Execute(
ctx context.Context,
) error {
err := cli.CheckEnvWarp(ctx)
if err != nil {
return errors.Trace(err)
}
result, err := cli.RunLocalCommand(ctx, warp.Command{
Type: warp.CmdTpState,
Args: []string{},
})
if err != nil {
return errors.Trace(err)
}
if result.Disconnected {
r... |
Fields returns all fields that were changed during this mutation. Note that, in order to get all numeric fields that were in/decremented, call AddedFields(). | func (m *DiagnosisMutation) Fields() []string {
fields := make([]string, 0, 3)
if m._DiagnosticMessages != nil {
fields = append(fields, diagnosis.FieldDiagnosticMessages)
}
if m._SurveillancePeriod != nil {
fields = append(fields, diagnosis.FieldSurveillancePeriod)
}
if m._DiagnosisDate != nil {
fields = a... |
Deprecated: Use EncodeRequest.ProtoReflect.Descriptor instead. | func (*EncodeRequest) Descriptor() ([]byte, []int) {
return file_raptorq_proto_rawDescGZIP(), []int{2}
} |
NewJobs create javascript jobs. | func NewJobs(r *GoRuntime, script string, parentName string, name string) ([]*JobJs, error) {
var (
filename string
fileModTime time.Time
prev = fmt.Sprintf("init %q jobs, ", parentName)
)
if r == nil {
return nil, errors.New(prev + "js runtime object is not initialized")
}
if script == "" {
re... |
wrapping slice: []float64 export Slice_float64_CTor | func Slice_float64_CTor() CGoHandle {
return CGoHandle(handleFromPtr_Slice_float64(&[]float64{}))
} |
Registers a function capable of creating a new Module instance. | func RegisterModule(name string, f func() Module) {
mods[name] = f
} |
WithConfigFile set xuperclient config file. | func WithConfigFile(configFile string) ClientOption {
return func(opts *clientOptions) error {
opts.configFile = configFile
return nil
}
} |
MinLength defines the minimum value alotted to given field | func (v *Validator) MinLength(field string, d int) {
value := v.model[field]
if value == "" {
return
}
if utf8.RuneCountInString(value) < d {
v.errors["errors"] = append(v.errors["errors"], ErrFieldTooShort(d))
}
} |
let a b c d = foo(1) foo(0) | func TestAssigningVariableToInvokedBlockWithMultipleValuesAcrossMultipleInvocations(t *testing.T) {
ast := []Node{
Node{
Token: "ASSIGNMENT",
Row: 3,
Col: 1,
Data: map[string]interface{}{
"Names": "a b c d",
"Values": []Node{},
},
},
Node{
Token: "INVOCA... |
Test that status transitions from Inactive to Active, once the start time is reached | func TestActivation(t *testing.T) {
mockclock := clock.NewMock()
setClock(mockclock) // replace clock with mock for speedy testing
now := mockclock.Now()
reset()
p, _ := New("Promo1", now.Add(1*time.Hour), now.Add(24*time.Hour))
runtime.Gosched()
if res := p.AllowDisplay(ip); res != false {
t.Errorf("Bad Pr... |
Perform a node check | func checkNode(c *cli.Context) error {
monitoringData := nagiosPlugin.NewMonitoring()
// Check global parameters
err := manageGlobalParameters()
if err != nil {
return cli.NewExitError(fmt.Sprintf("%v", err), nagiosPlugin.STATUS_UNKNOWN)
}
// Check current parameters
if c.String("cluster-name") == "" {
re... |
GetHostPorts returns the HostPorts field value if set, zero value otherwise (both if not set or set to explicit null). | func (o *EquipmentIoCardBase) GetHostPorts() []EtherHostPortRelationship {
if o == nil {
var ret []EtherHostPortRelationship
return ret
}
return o.HostPorts
} |
Returns true if the value exists in the BTree. | func (tree *BTree) Contains(val interface{}) bool {
return tree.contains(wrap(val))
} |
DefaultCluster initializes a client given a Config. | func DefaultCluster(cfg *Config) (Client, error) {
ctx := context.Background()
client := &defaultCluster{
ctx: ctx,
config: cfg,
}
if client.config.Port == "" {
client.config.Port = fmt.Sprintf("%d", DefaultPort)
}
err := client.setupAPIAddr()
if err != nil {
return nil, err
}
err = client.resolv... |
ScanX is like Scan, but panics if an error occurs. | func (das *DrugAllergySelect) ScanX(ctx context.Context, v interface{}) {
if err := das.Scan(ctx, v); err != nil {
panic(err)
}
} |
Put a value for key, if key is unknown, add a new. | func (m *OMap) Put(k string, v interface{}) bool {
if !m.HasKey(k) {
m.add(k, v)
return false
}
// move k to last of m.keys
n := indexOf(k, m.keys)
m.keys = append(append(m.keys[:n], m.keys[n+1:]...), k)
// set v for k in m.baseMap
m.baseMap[k] = v
return true
} |
Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously. | func (o FioSpecVolumeVolumeSourceFcOutput) Wwids() pulumi.StringArrayOutput {
return o.ApplyT(func(v FioSpecVolumeVolumeSourceFc) []string { return v.Wwids }).(pulumi.StringArrayOutput)
} |
GetOwnershipType returns the OwnershipType field value | func (o *KanbanViewView) GetOwnershipType() string {
if o == nil {
var ret string
return ret
}
return o.OwnershipType
} |
Enqueue enqueues and never blocks | func (w *watchQueue) Enqueue(key string, kvp *kvdb.KVPair, err error) {
w.m.Lock()
w.updates = append(w.updates, &watchUpdate{key: key, kvp: kvp, err: err})
w.cv.Signal()
w.m.Unlock()
} |
SetPlmnIdFilter resets the service's PLMN ID filter from given PLMN ID list | func (s *EapAkaSrv) SetPlmnIdFilter(plmnIds []string) {
s.plmnFilter = plmn_filter.GetPlmnVals(plmnIds, "EAP-AKA")
} |
New returns a new PagerDuty notifier. | func New(c *config.PagerdutyConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "pagerduty", httpOpts...)
if err != nil {
return nil, err
}
n := &Notifier{conf: c, tmpl: t, logger: l, client: client}
... |
Bool decodes any JSON field into a bool | func Bool() Decoder {
return newDecoder(func(b []byte) (interface{}, error) {
var bl bool
if err := json.Unmarshal(b, &bl); err != nil {
return "", err
}
return bl, nil
})
} |
RecoverPanics wraps http.Handler to recover and log panics. | func RecoverPanics(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
if x := recover(); x != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "apis panic. Look in log for details.")
glog.Infof("APIServer panic'... |
compareResult compares the result value with the defined expectation. | func (ev *evalCmd) compareResult(j []byte) error {
var response prometheus.Response
err := json.Unmarshal(j, &response)
if err != nil {
return err
}
if response.Status != "success" {
return fmt.Errorf("unsuccess status received: %s", response.Status)
}
result := response.Data.Result
switch result := resu... |
MakeNAT creates a port mapper from set cmd line flags. | func MakeNAT(ctx *cli.Context) nat.Interface {
natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
if err != nil {
Fatalf("Option %s: %v", NATFlag.Name, err)
}
return natif
} |
UnmarshalXML implements the xml.Unmarshaller interface for type ContainerProperties. | func (c *ContainerProperties) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error {
type alias ContainerProperties
aux := &struct {
*alias
DeletedTime *timeRFC1123 `xml:"DeletedTime"`
LastModified *timeRFC1123 `xml:"Last-Modified"`
}{
alias: (*alias)(c),
}
if err := dec.DecodeElement(aux, &start)... |
CheckHealth handles health checks sent from Grafana to the plugin. The main use case for these health checks is the test button on the datasource configuration page which allows users to verify that a datasource is working as expected. | func (v *VerticaDatasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) {
log.DefaultLogger.Debug("Inside datasource.CheckHealth Function", "request", req)
var status = backend.HealthStatusOk
connDB, err := v.GetVerticaDb(req.PluginContext)
if err != nil ... |
IsComment return true if content is comment | func (c *Content) IsComment() bool {
return c.Type == CONTENT_TYPE_COMMENT
} |
WithHTTPMethod returns an HTTPCheckerOption that specifies the method for HTTP requests. The default method is "GET" which works in most of the cases, but another popular choice is "HEAD". | func WithHTTPMethod(method string) HTTPCheckerOption {
return func(c *HTTPChecker) {
c.method = method
}
} |
GetVPCS returns the list of AWS VPC's. | func GetVPCS(accessKeyID, secretAccessKey, region string) ([]*ec2.Vpc, error) {
client, err := GetClientSet(accessKeyID, secretAccessKey, region)
if err != nil {
return nil, err
}
vpcOut, err := client.EC2.DescribeVpcs(&ec2.DescribeVpcsInput{})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsEr... |
NewWatchPolicyV1beta1PodSecurityPolicyUnauthorized creates WatchPolicyV1beta1PodSecurityPolicyUnauthorized with default headers values | func NewWatchPolicyV1beta1PodSecurityPolicyUnauthorized() *WatchPolicyV1beta1PodSecurityPolicyUnauthorized {
return &WatchPolicyV1beta1PodSecurityPolicyUnauthorized{}
} |
Set a PUT request handler for the route. | func (r *Route) Put(h http.Handler) *Route {
r.Add("PUT", h)
return r
} |
addGrant merges a new clawback vesting grant into an existing ClawbackVestingAccount. | func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {
// how much is really delegated?
bondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())
unbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetA... |
archiveContext makes a tar.gz stream consists of files. | func archiveContext(ctx context.Context, root string, writer io.Writer) (err error) {
// Create a buffered writer.
bufWriter := bufio.NewWriter(writer)
defer bufWriter.Flush()
// Create a zipped writer on the bufferd writer.
zipWriter, err := gzip.NewWriterLevel(bufWriter, gzip.BestCompression)
if err != nil {
... |
Contains checks whether rh.Hierarchy contains orh.Hierarchy | func (rh ResourceHierarchy) Contains(orh ResourceHierarchy) bool {
rhh := buildResourceHierarchy(rh)
orhh := buildResourceHierarchy(orh)
if rhh.size > orhh.size {
return false
}
for i := range orhh.hierarchy {
if i >= len(rhh.hierarchy) {
return false
}
if rhh.hierarchy[i] == "*" {
return true
}
... |
NewSalt generates a random salt for use in account passwords | func NewSalt() ([]byte, error) {
key := make([]byte, 60)
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
} |
hasDataCite returns 'true' if a repository includes a file called 'datacite.yml' in its root. No checks are made to determine if the file is valid. If any error occurs, for example due to an uninitialised repository or missing repository root, it returns 'false' without error. | func hasDataCite(c *Context) bool {
commit, err := c.Repo.GitRepo.BranchCommit(c.Repo.Repository.DefaultBranch)
if err != nil {
log.Trace("Couldn't get commit: %v", err)
return false
}
_, err = commit.Blob("/datacite.yml")
log.Trace("Found datacite? %t", err == nil)
return err == nil
} |
Code implements the Frame interface. | func (f *CreateBundleReply) Code() FrameCode {
return FrameCreateBundle
} |
Function to sort strings using slices? | func Sort_String(str string) string {
newStr := strings.Split(str, "")
sort.Strings(newStr)
return strings.Join(newStr,"")
} |
DeleteTransitKey : Delete a transit key from Vault | func (v *Vault) DeleteTransitKey(key string) {
p := make(map[string]interface{})
p["deletion_allowed"] = "true"
_, err := v.Client.Logical().Write("transit/keys/"+key+"/config", p)
if err != nil {
log.Fatalf("Vault error: %v", err)
}
_, err = v.Client.Logical().Delete("transit/keys/" + key)
if err != nil {
... |
Handle success response from salesforce. | func (op *OpQuery) Handle(resp *http.Response) error {
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("get operator can't handle response with code %d, expect %d", resp.StatusCode, http.StatusOK)
}
return json.NewDecoder(resp.Body).Decode(&op.result)
} |
Inc increases the counter by one. | func (g *Gorc) Inc() {
g.Lock()
g.count++
g.Unlock()
} |
GetAndLock Get and lock the server. | func (impl *Server) GetAndLock(ID string) (bool, base.ModelInterface) {
var (
c = impl.TemplateImpl.GetConnection()
server = new(entity.Server)
)
// Transaction start.
tx := c.Begin()
if err := tx.Error; err != nil {
log.WithFields(log.Fields{
"id": ID,
"error": err}).
Warn("DB get and lock ... |
SetupServer : This function initializes a datasending server that lies outside of the Blink Node System. It responds to a HelloOracle message (sent by the server) by setting up a SessionID as well as an initial series of hops for the session. The oracle then sends the SessionID and the first blink node's address to the... | func SetupServer(serverAddr *net.UDPAddr, conn *net.UDPConn, buf []byte) {
destAddr := ExtractFinalDestAddr(buf)
fmt.Println("Dest Addr:", destAddr.String())
SID := "1001100110011001"
decisionTable := make(map[string][]string)
decisionTable[SID] = []string{nodesTable[0], nodesTable[2], destAddr.String()}
Decisio... |
NewRemoveUserGroupParamsWithHTTPClient creates a new RemoveUserGroupParams object with the ability to set a custom HTTPClient for a request. | func NewRemoveUserGroupParamsWithHTTPClient(client *http.Client) *RemoveUserGroupParams {
return &RemoveUserGroupParams{
HTTPClient: client,
}
} |
SelectFromPostByID return one row by Id | func SelectFromPostByID(id int) *Post {
db := MysqlConnect()
defer db.Close()
var post Post
err := db.QueryRow("SELECT * FROM post where id = ?", id).Scan(&post.ID,
&post.Title, &post.Description, &post.Post, &post.Date, &post.Author,
&post.Thumbnail, &post.Categories)
if err != nil {
panic(err.Error())
... |
SetSensitivityPolicySettings sets the sensitivityPolicySettings property value. The sensitivityPolicySettings property | func (m *InformationProtection) SetSensitivityPolicySettings(value SensitivityPolicySettingsable)() {
err := m.GetBackingStore().Set("sensitivityPolicySettings", value)
if err != nil {
panic(err)
}
} |
CreateUser indicates an expected call of CreateUser. | func (mr *ClientMockRecorder) CreateUser(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateUser", reflect.TypeOf((*Client)(nil).CreateUser), arg0, arg1)
} |
NewIntentsDeviceManagementIntentItemRequestBuilderInternal instantiates a new DeviceManagementIntentItemRequestBuilder and sets the default values. | func NewIntentsDeviceManagementIntentItemRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*IntentsDeviceManagementIntentItemRequestBuilder) {
m := &IntentsDeviceManagementIntentItemRequestBuilder{
BaseRe... |
NewFeedURL sets itunes:newfeedurl of given feed. | func NewFeedURL(newURL string) func(f *Feed) error {
return func(f *Feed) error {
u, err := url.Parse(newURL)
if err != nil {
return err
}
if !u.IsAbs() {
return ErrInvalidURL
}
f.Channel.NewFeedURL = newURL
return nil
}
} |
calculateDigit calculates the next digit for the given document. | func calculateDigit(doc string, position int) string {
var sum int
for _, r := range doc {
sum += toInt(r) * position
position--
if position < 2 {
position = 9
}
}
sum %= 11
if sum < 2 {
return "0"
}
return strconv.Itoa(11 - sum)
} |
NewPutTravelExpensePassengerIDParamsWithTimeout creates a new PutTravelExpensePassengerIDParams object with the default values initialized, and the ability to set a timeout on a request | func NewPutTravelExpensePassengerIDParamsWithTimeout(timeout time.Duration) *PutTravelExpensePassengerIDParams {
var ()
return &PutTravelExpensePassengerIDParams{
timeout: timeout,
}
} |
EdgeCleared returns a boolean indicates if this edge was cleared in this mutation. | func (m *DiseaseMutation) EdgeCleared(name string) bool {
switch name {
case disease.EdgeEmployee:
return m.clearedemployee
case disease.EdgeSeverity:
return m.clearedseverity
case disease.EdgeDiseasetype:
return m.cleareddiseasetype
case disease.EdgeDiagnosis:
return m.cleareddiagnosis
}
return false
} |
GetVestingCoins returns the total number of vesting coins. If no coins are vesting, nil is returned. | func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {
return pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))
} |
A label query over a set of resources, in this case pods. | func (o PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) LabelSelector() PgbenchSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelectorPtrOutput {
return o.ApplyT(func(v Pgb... |
AddAggregate is a mock implementation | func (f *FakeWatchPrefixes) AddAggregate(paths []string, peer string) watchstream.WatchEventQ {
f.AddAgg++
if f.AddAggFn != nil {
return f.AddAggFn(paths, peer)
}
return nil
} |
Cinder represents a cinder volume attached and mounted on kubelets host machine More info: | func (o IopingSpecVolumeVolumeSourcePtrOutput) Cinder() IopingSpecVolumeVolumeSourceCinderPtrOutput {
return o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceCinder {
if v == nil {
return nil
}
return v.Cinder
}).(IopingSpecVolumeVolumeSourceCinderPtrOutput)
} |
HasClonedFrom returns a boolean if a field has been set. | func (o *WorkflowWorkflowDefinitionAllOf) HasClonedFrom() bool {
if o != nil && o.ClonedFrom != nil {
return true
}
return false
} |
SetConstraintNil sets the value for Constraint to be an explicit nil | func (o *HyperflexServerFirmwareVersionEntryAllOf) SetConstraintNil() {
o.Constraint.Set(nil)
} |
DutyCleared returns if the "duty" field was cleared in this mutation. | func (m *OrgUnitPositionMutation) DutyCleared() bool {
_, ok := m.clearedFields[orgunitposition.FieldDuty]
return ok
} |
Deprecated: Use DownstreamTlsWrapperContext.ProtoReflect.Descriptor instead. | func (*DownstreamTlsWrapperContext) Descriptor() ([]byte, []int) {
return file_cilium_api_tls_wrapper_proto_rawDescGZIP(), []int{1}
} |
EncodeX509Chain will encode a list of x509.Certificates into a PEM format chain. Selfsigned certificates are not included as per Certificates are output in the order they're given; if the input is not ordered as specified in RFC5246 section 7.4.2, the resulting chain might not be valid for use in TLS. | func EncodeX509Chain(certs []*x509.Certificate) ([]byte, error) {
if len(certs) == 0 {
return nil, errors.New("no certificates in chain")
}
certPEM := bytes.NewBuffer([]byte{})
for _, cert := range certs {
if cert == nil {
continue
}
if cert.CheckSignatureFrom(cert) == nil {
// Don't include self-si... |
GetUsersHandler lista todos los usuarios | func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
var users []User
for _, v := range Listusers {
users = append(users, v)
}
w.Header().Set("Content-Type", "application/json")
j, err := json.Marshal(users)
if err != nil {
panic(err)
}
w.WriteHeader(http.StatusOK)
w.Write(j)
} |
CloseTheCloser closes the closer | func CloseTheCloser(c io.Closer) {
_ = c.Close()
} |
Request returns a new Request instance. Arguments are similar to NewRequest. After creating request, all builders attached to Expect instance are invoked. See Builder. | func (e *Expect) Request(method, path string, pathargs ...interface{}) *Request {
opChain := e.chain.enter("Request(%q)", method)
defer opChain.leave()
req := newRequest(opChain, e.config, method, path, pathargs...)
for _, builder := range e.builders {
builder(req)
}
for _, matcher := range e.matchers {
re... |
WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors. Basically syntactic sugar. | func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption {
return grpc.StreamInterceptor(ChainStreamServer(interceptors...))
} |
Show runs the show action. | func (c *TrackerController) Show(ctx *app.ShowTrackerContext) error {
return application.Transactional(c.db, func(appl application.Application) error {
t, err := appl.Trackers().Load(ctx.Context, ctx.ID)
if err != nil {
switch err.(type) {
case remoteworkitem.NotFoundError:
log.Printf("not found, id=%s",... |
Deprecated: Do not use. | func (m *TracingZipkinConfig) GetResources() *Resources {
if m != nil {
return m.Resources
}
return nil
} |
ReadMask sets the optional parameter "readMask": Required. The specific fields to return. Use "" to include all fields. Repeated field items cannot be individually specified. | func (c *LocationsLodgingGetGoogleUpdatedCall) ReadMask(readMask string) *LocationsLodgingGetGoogleUpdatedCall {
c.urlParams_.Set("readMask", readMask)
return c
} |
Version returns the version of the content. | func (o SparseEnforcerReportsList) Version() int {
return 1
} |
NewTimer return an instance of delay queue | func NewTimer(name string, redis *RedisInstance, interval, checkBackupInterval time.Duration) (*Timer, error) {
timer := &Timer{
name: name,
redis: redis,
interval: interval,
checkBackupInterval: checkBackupInterval,
shutdown: make(chan struct{}),
}
// Pr... |
ok fails the test if an err is not nil. | func ok(tb testing.TB, err error) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
tb.FailNow()
}
} |
Stop terminates the sink manager. | func (sm *SinkManager) Stop() {
sm.stopOnce.Do(func() {
close(sm.doneChannel)
sm.metrics.Stop()
sm.sinks.DeleteAll()
})
} |
1) Directly test is use the server side completed policies to test 2) Partial policies test is only using the policies that are related with the subject to test. This is a simulation for frontend, since the user can only get policies that relate to him/her. | func directlyAndRebuildWithPartialPoliciesTest(oldEnforcer Enforcer, sub string, fn func(e Enforcer, helperMessage string)) {
// directly test
fn(oldEnforcer, "directly test")
// create a new enforcer with abbreviated policies
policies := oldEnforcer.GetCompletePoliciesFor(sub)
policyAdapter := NewStringPolicyAda... |
ListView Clicked item index | @Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
int itemPosition = position;
switch (itemPosition) {
case 0:
... |
Read in the JSON from the example resources | @Test
public void testTradesAdapter() throws IOException {
InputStream is =
CryptopiaAdaptersTest.class.getResourceAsStream(
"/org/knowm/xchange/cryptopia/dto/marketdata/example-trades.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
CryptopiaBaseRespon... |
Convertimos la lista de generos | public MovieDetails transform(Movie movie){
String genres = "";
for (int i = 0; i < movie.getMovieGenres().size(); i++)
genres += movie.getMovieGenres().get(i).getName() + ", ";
genres = genres.substring(0,genres.length() - 2);
String originalTitle = movie.getOriginalTitle... |
Proveedores mas solicitados (de todos los tiempos) (Grafica Barras => Proveedor vs NumeroCompras) | public String estadisticasFinancieras(String anio) {
String html = "";
DefaultTableModel dtm1 = venta.estadisticaFinancierasMeseVsIngresoGasto(anio);
DefaultTableModel dtm2 = venta.estadisticaFinancierasIngresosGastosUtilidades(anio);
html = Utils.dibujarGraficasHTMLLineasYTorta... |
This method populates Entity To Deletet List. | private void populateEntityToDeletetList()
{
entityNameListDelete = new ArrayList<String>();
entityNameListDelete.add("edu.wustl.catissuecore.domain.Quantity");
entityNameListDelete
.add("edu.wustl.catissuecore.domain.SpecimenCollectionRequirementGroup");
} |
Finds all airports in provided txt file, with corresponding city with comments in database. Airport that does not have active city in database is not part of resulting HashMap. | @Override
public HashMap<String, Airport> findAll() {
List<City> cities = cityDao.findAll(0);
airportFile = new File(AirportDao.class.getClassLoader().getResource("airports.txt").getPath());
try {
FlightFileReader.consumeNonEmptyLinesFromFile(airportFile, line -> {
... |
Do a traversal of the list and print it out | public void printList(TernaryTreeNode head) {
// System.out.println(" head :: " + head.right.right.data);
TernaryTreeNode current = head;
while (true)
{
System.out.print(current.data + " ");
current = current.right;
if... |
attempt to parse an integer | public static boolean tryParse(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException ex) {
return false;
} catch (Exception ex) {
logError(ex);
return false;
}
} |
Returns a string specifying the message to display when there is no row to display. | public String getNoPagedMessage() {
return getNoPagedMessage(null);
} |
TODO Autogenerated method stub | @Override
public BaseResponse testResponse() {
return setResultSuccess();
} |
get comment to see | public static List<Comment> getCommentByMB(int idtargetmicroblog) throws SQLException {
List<Comment> comments = new ArrayList<Comment>();
Connection c = DriverManager.getConnection(connectionString,dbUsername, dbPassword);
PreparedStatement ps = null;
ResultSet rs = null;
try {
/*List focusingIdusers = ge... |
/ returns a string of its children types (nonJavadoc) | public Object visitReturnStmt(GoIRReturnStmtNode node) {
return node.getChild().accept(this);
} |
Activity wird beendet BroadcastReceiver deregistrieren | @Override
protected void onDestroy() {
super.onDestroy();
if(mReceiver != null) unregisterReceiver(mReceiver);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.