id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
158,200
Shopify/sarama
mocks/consumer.go
Topics
func (c *Consumer) Topics() ([]string, error) { c.l.Lock() defer c.l.Unlock() if c.metadata == nil { c.t.Errorf("Unexpected call to Topics. Initialize the mock's topic metadata with SetMetadata.") return nil, sarama.ErrOutOfBrokers } var result []string for topic := range c.metadata { result = append(result, topic) } return result, nil }
go
func (c *Consumer) Topics() ([]string, error) { c.l.Lock() defer c.l.Unlock() if c.metadata == nil { c.t.Errorf("Unexpected call to Topics. Initialize the mock's topic metadata with SetMetadata.") return nil, sarama.ErrOutOfBrokers } var result []string for topic := range c.metadata { result = append(result, topic) } return result, nil }
[ "func", "(", "c", "*", "Consumer", ")", "Topics", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "metadata", "==", "nil", "{", "c", ".", "t", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "sarama", ".", "ErrOutOfBrokers", "\n", "}", "\n\n", "var", "result", "[", "]", "string", "\n", "for", "topic", ":=", "range", "c", ".", "metadata", "{", "result", "=", "append", "(", "result", ",", "topic", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Topics returns a list of topics, as registered with SetMetadata
[ "Topics", "returns", "a", "list", "of", "topics", "as", "registered", "with", "SetMetadata" ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/consumer.go#L67-L81
158,201
Shopify/sarama
mocks/consumer.go
Partitions
func (c *Consumer) Partitions(topic string) ([]int32, error) { c.l.Lock() defer c.l.Unlock() if c.metadata == nil { c.t.Errorf("Unexpected call to Partitions. Initialize the mock's topic metadata with SetMetadata.") return nil, sarama.ErrOutOfBrokers } if c.metadata[topic] == nil { return nil, sarama.ErrUnknownTopicOrPartition } return c.metadata[topic], nil }
go
func (c *Consumer) Partitions(topic string) ([]int32, error) { c.l.Lock() defer c.l.Unlock() if c.metadata == nil { c.t.Errorf("Unexpected call to Partitions. Initialize the mock's topic metadata with SetMetadata.") return nil, sarama.ErrOutOfBrokers } if c.metadata[topic] == nil { return nil, sarama.ErrUnknownTopicOrPartition } return c.metadata[topic], nil }
[ "func", "(", "c", "*", "Consumer", ")", "Partitions", "(", "topic", "string", ")", "(", "[", "]", "int32", ",", "error", ")", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "metadata", "==", "nil", "{", "c", ".", "t", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "sarama", ".", "ErrOutOfBrokers", "\n", "}", "\n", "if", "c", ".", "metadata", "[", "topic", "]", "==", "nil", "{", "return", "nil", ",", "sarama", ".", "ErrUnknownTopicOrPartition", "\n", "}", "\n\n", "return", "c", ".", "metadata", "[", "topic", "]", ",", "nil", "\n", "}" ]
// Partitions returns the list of parititons for the given topic, as registered with SetMetadata
[ "Partitions", "returns", "the", "list", "of", "parititons", "for", "the", "given", "topic", "as", "registered", "with", "SetMetadata" ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/consumer.go#L84-L97
158,202
Shopify/sarama
mocks/consumer.go
Close
func (c *Consumer) Close() error { c.l.Lock() defer c.l.Unlock() for _, partitions := range c.partitionConsumers { for _, partitionConsumer := range partitions { _ = partitionConsumer.Close() } } return nil }
go
func (c *Consumer) Close() error { c.l.Lock() defer c.l.Unlock() for _, partitions := range c.partitionConsumers { for _, partitionConsumer := range partitions { _ = partitionConsumer.Close() } } return nil }
[ "func", "(", "c", "*", "Consumer", ")", "Close", "(", ")", "error", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "partitions", ":=", "range", "c", ".", "partitionConsumers", "{", "for", "_", ",", "partitionConsumer", ":=", "range", "partitions", "{", "_", "=", "partitionConsumer", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Close implements the Close method from the sarama.Consumer interface. It will close // all registered PartitionConsumer instances.
[ "Close", "implements", "the", "Close", "method", "from", "the", "sarama", ".", "Consumer", "interface", ".", "It", "will", "close", "all", "registered", "PartitionConsumer", "instances", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/consumer.go#L117-L128
158,203
Shopify/sarama
mocks/consumer.go
Close
func (pc *PartitionConsumer) Close() error { if !pc.consumed { pc.t.Errorf("Expectations set on %s/%d, but no partition consumer was started.", pc.topic, pc.partition) return errPartitionConsumerNotStarted } if pc.errorsShouldBeDrained && len(pc.errors) > 0 { pc.t.Errorf("Expected the errors channel for %s/%d to be drained on close, but found %d errors.", pc.topic, pc.partition, len(pc.errors)) } if pc.messagesShouldBeDrained && len(pc.messages) > 0 { pc.t.Errorf("Expected the messages channel for %s/%d to be drained on close, but found %d messages.", pc.topic, pc.partition, len(pc.messages)) } pc.AsyncClose() var ( closeErr error wg sync.WaitGroup ) wg.Add(1) go func() { defer wg.Done() var errs = make(sarama.ConsumerErrors, 0) for err := range pc.errors { errs = append(errs, err) } if len(errs) > 0 { closeErr = errs } }() wg.Add(1) go func() { defer wg.Done() for range pc.messages { // drain } }() wg.Wait() return closeErr }
go
func (pc *PartitionConsumer) Close() error { if !pc.consumed { pc.t.Errorf("Expectations set on %s/%d, but no partition consumer was started.", pc.topic, pc.partition) return errPartitionConsumerNotStarted } if pc.errorsShouldBeDrained && len(pc.errors) > 0 { pc.t.Errorf("Expected the errors channel for %s/%d to be drained on close, but found %d errors.", pc.topic, pc.partition, len(pc.errors)) } if pc.messagesShouldBeDrained && len(pc.messages) > 0 { pc.t.Errorf("Expected the messages channel for %s/%d to be drained on close, but found %d messages.", pc.topic, pc.partition, len(pc.messages)) } pc.AsyncClose() var ( closeErr error wg sync.WaitGroup ) wg.Add(1) go func() { defer wg.Done() var errs = make(sarama.ConsumerErrors, 0) for err := range pc.errors { errs = append(errs, err) } if len(errs) > 0 { closeErr = errs } }() wg.Add(1) go func() { defer wg.Done() for range pc.messages { // drain } }() wg.Wait() return closeErr }
[ "func", "(", "pc", "*", "PartitionConsumer", ")", "Close", "(", ")", "error", "{", "if", "!", "pc", ".", "consumed", "{", "pc", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "pc", ".", "topic", ",", "pc", ".", "partition", ")", "\n", "return", "errPartitionConsumerNotStarted", "\n", "}", "\n\n", "if", "pc", ".", "errorsShouldBeDrained", "&&", "len", "(", "pc", ".", "errors", ")", ">", "0", "{", "pc", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "pc", ".", "topic", ",", "pc", ".", "partition", ",", "len", "(", "pc", ".", "errors", ")", ")", "\n", "}", "\n\n", "if", "pc", ".", "messagesShouldBeDrained", "&&", "len", "(", "pc", ".", "messages", ")", ">", "0", "{", "pc", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "pc", ".", "topic", ",", "pc", ".", "partition", ",", "len", "(", "pc", ".", "messages", ")", ")", "\n", "}", "\n\n", "pc", ".", "AsyncClose", "(", ")", "\n\n", "var", "(", "closeErr", "error", "\n", "wg", "sync", ".", "WaitGroup", "\n", ")", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "var", "errs", "=", "make", "(", "sarama", ".", "ConsumerErrors", ",", "0", ")", "\n", "for", "err", ":=", "range", "pc", ".", "errors", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "errs", ")", ">", "0", "{", "closeErr", "=", "errs", "\n", "}", "\n", "}", "(", ")", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "for", "range", "pc", ".", "messages", "{", "// drain", "}", "\n", "}", "(", ")", "\n\n", "wg", ".", "Wait", "(", ")", "\n", "return", "closeErr", "\n", "}" ]
// Close implements the Close method from the sarama.PartitionConsumer interface. It will // verify whether the partition consumer was actually started.
[ "Close", "implements", "the", "Close", "method", "from", "the", "sarama", ".", "PartitionConsumer", "interface", ".", "It", "will", "verify", "whether", "the", "partition", "consumer", "was", "actually", "started", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/consumer.go#L209-L254
158,204
Shopify/sarama
mocks/consumer.go
YieldError
func (pc *PartitionConsumer) YieldError(err error) { pc.errors <- &sarama.ConsumerError{ Topic: pc.topic, Partition: pc.partition, Err: err, } }
go
func (pc *PartitionConsumer) YieldError(err error) { pc.errors <- &sarama.ConsumerError{ Topic: pc.topic, Partition: pc.partition, Err: err, } }
[ "func", "(", "pc", "*", "PartitionConsumer", ")", "YieldError", "(", "err", "error", ")", "{", "pc", ".", "errors", "<-", "&", "sarama", ".", "ConsumerError", "{", "Topic", ":", "pc", ".", "topic", ",", "Partition", ":", "pc", ".", "partition", ",", "Err", ":", "err", ",", "}", "\n", "}" ]
// YieldError will yield an error on the Errors channel of this partition consumer // when it is consumed. By default, the mock consumer will not verify whether this error was // consumed from the Errors channel, because there are legitimate reasons for this // not to happen. You can call ExpectErrorsDrainedOnClose so it will verify that // the channel is empty on close.
[ "YieldError", "will", "yield", "an", "error", "on", "the", "Errors", "channel", "of", "this", "partition", "consumer", "when", "it", "is", "consumed", ".", "By", "default", "the", "mock", "consumer", "will", "not", "verify", "whether", "this", "error", "was", "consumed", "from", "the", "Errors", "channel", "because", "there", "are", "legitimate", "reasons", "for", "this", "not", "to", "happen", ".", "You", "can", "call", "ExpectErrorsDrainedOnClose", "so", "it", "will", "verify", "that", "the", "channel", "is", "empty", "on", "close", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/consumer.go#L295-L301
158,205
Shopify/sarama
balance_strategy.go
Add
func (p BalanceStrategyPlan) Add(memberID, topic string, partitions ...int32) { if len(partitions) == 0 { return } if _, ok := p[memberID]; !ok { p[memberID] = make(map[string][]int32, 1) } p[memberID][topic] = append(p[memberID][topic], partitions...) }
go
func (p BalanceStrategyPlan) Add(memberID, topic string, partitions ...int32) { if len(partitions) == 0 { return } if _, ok := p[memberID]; !ok { p[memberID] = make(map[string][]int32, 1) } p[memberID][topic] = append(p[memberID][topic], partitions...) }
[ "func", "(", "p", "BalanceStrategyPlan", ")", "Add", "(", "memberID", ",", "topic", "string", ",", "partitions", "...", "int32", ")", "{", "if", "len", "(", "partitions", ")", "==", "0", "{", "return", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "p", "[", "memberID", "]", ";", "!", "ok", "{", "p", "[", "memberID", "]", "=", "make", "(", "map", "[", "string", "]", "[", "]", "int32", ",", "1", ")", "\n", "}", "\n", "p", "[", "memberID", "]", "[", "topic", "]", "=", "append", "(", "p", "[", "memberID", "]", "[", "topic", "]", ",", "partitions", "...", ")", "\n", "}" ]
// Add assigns a topic with a number partitions to a member.
[ "Add", "assigns", "a", "topic", "with", "a", "number", "partitions", "to", "a", "member", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/balance_strategy.go#L14-L22
158,206
Shopify/sarama
balance_strategy.go
Plan
func (s *balanceStrategy) Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) { // Build members by topic map mbt := make(map[string][]string) for memberID, meta := range members { for _, topic := range meta.Topics { mbt[topic] = append(mbt[topic], memberID) } } // Sort members for each topic for topic, memberIDs := range mbt { sort.Sort(&balanceStrategySortable{ topic: topic, memberIDs: memberIDs, }) } // Assemble plan plan := make(BalanceStrategyPlan, len(members)) for topic, memberIDs := range mbt { s.coreFn(plan, memberIDs, topic, topics[topic]) } return plan, nil }
go
func (s *balanceStrategy) Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) { // Build members by topic map mbt := make(map[string][]string) for memberID, meta := range members { for _, topic := range meta.Topics { mbt[topic] = append(mbt[topic], memberID) } } // Sort members for each topic for topic, memberIDs := range mbt { sort.Sort(&balanceStrategySortable{ topic: topic, memberIDs: memberIDs, }) } // Assemble plan plan := make(BalanceStrategyPlan, len(members)) for topic, memberIDs := range mbt { s.coreFn(plan, memberIDs, topic, topics[topic]) } return plan, nil }
[ "func", "(", "s", "*", "balanceStrategy", ")", "Plan", "(", "members", "map", "[", "string", "]", "ConsumerGroupMemberMetadata", ",", "topics", "map", "[", "string", "]", "[", "]", "int32", ")", "(", "BalanceStrategyPlan", ",", "error", ")", "{", "// Build members by topic map", "mbt", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "memberID", ",", "meta", ":=", "range", "members", "{", "for", "_", ",", "topic", ":=", "range", "meta", ".", "Topics", "{", "mbt", "[", "topic", "]", "=", "append", "(", "mbt", "[", "topic", "]", ",", "memberID", ")", "\n", "}", "\n", "}", "\n\n", "// Sort members for each topic", "for", "topic", ",", "memberIDs", ":=", "range", "mbt", "{", "sort", ".", "Sort", "(", "&", "balanceStrategySortable", "{", "topic", ":", "topic", ",", "memberIDs", ":", "memberIDs", ",", "}", ")", "\n", "}", "\n\n", "// Assemble plan", "plan", ":=", "make", "(", "BalanceStrategyPlan", ",", "len", "(", "members", ")", ")", "\n", "for", "topic", ",", "memberIDs", ":=", "range", "mbt", "{", "s", ".", "coreFn", "(", "plan", ",", "memberIDs", ",", "topic", ",", "topics", "[", "topic", "]", ")", "\n", "}", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// Plan implements BalanceStrategy.
[ "Plan", "implements", "BalanceStrategy", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/balance_strategy.go#L82-L105
158,207
Shopify/sarama
admin.go
NewClusterAdmin
func NewClusterAdmin(addrs []string, conf *Config) (ClusterAdmin, error) { client, err := NewClient(addrs, conf) if err != nil { return nil, err } //make sure we can retrieve the controller _, err = client.Controller() if err != nil { return nil, err } ca := &clusterAdmin{ client: client, conf: client.Config(), } return ca, nil }
go
func NewClusterAdmin(addrs []string, conf *Config) (ClusterAdmin, error) { client, err := NewClient(addrs, conf) if err != nil { return nil, err } //make sure we can retrieve the controller _, err = client.Controller() if err != nil { return nil, err } ca := &clusterAdmin{ client: client, conf: client.Config(), } return ca, nil }
[ "func", "NewClusterAdmin", "(", "addrs", "[", "]", "string", ",", "conf", "*", "Config", ")", "(", "ClusterAdmin", ",", "error", ")", "{", "client", ",", "err", ":=", "NewClient", "(", "addrs", ",", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "//make sure we can retrieve the controller", "_", ",", "err", "=", "client", ".", "Controller", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ca", ":=", "&", "clusterAdmin", "{", "client", ":", "client", ",", "conf", ":", "client", ".", "Config", "(", ")", ",", "}", "\n", "return", "ca", ",", "nil", "\n", "}" ]
// NewClusterAdmin creates a new ClusterAdmin using the given broker addresses and configuration.
[ "NewClusterAdmin", "creates", "a", "new", "ClusterAdmin", "using", "the", "given", "broker", "addresses", "and", "configuration", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/admin.go#L100-L117
158,208
Shopify/sarama
encoder_decoder.go
encode
func encode(e encoder, metricRegistry metrics.Registry) ([]byte, error) { if e == nil { return nil, nil } var prepEnc prepEncoder var realEnc realEncoder err := e.encode(&prepEnc) if err != nil { return nil, err } if prepEnc.length < 0 || prepEnc.length > int(MaxRequestSize) { return nil, PacketEncodingError{fmt.Sprintf("invalid request size (%d)", prepEnc.length)} } realEnc.raw = make([]byte, prepEnc.length) realEnc.registry = metricRegistry err = e.encode(&realEnc) if err != nil { return nil, err } return realEnc.raw, nil }
go
func encode(e encoder, metricRegistry metrics.Registry) ([]byte, error) { if e == nil { return nil, nil } var prepEnc prepEncoder var realEnc realEncoder err := e.encode(&prepEnc) if err != nil { return nil, err } if prepEnc.length < 0 || prepEnc.length > int(MaxRequestSize) { return nil, PacketEncodingError{fmt.Sprintf("invalid request size (%d)", prepEnc.length)} } realEnc.raw = make([]byte, prepEnc.length) realEnc.registry = metricRegistry err = e.encode(&realEnc) if err != nil { return nil, err } return realEnc.raw, nil }
[ "func", "encode", "(", "e", "encoder", ",", "metricRegistry", "metrics", ".", "Registry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "e", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "var", "prepEnc", "prepEncoder", "\n", "var", "realEnc", "realEncoder", "\n\n", "err", ":=", "e", ".", "encode", "(", "&", "prepEnc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "prepEnc", ".", "length", "<", "0", "||", "prepEnc", ".", "length", ">", "int", "(", "MaxRequestSize", ")", "{", "return", "nil", ",", "PacketEncodingError", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prepEnc", ".", "length", ")", "}", "\n", "}", "\n\n", "realEnc", ".", "raw", "=", "make", "(", "[", "]", "byte", ",", "prepEnc", ".", "length", ")", "\n", "realEnc", ".", "registry", "=", "metricRegistry", "\n", "err", "=", "e", ".", "encode", "(", "&", "realEnc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "realEnc", ".", "raw", ",", "nil", "\n", "}" ]
// Encode takes an Encoder and turns it into bytes while potentially recording metrics.
[ "Encode", "takes", "an", "Encoder", "and", "turns", "it", "into", "bytes", "while", "potentially", "recording", "metrics", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/encoder_decoder.go#L16-L41
158,209
Shopify/sarama
encoder_decoder.go
decode
func decode(buf []byte, in decoder) error { if buf == nil { return nil } helper := realDecoder{raw: buf} err := in.decode(&helper) if err != nil { return err } if helper.off != len(buf) { return PacketDecodingError{"invalid length"} } return nil }
go
func decode(buf []byte, in decoder) error { if buf == nil { return nil } helper := realDecoder{raw: buf} err := in.decode(&helper) if err != nil { return err } if helper.off != len(buf) { return PacketDecodingError{"invalid length"} } return nil }
[ "func", "decode", "(", "buf", "[", "]", "byte", ",", "in", "decoder", ")", "error", "{", "if", "buf", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "helper", ":=", "realDecoder", "{", "raw", ":", "buf", "}", "\n", "err", ":=", "in", ".", "decode", "(", "&", "helper", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "helper", ".", "off", "!=", "len", "(", "buf", ")", "{", "return", "PacketDecodingError", "{", "\"", "\"", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Decode takes bytes and a Decoder and fills the fields of the decoder from the bytes, // interpreted using Kafka's encoding rules.
[ "Decode", "takes", "bytes", "and", "a", "Decoder", "and", "fills", "the", "fields", "of", "the", "decoder", "from", "the", "bytes", "interpreted", "using", "Kafka", "s", "encoding", "rules", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/encoder_decoder.go#L55-L71
158,210
Shopify/sarama
mocks/sync_producer.go
SendMessages
func (sp *SyncProducer) SendMessages(msgs []*sarama.ProducerMessage) error { sp.l.Lock() defer sp.l.Unlock() if len(sp.expectations) >= len(msgs) { expectations := sp.expectations[0:len(msgs)] sp.expectations = sp.expectations[len(msgs):] for i, expectation := range expectations { if expectation.CheckFunction != nil { val, err := msgs[i].Value.Encode() if err != nil { sp.t.Errorf("Input message encoding failed: %s", err.Error()) return err } errCheck := expectation.CheckFunction(val) if errCheck != nil { sp.t.Errorf("Check function returned an error: %s", errCheck.Error()) return errCheck } } if expectation.Result != errProduceSuccess { return expectation.Result } } return nil } sp.t.Errorf("Insufficient expectations set on this mock producer to handle the input messages.") return errOutOfExpectations }
go
func (sp *SyncProducer) SendMessages(msgs []*sarama.ProducerMessage) error { sp.l.Lock() defer sp.l.Unlock() if len(sp.expectations) >= len(msgs) { expectations := sp.expectations[0:len(msgs)] sp.expectations = sp.expectations[len(msgs):] for i, expectation := range expectations { if expectation.CheckFunction != nil { val, err := msgs[i].Value.Encode() if err != nil { sp.t.Errorf("Input message encoding failed: %s", err.Error()) return err } errCheck := expectation.CheckFunction(val) if errCheck != nil { sp.t.Errorf("Check function returned an error: %s", errCheck.Error()) return errCheck } } if expectation.Result != errProduceSuccess { return expectation.Result } } return nil } sp.t.Errorf("Insufficient expectations set on this mock producer to handle the input messages.") return errOutOfExpectations }
[ "func", "(", "sp", "*", "SyncProducer", ")", "SendMessages", "(", "msgs", "[", "]", "*", "sarama", ".", "ProducerMessage", ")", "error", "{", "sp", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "sp", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "sp", ".", "expectations", ")", ">=", "len", "(", "msgs", ")", "{", "expectations", ":=", "sp", ".", "expectations", "[", "0", ":", "len", "(", "msgs", ")", "]", "\n", "sp", ".", "expectations", "=", "sp", ".", "expectations", "[", "len", "(", "msgs", ")", ":", "]", "\n\n", "for", "i", ",", "expectation", ":=", "range", "expectations", "{", "if", "expectation", ".", "CheckFunction", "!=", "nil", "{", "val", ",", "err", ":=", "msgs", "[", "i", "]", ".", "Value", ".", "Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "sp", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n", "errCheck", ":=", "expectation", ".", "CheckFunction", "(", "val", ")", "\n", "if", "errCheck", "!=", "nil", "{", "sp", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "errCheck", ".", "Error", "(", ")", ")", "\n", "return", "errCheck", "\n", "}", "\n", "}", "\n", "if", "expectation", ".", "Result", "!=", "errProduceSuccess", "{", "return", "expectation", ".", "Result", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "sp", ".", "t", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "errOutOfExpectations", "\n", "}" ]
// SendMessages corresponds with the SendMessages method of sarama's SyncProducer implementation. // You have to set expectations on the mock producer before calling SendMessages, so it knows // how to handle them. If there is no more remaining expectations when SendMessages is called, // the mock producer will write an error to the test state object.
[ "SendMessages", "corresponds", "with", "the", "SendMessages", "method", "of", "sarama", "s", "SyncProducer", "implementation", ".", "You", "have", "to", "set", "expectations", "on", "the", "mock", "producer", "before", "calling", "SendMessages", "so", "it", "knows", "how", "to", "handle", "them", ".", "If", "there", "is", "no", "more", "remaining", "expectations", "when", "SendMessages", "is", "called", "the", "mock", "producer", "will", "write", "an", "error", "to", "the", "test", "state", "object", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/sync_producer.go#L76-L105
158,211
Shopify/sarama
mocks/sync_producer.go
Close
func (sp *SyncProducer) Close() error { sp.l.Lock() defer sp.l.Unlock() if len(sp.expectations) > 0 { sp.t.Errorf("Expected to exhaust all expectations, but %d are left.", len(sp.expectations)) } return nil }
go
func (sp *SyncProducer) Close() error { sp.l.Lock() defer sp.l.Unlock() if len(sp.expectations) > 0 { sp.t.Errorf("Expected to exhaust all expectations, but %d are left.", len(sp.expectations)) } return nil }
[ "func", "(", "sp", "*", "SyncProducer", ")", "Close", "(", ")", "error", "{", "sp", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "sp", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "sp", ".", "expectations", ")", ">", "0", "{", "sp", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "sp", ".", "expectations", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Close corresponds with the Close method of sarama's SyncProducer implementation. // By closing a mock syncproducer, you also tell it that no more SendMessage calls will follow, // so it will write an error to the test state if there's any remaining expectations.
[ "Close", "corresponds", "with", "the", "Close", "method", "of", "sarama", "s", "SyncProducer", "implementation", ".", "By", "closing", "a", "mock", "syncproducer", "you", "also", "tell", "it", "that", "no", "more", "SendMessage", "calls", "will", "follow", "so", "it", "will", "write", "an", "error", "to", "the", "test", "state", "if", "there", "s", "any", "remaining", "expectations", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/sync_producer.go#L110-L119
158,212
Shopify/sarama
mocks/sync_producer.go
ExpectSendMessageWithCheckerFunctionAndFail
func (sp *SyncProducer) ExpectSendMessageWithCheckerFunctionAndFail(cf ValueChecker, err error) { sp.l.Lock() defer sp.l.Unlock() sp.expectations = append(sp.expectations, &producerExpectation{Result: err, CheckFunction: cf}) }
go
func (sp *SyncProducer) ExpectSendMessageWithCheckerFunctionAndFail(cf ValueChecker, err error) { sp.l.Lock() defer sp.l.Unlock() sp.expectations = append(sp.expectations, &producerExpectation{Result: err, CheckFunction: cf}) }
[ "func", "(", "sp", "*", "SyncProducer", ")", "ExpectSendMessageWithCheckerFunctionAndFail", "(", "cf", "ValueChecker", ",", "err", "error", ")", "{", "sp", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "sp", ".", "l", ".", "Unlock", "(", ")", "\n", "sp", ".", "expectations", "=", "append", "(", "sp", ".", "expectations", ",", "&", "producerExpectation", "{", "Result", ":", "err", ",", "CheckFunction", ":", "cf", "}", ")", "\n", "}" ]
// ExpectSendMessageWithCheckerFunctionAndFail sets an expectation on the mock producer that SendMessage will be // called. The mock producer will first call the given function to check the message value. // It will cascade the error of the function, if any, or handle the message as if it failed // to produce successfully, i.e. by returning the provided error.
[ "ExpectSendMessageWithCheckerFunctionAndFail", "sets", "an", "expectation", "on", "the", "mock", "producer", "that", "SendMessage", "will", "be", "called", ".", "The", "mock", "producer", "will", "first", "call", "the", "given", "function", "to", "check", "the", "message", "value", ".", "It", "will", "cascade", "the", "error", "of", "the", "function", "if", "any", "or", "handle", "the", "message", "as", "if", "it", "failed", "to", "produce", "successfully", "i", ".", "e", ".", "by", "returning", "the", "provided", "error", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/sync_producer.go#L139-L143
158,213
Shopify/sarama
utils.go
ParseKafkaVersion
func ParseKafkaVersion(s string) (KafkaVersion, error) { if len(s) < 5 { return MinVersion, fmt.Errorf("invalid version `%s`", s) } var major, minor, veryMinor, patch uint var err error if s[0] == '0' { err = scanKafkaVersion(s, `^0\.\d+\.\d+\.\d+$`, "0.%d.%d.%d", [3]*uint{&minor, &veryMinor, &patch}) } else { err = scanKafkaVersion(s, `^\d+\.\d+\.\d+$`, "%d.%d.%d", [3]*uint{&major, &minor, &veryMinor}) } if err != nil { return MinVersion, err } return newKafkaVersion(major, minor, veryMinor, patch), nil }
go
func ParseKafkaVersion(s string) (KafkaVersion, error) { if len(s) < 5 { return MinVersion, fmt.Errorf("invalid version `%s`", s) } var major, minor, veryMinor, patch uint var err error if s[0] == '0' { err = scanKafkaVersion(s, `^0\.\d+\.\d+\.\d+$`, "0.%d.%d.%d", [3]*uint{&minor, &veryMinor, &patch}) } else { err = scanKafkaVersion(s, `^\d+\.\d+\.\d+$`, "%d.%d.%d", [3]*uint{&major, &minor, &veryMinor}) } if err != nil { return MinVersion, err } return newKafkaVersion(major, minor, veryMinor, patch), nil }
[ "func", "ParseKafkaVersion", "(", "s", "string", ")", "(", "KafkaVersion", ",", "error", ")", "{", "if", "len", "(", "s", ")", "<", "5", "{", "return", "MinVersion", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "var", "major", ",", "minor", ",", "veryMinor", ",", "patch", "uint", "\n", "var", "err", "error", "\n", "if", "s", "[", "0", "]", "==", "'0'", "{", "err", "=", "scanKafkaVersion", "(", "s", ",", "`^0\\.\\d+\\.\\d+\\.\\d+$`", ",", "\"", "\"", ",", "[", "3", "]", "*", "uint", "{", "&", "minor", ",", "&", "veryMinor", ",", "&", "patch", "}", ")", "\n", "}", "else", "{", "err", "=", "scanKafkaVersion", "(", "s", ",", "`^\\d+\\.\\d+\\.\\d+$`", ",", "\"", "\"", ",", "[", "3", "]", "*", "uint", "{", "&", "major", ",", "&", "minor", ",", "&", "veryMinor", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "MinVersion", ",", "err", "\n", "}", "\n", "return", "newKafkaVersion", "(", "major", ",", "minor", ",", "veryMinor", ",", "patch", ")", ",", "nil", "\n", "}" ]
//ParseKafkaVersion parses and returns kafka version or error from a string
[ "ParseKafkaVersion", "parses", "and", "returns", "kafka", "version", "or", "error", "from", "a", "string" ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/utils.go#L192-L207
158,214
Shopify/sarama
mocks/async_producer.go
ExpectInputWithCheckerFunctionAndFail
func (mp *AsyncProducer) ExpectInputWithCheckerFunctionAndFail(cf ValueChecker, err error) { mp.l.Lock() defer mp.l.Unlock() mp.expectations = append(mp.expectations, &producerExpectation{Result: err, CheckFunction: cf}) }
go
func (mp *AsyncProducer) ExpectInputWithCheckerFunctionAndFail(cf ValueChecker, err error) { mp.l.Lock() defer mp.l.Unlock() mp.expectations = append(mp.expectations, &producerExpectation{Result: err, CheckFunction: cf}) }
[ "func", "(", "mp", "*", "AsyncProducer", ")", "ExpectInputWithCheckerFunctionAndFail", "(", "cf", "ValueChecker", ",", "err", "error", ")", "{", "mp", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "mp", ".", "l", ".", "Unlock", "(", ")", "\n", "mp", ".", "expectations", "=", "append", "(", "mp", ".", "expectations", ",", "&", "producerExpectation", "{", "Result", ":", "err", ",", "CheckFunction", ":", "cf", "}", ")", "\n", "}" ]
// ExpectInputWithCheckerFunctionAndFail sets an expectation on the mock producer that a message // will be provided on the input channel. The mock producer will first call the given function to // check the message value. If an error is returned it will be made available on the Errors channel // otherwise the mock will handle the message as if it failed to produce successfully. This means // it will make a ProducerError available on the Errors channel.
[ "ExpectInputWithCheckerFunctionAndFail", "sets", "an", "expectation", "on", "the", "mock", "producer", "that", "a", "message", "will", "be", "provided", "on", "the", "input", "channel", ".", "The", "mock", "producer", "will", "first", "call", "the", "given", "function", "to", "check", "the", "message", "value", ".", "If", "an", "error", "is", "returned", "it", "will", "be", "made", "available", "on", "the", "Errors", "channel", "otherwise", "the", "mock", "will", "handle", "the", "message", "as", "if", "it", "failed", "to", "produce", "successfully", ".", "This", "means", "it", "will", "make", "a", "ProducerError", "available", "on", "the", "Errors", "channel", "." ]
ea9ab1c316850bee881a07bb2555ee8a685cd4b6
https://github.com/Shopify/sarama/blob/ea9ab1c316850bee881a07bb2555ee8a685cd4b6/mocks/async_producer.go#L154-L158
158,215
spf13/viper
util.go
toCaseInsensitiveValue
func toCaseInsensitiveValue(value interface{}) interface{} { switch v := value.(type) { case map[interface{}]interface{}: value = copyAndInsensitiviseMap(cast.ToStringMap(v)) case map[string]interface{}: value = copyAndInsensitiviseMap(v) } return value }
go
func toCaseInsensitiveValue(value interface{}) interface{} { switch v := value.(type) { case map[interface{}]interface{}: value = copyAndInsensitiviseMap(cast.ToStringMap(v)) case map[string]interface{}: value = copyAndInsensitiviseMap(v) } return value }
[ "func", "toCaseInsensitiveValue", "(", "value", "interface", "{", "}", ")", "interface", "{", "}", "{", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ":", "value", "=", "copyAndInsensitiviseMap", "(", "cast", ".", "ToStringMap", "(", "v", ")", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "value", "=", "copyAndInsensitiviseMap", "(", "v", ")", "\n", "}", "\n\n", "return", "value", "\n", "}" ]
// toCaseInsensitiveValue checks if the value is a map; // if so, create a copy and lower-case the keys recursively.
[ "toCaseInsensitiveValue", "checks", "if", "the", "value", "is", "a", "map", ";", "if", "so", "create", "a", "copy", "and", "lower", "-", "case", "the", "keys", "recursively", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/util.go#L38-L47
158,216
spf13/viper
util.go
copyAndInsensitiviseMap
func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} { nm := make(map[string]interface{}) for key, val := range m { lkey := strings.ToLower(key) switch v := val.(type) { case map[interface{}]interface{}: nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v)) case map[string]interface{}: nm[lkey] = copyAndInsensitiviseMap(v) default: nm[lkey] = v } } return nm }
go
func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} { nm := make(map[string]interface{}) for key, val := range m { lkey := strings.ToLower(key) switch v := val.(type) { case map[interface{}]interface{}: nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v)) case map[string]interface{}: nm[lkey] = copyAndInsensitiviseMap(v) default: nm[lkey] = v } } return nm }
[ "func", "copyAndInsensitiviseMap", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "nm", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "for", "key", ",", "val", ":=", "range", "m", "{", "lkey", ":=", "strings", ".", "ToLower", "(", "key", ")", "\n", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ":", "nm", "[", "lkey", "]", "=", "copyAndInsensitiviseMap", "(", "cast", ".", "ToStringMap", "(", "v", ")", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "nm", "[", "lkey", "]", "=", "copyAndInsensitiviseMap", "(", "v", ")", "\n", "default", ":", "nm", "[", "lkey", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "nm", "\n", "}" ]
// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of // any map it makes case insensitive.
[ "copyAndInsensitiviseMap", "behaves", "like", "insensitiviseMap", "but", "creates", "a", "copy", "of", "any", "map", "it", "makes", "case", "insensitive", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/util.go#L51-L67
158,217
spf13/viper
util.go
parseSizeInBytes
func parseSizeInBytes(sizeStr string) uint { sizeStr = strings.TrimSpace(sizeStr) lastChar := len(sizeStr) - 1 multiplier := uint(1) if lastChar > 0 { if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' { if lastChar > 1 { switch unicode.ToLower(rune(sizeStr[lastChar-1])) { case 'k': multiplier = 1 << 10 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'm': multiplier = 1 << 20 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'g': multiplier = 1 << 30 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) default: multiplier = 1 sizeStr = strings.TrimSpace(sizeStr[:lastChar]) } } } } size := cast.ToInt(sizeStr) if size < 0 { size = 0 } return safeMul(uint(size), multiplier) }
go
func parseSizeInBytes(sizeStr string) uint { sizeStr = strings.TrimSpace(sizeStr) lastChar := len(sizeStr) - 1 multiplier := uint(1) if lastChar > 0 { if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' { if lastChar > 1 { switch unicode.ToLower(rune(sizeStr[lastChar-1])) { case 'k': multiplier = 1 << 10 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'm': multiplier = 1 << 20 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'g': multiplier = 1 << 30 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) default: multiplier = 1 sizeStr = strings.TrimSpace(sizeStr[:lastChar]) } } } } size := cast.ToInt(sizeStr) if size < 0 { size = 0 } return safeMul(uint(size), multiplier) }
[ "func", "parseSizeInBytes", "(", "sizeStr", "string", ")", "uint", "{", "sizeStr", "=", "strings", ".", "TrimSpace", "(", "sizeStr", ")", "\n", "lastChar", ":=", "len", "(", "sizeStr", ")", "-", "1", "\n", "multiplier", ":=", "uint", "(", "1", ")", "\n\n", "if", "lastChar", ">", "0", "{", "if", "sizeStr", "[", "lastChar", "]", "==", "'b'", "||", "sizeStr", "[", "lastChar", "]", "==", "'B'", "{", "if", "lastChar", ">", "1", "{", "switch", "unicode", ".", "ToLower", "(", "rune", "(", "sizeStr", "[", "lastChar", "-", "1", "]", ")", ")", "{", "case", "'k'", ":", "multiplier", "=", "1", "<<", "10", "\n", "sizeStr", "=", "strings", ".", "TrimSpace", "(", "sizeStr", "[", ":", "lastChar", "-", "1", "]", ")", "\n", "case", "'m'", ":", "multiplier", "=", "1", "<<", "20", "\n", "sizeStr", "=", "strings", ".", "TrimSpace", "(", "sizeStr", "[", ":", "lastChar", "-", "1", "]", ")", "\n", "case", "'g'", ":", "multiplier", "=", "1", "<<", "30", "\n", "sizeStr", "=", "strings", ".", "TrimSpace", "(", "sizeStr", "[", ":", "lastChar", "-", "1", "]", ")", "\n", "default", ":", "multiplier", "=", "1", "\n", "sizeStr", "=", "strings", ".", "TrimSpace", "(", "sizeStr", "[", ":", "lastChar", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "size", ":=", "cast", ".", "ToInt", "(", "sizeStr", ")", "\n", "if", "size", "<", "0", "{", "size", "=", "0", "\n", "}", "\n\n", "return", "safeMul", "(", "uint", "(", "size", ")", ",", "multiplier", ")", "\n", "}" ]
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
[ "parseSizeInBytes", "converts", "strings", "like", "1GB", "or", "12", "mb", "into", "an", "unsigned", "integer", "number", "of", "bytes" ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/util.go#L158-L190
158,218
spf13/viper
viper.go
Error
func (fnfe ConfigFileNotFoundError) Error() string { return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations) }
go
func (fnfe ConfigFileNotFoundError) Error() string { return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations) }
[ "func", "(", "fnfe", "ConfigFileNotFoundError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fnfe", ".", "name", ",", "fnfe", ".", "locations", ")", "\n", "}" ]
// Error returns the formatted configuration error.
[ "Error", "returns", "the", "formatted", "configuration", "error", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L113-L115
158,219
spf13/viper
viper.go
New
func New() *Viper { v := new(Viper) v.keyDelim = "." v.configName = "config" v.configPermissions = os.FileMode(0644) v.fs = afero.NewOsFs() v.config = make(map[string]interface{}) v.override = make(map[string]interface{}) v.defaults = make(map[string]interface{}) v.kvstore = make(map[string]interface{}) v.pflags = make(map[string]FlagValue) v.env = make(map[string]string) v.aliases = make(map[string]string) v.typeByDefValue = false return v }
go
func New() *Viper { v := new(Viper) v.keyDelim = "." v.configName = "config" v.configPermissions = os.FileMode(0644) v.fs = afero.NewOsFs() v.config = make(map[string]interface{}) v.override = make(map[string]interface{}) v.defaults = make(map[string]interface{}) v.kvstore = make(map[string]interface{}) v.pflags = make(map[string]FlagValue) v.env = make(map[string]string) v.aliases = make(map[string]string) v.typeByDefValue = false return v }
[ "func", "New", "(", ")", "*", "Viper", "{", "v", ":=", "new", "(", "Viper", ")", "\n", "v", ".", "keyDelim", "=", "\"", "\"", "\n", "v", ".", "configName", "=", "\"", "\"", "\n", "v", ".", "configPermissions", "=", "os", ".", "FileMode", "(", "0644", ")", "\n", "v", ".", "fs", "=", "afero", ".", "NewOsFs", "(", ")", "\n", "v", ".", "config", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "v", ".", "override", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "v", ".", "defaults", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "v", ".", "kvstore", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "v", ".", "pflags", "=", "make", "(", "map", "[", "string", "]", "FlagValue", ")", "\n", "v", ".", "env", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "v", ".", "aliases", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "v", ".", "typeByDefValue", "=", "false", "\n\n", "return", "v", "\n", "}" ]
// New returns an initialized Viper instance.
[ "New", "returns", "an", "initialized", "Viper", "instance", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L210-L226
158,220
spf13/viper
viper.go
UnmarshalKey
func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalKey(key, rawVal, opts...) }
go
func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalKey(key, rawVal, opts...) }
[ "func", "UnmarshalKey", "(", "key", "string", ",", "rawVal", "interface", "{", "}", ",", "opts", "...", "DecoderConfigOption", ")", "error", "{", "return", "v", ".", "UnmarshalKey", "(", "key", ",", "rawVal", ",", "opts", "...", ")", "\n", "}" ]
// UnmarshalKey takes a single key and unmarshals it into a Struct.
[ "UnmarshalKey", "takes", "a", "single", "key", "and", "unmarshals", "it", "into", "a", "Struct", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L830-L832
158,221
spf13/viper
viper.go
defaultDecoderConfig
func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig { c := &mapstructure.DecoderConfig{ Metadata: nil, Result: output, WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToSliceHookFunc(","), ), } for _, opt := range opts { opt(c) } return c }
go
func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig { c := &mapstructure.DecoderConfig{ Metadata: nil, Result: output, WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToSliceHookFunc(","), ), } for _, opt := range opts { opt(c) } return c }
[ "func", "defaultDecoderConfig", "(", "output", "interface", "{", "}", ",", "opts", "...", "DecoderConfigOption", ")", "*", "mapstructure", ".", "DecoderConfig", "{", "c", ":=", "&", "mapstructure", ".", "DecoderConfig", "{", "Metadata", ":", "nil", ",", "Result", ":", "output", ",", "WeaklyTypedInput", ":", "true", ",", "DecodeHook", ":", "mapstructure", ".", "ComposeDecodeHookFunc", "(", "mapstructure", ".", "StringToTimeDurationHookFunc", "(", ")", ",", "mapstructure", ".", "StringToSliceHookFunc", "(", "\"", "\"", ")", ",", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "c", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot // of time.Duration values & string slices
[ "defaultDecoderConfig", "returns", "default", "mapsstructure", ".", "DecoderConfig", "with", "suppot", "of", "time", ".", "Duration", "values", "&", "string", "slices" ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L860-L874
158,222
spf13/viper
viper.go
decode
func decode(input interface{}, config *mapstructure.DecoderConfig) error { decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } return decoder.Decode(input) }
go
func decode(input interface{}, config *mapstructure.DecoderConfig) error { decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } return decoder.Decode(input) }
[ "func", "decode", "(", "input", "interface", "{", "}", ",", "config", "*", "mapstructure", ".", "DecoderConfig", ")", "error", "{", "decoder", ",", "err", ":=", "mapstructure", ".", "NewDecoder", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "decoder", ".", "Decode", "(", "input", ")", "\n", "}" ]
// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
[ "A", "wrapper", "around", "mapstructure", ".", "Decode", "that", "mimics", "the", "WeakDecode", "functionality" ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L877-L883
158,223
spf13/viper
viper.go
UnmarshalExact
func (v *Viper) UnmarshalExact(rawVal interface{}) error { config := defaultDecoderConfig(rawVal) config.ErrorUnused = true err := decode(v.AllSettings(), config) if err != nil { return err } return nil }
go
func (v *Viper) UnmarshalExact(rawVal interface{}) error { config := defaultDecoderConfig(rawVal) config.ErrorUnused = true err := decode(v.AllSettings(), config) if err != nil { return err } return nil }
[ "func", "(", "v", "*", "Viper", ")", "UnmarshalExact", "(", "rawVal", "interface", "{", "}", ")", "error", "{", "config", ":=", "defaultDecoderConfig", "(", "rawVal", ")", "\n", "config", ".", "ErrorUnused", "=", "true", "\n\n", "err", ":=", "decode", "(", "v", ".", "AllSettings", "(", ")", ",", "config", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent // in the destination struct.
[ "UnmarshalExact", "unmarshals", "the", "config", "into", "a", "Struct", "erroring", "if", "a", "field", "is", "nonexistent", "in", "the", "destination", "struct", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L887-L898
158,224
spf13/viper
viper.go
unmarshalReader
func unmarshalReader(in io.Reader, c map[string]interface{}) error { return v.unmarshalReader(in, c) }
go
func unmarshalReader(in io.Reader, c map[string]interface{}) error { return v.unmarshalReader(in, c) }
[ "func", "unmarshalReader", "(", "in", "io", ".", "Reader", ",", "c", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "return", "v", ".", "unmarshalReader", "(", "in", ",", "c", ")", "\n", "}" ]
// Unmarshal a Reader into a map. // Should probably be an unexported function.
[ "Unmarshal", "a", "Reader", "into", "a", "map", ".", "Should", "probably", "be", "an", "unexported", "function", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L1366-L1368
158,225
spf13/viper
viper.go
marshalWriter
func marshalWriter(f afero.File, configType string) error { return v.marshalWriter(f, configType) }
go
func marshalWriter(f afero.File, configType string) error { return v.marshalWriter(f, configType) }
[ "func", "marshalWriter", "(", "f", "afero", ".", "File", ",", "configType", "string", ")", "error", "{", "return", "v", ".", "marshalWriter", "(", "f", ",", "configType", ")", "\n", "}" ]
// Marshal a map into Writer.
[ "Marshal", "a", "map", "into", "Writer", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L1425-L1427
158,226
spf13/viper
viper.go
mergeFlatMap
func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool { // scan keys outer: for k, _ := range m { path := strings.Split(k, v.keyDelim) // scan intermediate paths var parentKey string for i := 1; i < len(path); i++ { parentKey = strings.Join(path[0:i], v.keyDelim) if shadow[parentKey] { // path is shadowed, continue continue outer } } // add key shadow[strings.ToLower(k)] = true } return shadow }
go
func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool { // scan keys outer: for k, _ := range m { path := strings.Split(k, v.keyDelim) // scan intermediate paths var parentKey string for i := 1; i < len(path); i++ { parentKey = strings.Join(path[0:i], v.keyDelim) if shadow[parentKey] { // path is shadowed, continue continue outer } } // add key shadow[strings.ToLower(k)] = true } return shadow }
[ "func", "(", "v", "*", "Viper", ")", "mergeFlatMap", "(", "shadow", "map", "[", "string", "]", "bool", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "bool", "{", "// scan keys", "outer", ":", "for", "k", ",", "_", ":=", "range", "m", "{", "path", ":=", "strings", ".", "Split", "(", "k", ",", "v", ".", "keyDelim", ")", "\n", "// scan intermediate paths", "var", "parentKey", "string", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "path", ")", ";", "i", "++", "{", "parentKey", "=", "strings", ".", "Join", "(", "path", "[", "0", ":", "i", "]", ",", "v", ".", "keyDelim", ")", "\n", "if", "shadow", "[", "parentKey", "]", "{", "// path is shadowed, continue", "continue", "outer", "\n", "}", "\n", "}", "\n", "// add key", "shadow", "[", "strings", ".", "ToLower", "(", "k", ")", "]", "=", "true", "\n", "}", "\n", "return", "shadow", "\n", "}" ]
// mergeFlatMap merges the given maps, excluding values of the second map // shadowed by values from the first map.
[ "mergeFlatMap", "merges", "the", "given", "maps", "excluding", "values", "of", "the", "second", "map", "shadowed", "by", "values", "from", "the", "first", "map", "." ]
7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4
https://github.com/spf13/viper/blob/7a605a50e69cd1ea431c4a1e6eebe9b287ef6de4/viper.go#L1728-L1746
158,227
robfig/cron
constantdelay.go
Next
func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) }
go
func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) }
[ "func", "(", "schedule", "ConstantDelaySchedule", ")", "Next", "(", "t", "time", ".", "Time", ")", "time", ".", "Time", "{", "return", "t", ".", "Add", "(", "schedule", ".", "Delay", "-", "time", ".", "Duration", "(", "t", ".", "Nanosecond", "(", ")", ")", "*", "time", ".", "Nanosecond", ")", "\n", "}" ]
// Next returns the next time this should be run. // This rounds so that the next activation time will be on the second.
[ "Next", "returns", "the", "next", "time", "this", "should", "be", "run", ".", "This", "rounds", "so", "that", "the", "next", "activation", "time", "will", "be", "on", "the", "second", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/constantdelay.go#L25-L27
158,228
robfig/cron
cron.go
NewWithLocation
func NewWithLocation(location *time.Location) *Cron { return &Cron{ entries: nil, add: make(chan *Entry), stop: make(chan struct{}), snapshot: make(chan []*Entry), running: false, ErrorLog: nil, location: location, } }
go
func NewWithLocation(location *time.Location) *Cron { return &Cron{ entries: nil, add: make(chan *Entry), stop: make(chan struct{}), snapshot: make(chan []*Entry), running: false, ErrorLog: nil, location: location, } }
[ "func", "NewWithLocation", "(", "location", "*", "time", ".", "Location", ")", "*", "Cron", "{", "return", "&", "Cron", "{", "entries", ":", "nil", ",", "add", ":", "make", "(", "chan", "*", "Entry", ")", ",", "stop", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "snapshot", ":", "make", "(", "chan", "[", "]", "*", "Entry", ")", ",", "running", ":", "false", ",", "ErrorLog", ":", "nil", ",", "location", ":", "location", ",", "}", "\n", "}" ]
// NewWithLocation returns a new Cron job runner.
[ "NewWithLocation", "returns", "a", "new", "Cron", "job", "runner", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L77-L87
158,229
robfig/cron
cron.go
AddFunc
func (c *Cron) AddFunc(spec string, cmd func()) error { return c.AddJob(spec, FuncJob(cmd)) }
go
func (c *Cron) AddFunc(spec string, cmd func()) error { return c.AddJob(spec, FuncJob(cmd)) }
[ "func", "(", "c", "*", "Cron", ")", "AddFunc", "(", "spec", "string", ",", "cmd", "func", "(", ")", ")", "error", "{", "return", "c", ".", "AddJob", "(", "spec", ",", "FuncJob", "(", "cmd", ")", ")", "\n", "}" ]
// AddFunc adds a func to the Cron to be run on the given schedule.
[ "AddFunc", "adds", "a", "func", "to", "the", "Cron", "to", "be", "run", "on", "the", "given", "schedule", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L95-L97
158,230
robfig/cron
cron.go
AddJob
func (c *Cron) AddJob(spec string, cmd Job) error { schedule, err := Parse(spec) if err != nil { return err } c.Schedule(schedule, cmd) return nil }
go
func (c *Cron) AddJob(spec string, cmd Job) error { schedule, err := Parse(spec) if err != nil { return err } c.Schedule(schedule, cmd) return nil }
[ "func", "(", "c", "*", "Cron", ")", "AddJob", "(", "spec", "string", ",", "cmd", "Job", ")", "error", "{", "schedule", ",", "err", ":=", "Parse", "(", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "Schedule", "(", "schedule", ",", "cmd", ")", "\n", "return", "nil", "\n", "}" ]
// AddJob adds a Job to the Cron to be run on the given schedule.
[ "AddJob", "adds", "a", "Job", "to", "the", "Cron", "to", "be", "run", "on", "the", "given", "schedule", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L100-L107
158,231
robfig/cron
cron.go
Schedule
func (c *Cron) Schedule(schedule Schedule, cmd Job) { entry := &Entry{ Schedule: schedule, Job: cmd, } if !c.running { c.entries = append(c.entries, entry) return } c.add <- entry }
go
func (c *Cron) Schedule(schedule Schedule, cmd Job) { entry := &Entry{ Schedule: schedule, Job: cmd, } if !c.running { c.entries = append(c.entries, entry) return } c.add <- entry }
[ "func", "(", "c", "*", "Cron", ")", "Schedule", "(", "schedule", "Schedule", ",", "cmd", "Job", ")", "{", "entry", ":=", "&", "Entry", "{", "Schedule", ":", "schedule", ",", "Job", ":", "cmd", ",", "}", "\n", "if", "!", "c", ".", "running", "{", "c", ".", "entries", "=", "append", "(", "c", ".", "entries", ",", "entry", ")", "\n", "return", "\n", "}", "\n\n", "c", ".", "add", "<-", "entry", "\n", "}" ]
// Schedule adds a Job to the Cron to be run on the given schedule.
[ "Schedule", "adds", "a", "Job", "to", "the", "Cron", "to", "be", "run", "on", "the", "given", "schedule", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L110-L121
158,232
robfig/cron
cron.go
Entries
func (c *Cron) Entries() []*Entry { if c.running { c.snapshot <- nil x := <-c.snapshot return x } return c.entrySnapshot() }
go
func (c *Cron) Entries() []*Entry { if c.running { c.snapshot <- nil x := <-c.snapshot return x } return c.entrySnapshot() }
[ "func", "(", "c", "*", "Cron", ")", "Entries", "(", ")", "[", "]", "*", "Entry", "{", "if", "c", ".", "running", "{", "c", ".", "snapshot", "<-", "nil", "\n", "x", ":=", "<-", "c", ".", "snapshot", "\n", "return", "x", "\n", "}", "\n", "return", "c", ".", "entrySnapshot", "(", ")", "\n", "}" ]
// Entries returns a snapshot of the cron entries.
[ "Entries", "returns", "a", "snapshot", "of", "the", "cron", "entries", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L124-L131
158,233
robfig/cron
cron.go
Start
func (c *Cron) Start() { if c.running { return } c.running = true go c.run() }
go
func (c *Cron) Start() { if c.running { return } c.running = true go c.run() }
[ "func", "(", "c", "*", "Cron", ")", "Start", "(", ")", "{", "if", "c", ".", "running", "{", "return", "\n", "}", "\n", "c", ".", "running", "=", "true", "\n", "go", "c", ".", "run", "(", ")", "\n", "}" ]
// Start the cron scheduler in its own go-routine, or no-op if already started.
[ "Start", "the", "cron", "scheduler", "in", "its", "own", "go", "-", "routine", "or", "no", "-", "op", "if", "already", "started", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L139-L145
158,234
robfig/cron
cron.go
Run
func (c *Cron) Run() { if c.running { return } c.running = true c.run() }
go
func (c *Cron) Run() { if c.running { return } c.running = true c.run() }
[ "func", "(", "c", "*", "Cron", ")", "Run", "(", ")", "{", "if", "c", ".", "running", "{", "return", "\n", "}", "\n", "c", ".", "running", "=", "true", "\n", "c", ".", "run", "(", ")", "\n", "}" ]
// Run the cron scheduler, or no-op if already running.
[ "Run", "the", "cron", "scheduler", "or", "no", "-", "op", "if", "already", "running", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L148-L154
158,235
robfig/cron
cron.go
run
func (c *Cron) run() { // Figure out the next activation times for each entry. now := c.now() for _, entry := range c.entries { entry.Next = entry.Schedule.Next(now) } for { // Determine the next entry to run. sort.Sort(byTime(c.entries)) var timer *time.Timer if len(c.entries) == 0 || c.entries[0].Next.IsZero() { // If there are no entries yet, just sleep - it still handles new entries // and stop requests. timer = time.NewTimer(100000 * time.Hour) } else { timer = time.NewTimer(c.entries[0].Next.Sub(now)) } for { select { case now = <-timer.C: now = now.In(c.location) // Run every entry whose next time was less than now for _, e := range c.entries { if e.Next.After(now) || e.Next.IsZero() { break } go c.runWithRecovery(e.Job) e.Prev = e.Next e.Next = e.Schedule.Next(now) } case newEntry := <-c.add: timer.Stop() now = c.now() newEntry.Next = newEntry.Schedule.Next(now) c.entries = append(c.entries, newEntry) case <-c.snapshot: c.snapshot <- c.entrySnapshot() continue case <-c.stop: timer.Stop() return } break } } }
go
func (c *Cron) run() { // Figure out the next activation times for each entry. now := c.now() for _, entry := range c.entries { entry.Next = entry.Schedule.Next(now) } for { // Determine the next entry to run. sort.Sort(byTime(c.entries)) var timer *time.Timer if len(c.entries) == 0 || c.entries[0].Next.IsZero() { // If there are no entries yet, just sleep - it still handles new entries // and stop requests. timer = time.NewTimer(100000 * time.Hour) } else { timer = time.NewTimer(c.entries[0].Next.Sub(now)) } for { select { case now = <-timer.C: now = now.In(c.location) // Run every entry whose next time was less than now for _, e := range c.entries { if e.Next.After(now) || e.Next.IsZero() { break } go c.runWithRecovery(e.Job) e.Prev = e.Next e.Next = e.Schedule.Next(now) } case newEntry := <-c.add: timer.Stop() now = c.now() newEntry.Next = newEntry.Schedule.Next(now) c.entries = append(c.entries, newEntry) case <-c.snapshot: c.snapshot <- c.entrySnapshot() continue case <-c.stop: timer.Stop() return } break } } }
[ "func", "(", "c", "*", "Cron", ")", "run", "(", ")", "{", "// Figure out the next activation times for each entry.", "now", ":=", "c", ".", "now", "(", ")", "\n", "for", "_", ",", "entry", ":=", "range", "c", ".", "entries", "{", "entry", ".", "Next", "=", "entry", ".", "Schedule", ".", "Next", "(", "now", ")", "\n", "}", "\n\n", "for", "{", "// Determine the next entry to run.", "sort", ".", "Sort", "(", "byTime", "(", "c", ".", "entries", ")", ")", "\n\n", "var", "timer", "*", "time", ".", "Timer", "\n", "if", "len", "(", "c", ".", "entries", ")", "==", "0", "||", "c", ".", "entries", "[", "0", "]", ".", "Next", ".", "IsZero", "(", ")", "{", "// If there are no entries yet, just sleep - it still handles new entries", "// and stop requests.", "timer", "=", "time", ".", "NewTimer", "(", "100000", "*", "time", ".", "Hour", ")", "\n", "}", "else", "{", "timer", "=", "time", ".", "NewTimer", "(", "c", ".", "entries", "[", "0", "]", ".", "Next", ".", "Sub", "(", "now", ")", ")", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "now", "=", "<-", "timer", ".", "C", ":", "now", "=", "now", ".", "In", "(", "c", ".", "location", ")", "\n", "// Run every entry whose next time was less than now", "for", "_", ",", "e", ":=", "range", "c", ".", "entries", "{", "if", "e", ".", "Next", ".", "After", "(", "now", ")", "||", "e", ".", "Next", ".", "IsZero", "(", ")", "{", "break", "\n", "}", "\n", "go", "c", ".", "runWithRecovery", "(", "e", ".", "Job", ")", "\n", "e", ".", "Prev", "=", "e", ".", "Next", "\n", "e", ".", "Next", "=", "e", ".", "Schedule", ".", "Next", "(", "now", ")", "\n", "}", "\n\n", "case", "newEntry", ":=", "<-", "c", ".", "add", ":", "timer", ".", "Stop", "(", ")", "\n", "now", "=", "c", ".", "now", "(", ")", "\n", "newEntry", ".", "Next", "=", "newEntry", ".", "Schedule", ".", "Next", "(", "now", ")", "\n", "c", ".", "entries", "=", "append", "(", "c", ".", "entries", ",", "newEntry", ")", "\n\n", "case", "<-", "c", ".", "snapshot", ":", "c", ".", "snapshot", "<-", "c", ".", "entrySnapshot", "(", ")", "\n", "continue", "\n\n", "case", "<-", "c", ".", "stop", ":", "timer", ".", "Stop", "(", ")", "\n", "return", "\n", "}", "\n\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Run the scheduler. this is private just due to the need to synchronize // access to the 'running' state variable.
[ "Run", "the", "scheduler", ".", "this", "is", "private", "just", "due", "to", "the", "need", "to", "synchronize", "access", "to", "the", "running", "state", "variable", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L170-L222
158,236
robfig/cron
cron.go
logf
func (c *Cron) logf(format string, args ...interface{}) { if c.ErrorLog != nil { c.ErrorLog.Printf(format, args...) } else { log.Printf(format, args...) } }
go
func (c *Cron) logf(format string, args ...interface{}) { if c.ErrorLog != nil { c.ErrorLog.Printf(format, args...) } else { log.Printf(format, args...) } }
[ "func", "(", "c", "*", "Cron", ")", "logf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "c", ".", "ErrorLog", "!=", "nil", "{", "c", ".", "ErrorLog", ".", "Printf", "(", "format", ",", "args", "...", ")", "\n", "}", "else", "{", "log", ".", "Printf", "(", "format", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// Logs an error to stderr or to the configured error log
[ "Logs", "an", "error", "to", "stderr", "or", "to", "the", "configured", "error", "log" ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L225-L231
158,237
robfig/cron
cron.go
entrySnapshot
func (c *Cron) entrySnapshot() []*Entry { entries := []*Entry{} for _, e := range c.entries { entries = append(entries, &Entry{ Schedule: e.Schedule, Next: e.Next, Prev: e.Prev, Job: e.Job, }) } return entries }
go
func (c *Cron) entrySnapshot() []*Entry { entries := []*Entry{} for _, e := range c.entries { entries = append(entries, &Entry{ Schedule: e.Schedule, Next: e.Next, Prev: e.Prev, Job: e.Job, }) } return entries }
[ "func", "(", "c", "*", "Cron", ")", "entrySnapshot", "(", ")", "[", "]", "*", "Entry", "{", "entries", ":=", "[", "]", "*", "Entry", "{", "}", "\n", "for", "_", ",", "e", ":=", "range", "c", ".", "entries", "{", "entries", "=", "append", "(", "entries", ",", "&", "Entry", "{", "Schedule", ":", "e", ".", "Schedule", ",", "Next", ":", "e", ".", "Next", ",", "Prev", ":", "e", ".", "Prev", ",", "Job", ":", "e", ".", "Job", ",", "}", ")", "\n", "}", "\n", "return", "entries", "\n", "}" ]
// entrySnapshot returns a copy of the current cron entry list.
[ "entrySnapshot", "returns", "a", "copy", "of", "the", "current", "cron", "entry", "list", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L243-L254
158,238
robfig/cron
cron.go
now
func (c *Cron) now() time.Time { return time.Now().In(c.location) }
go
func (c *Cron) now() time.Time { return time.Now().In(c.location) }
[ "func", "(", "c", "*", "Cron", ")", "now", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Now", "(", ")", ".", "In", "(", "c", ".", "location", ")", "\n", "}" ]
// now returns current time in c location
[ "now", "returns", "current", "time", "in", "c", "location" ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/cron.go#L257-L259
158,239
robfig/cron
parser.go
Parse
func (p Parser) Parse(spec string) (Schedule, error) { if len(spec) == 0 { return nil, fmt.Errorf("Empty spec string") } if spec[0] == '@' && p.options&Descriptor > 0 { return parseDescriptor(spec) } // Figure out how many fields we need max := 0 for _, place := range places { if p.options&place > 0 { max++ } } min := max - p.optionals // Split fields on whitespace fields := strings.Fields(spec) // Validate number of fields if count := len(fields); count < min || count > max { if min == max { return nil, fmt.Errorf("Expected exactly %d fields, found %d: %s", min, count, spec) } return nil, fmt.Errorf("Expected %d to %d fields, found %d: %s", min, max, count, spec) } // Fill in missing fields fields = expandFields(fields, p.options) var err error field := func(field string, r bounds) uint64 { if err != nil { return 0 } var bits uint64 bits, err = getField(field, r) return bits } var ( second = field(fields[0], seconds) minute = field(fields[1], minutes) hour = field(fields[2], hours) dayofmonth = field(fields[3], dom) month = field(fields[4], months) dayofweek = field(fields[5], dow) ) if err != nil { return nil, err } return &SpecSchedule{ Second: second, Minute: minute, Hour: hour, Dom: dayofmonth, Month: month, Dow: dayofweek, }, nil }
go
func (p Parser) Parse(spec string) (Schedule, error) { if len(spec) == 0 { return nil, fmt.Errorf("Empty spec string") } if spec[0] == '@' && p.options&Descriptor > 0 { return parseDescriptor(spec) } // Figure out how many fields we need max := 0 for _, place := range places { if p.options&place > 0 { max++ } } min := max - p.optionals // Split fields on whitespace fields := strings.Fields(spec) // Validate number of fields if count := len(fields); count < min || count > max { if min == max { return nil, fmt.Errorf("Expected exactly %d fields, found %d: %s", min, count, spec) } return nil, fmt.Errorf("Expected %d to %d fields, found %d: %s", min, max, count, spec) } // Fill in missing fields fields = expandFields(fields, p.options) var err error field := func(field string, r bounds) uint64 { if err != nil { return 0 } var bits uint64 bits, err = getField(field, r) return bits } var ( second = field(fields[0], seconds) minute = field(fields[1], minutes) hour = field(fields[2], hours) dayofmonth = field(fields[3], dom) month = field(fields[4], months) dayofweek = field(fields[5], dow) ) if err != nil { return nil, err } return &SpecSchedule{ Second: second, Minute: minute, Hour: hour, Dom: dayofmonth, Month: month, Dow: dayofweek, }, nil }
[ "func", "(", "p", "Parser", ")", "Parse", "(", "spec", "string", ")", "(", "Schedule", ",", "error", ")", "{", "if", "len", "(", "spec", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "spec", "[", "0", "]", "==", "'@'", "&&", "p", ".", "options", "&", "Descriptor", ">", "0", "{", "return", "parseDescriptor", "(", "spec", ")", "\n", "}", "\n\n", "// Figure out how many fields we need", "max", ":=", "0", "\n", "for", "_", ",", "place", ":=", "range", "places", "{", "if", "p", ".", "options", "&", "place", ">", "0", "{", "max", "++", "\n", "}", "\n", "}", "\n", "min", ":=", "max", "-", "p", ".", "optionals", "\n\n", "// Split fields on whitespace", "fields", ":=", "strings", ".", "Fields", "(", "spec", ")", "\n\n", "// Validate number of fields", "if", "count", ":=", "len", "(", "fields", ")", ";", "count", "<", "min", "||", "count", ">", "max", "{", "if", "min", "==", "max", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "min", ",", "count", ",", "spec", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "min", ",", "max", ",", "count", ",", "spec", ")", "\n", "}", "\n\n", "// Fill in missing fields", "fields", "=", "expandFields", "(", "fields", ",", "p", ".", "options", ")", "\n\n", "var", "err", "error", "\n", "field", ":=", "func", "(", "field", "string", ",", "r", "bounds", ")", "uint64", "{", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n", "var", "bits", "uint64", "\n", "bits", ",", "err", "=", "getField", "(", "field", ",", "r", ")", "\n", "return", "bits", "\n", "}", "\n\n", "var", "(", "second", "=", "field", "(", "fields", "[", "0", "]", ",", "seconds", ")", "\n", "minute", "=", "field", "(", "fields", "[", "1", "]", ",", "minutes", ")", "\n", "hour", "=", "field", "(", "fields", "[", "2", "]", ",", "hours", ")", "\n", "dayofmonth", "=", "field", "(", "fields", "[", "3", "]", ",", "dom", ")", "\n", "month", "=", "field", "(", "fields", "[", "4", "]", ",", "months", ")", "\n", "dayofweek", "=", "field", "(", "fields", "[", "5", "]", ",", "dow", ")", "\n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "SpecSchedule", "{", "Second", ":", "second", ",", "Minute", ":", "minute", ",", "Hour", ":", "hour", ",", "Dom", ":", "dayofmonth", ",", "Month", ":", "month", ",", "Dow", ":", "dayofweek", ",", "}", ",", "nil", "\n", "}" ]
// Parse returns a new crontab schedule representing the given spec. // It returns a descriptive error if the spec is not valid. // It accepts crontab specs and features configured by NewParser.
[ "Parse", "returns", "a", "new", "crontab", "schedule", "representing", "the", "given", "spec", ".", "It", "returns", "a", "descriptive", "error", "if", "the", "spec", "is", "not", "valid", ".", "It", "accepts", "crontab", "specs", "and", "features", "configured", "by", "NewParser", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/parser.go#L78-L139
158,240
robfig/cron
parser.go
getField
func getField(field string, r bounds) (uint64, error) { var bits uint64 ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) for _, expr := range ranges { bit, err := getRange(expr, r) if err != nil { return bits, err } bits |= bit } return bits, nil }
go
func getField(field string, r bounds) (uint64, error) { var bits uint64 ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) for _, expr := range ranges { bit, err := getRange(expr, r) if err != nil { return bits, err } bits |= bit } return bits, nil }
[ "func", "getField", "(", "field", "string", ",", "r", "bounds", ")", "(", "uint64", ",", "error", ")", "{", "var", "bits", "uint64", "\n", "ranges", ":=", "strings", ".", "FieldsFunc", "(", "field", ",", "func", "(", "r", "rune", ")", "bool", "{", "return", "r", "==", "','", "}", ")", "\n", "for", "_", ",", "expr", ":=", "range", "ranges", "{", "bit", ",", "err", ":=", "getRange", "(", "expr", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "bits", ",", "err", "\n", "}", "\n", "bits", "|=", "bit", "\n", "}", "\n", "return", "bits", ",", "nil", "\n", "}" ]
// getField returns an Int with the bits set representing all of the times that // the field represents or error parsing field value. A "field" is a comma-separated // list of "ranges".
[ "getField", "returns", "an", "Int", "with", "the", "bits", "set", "representing", "all", "of", "the", "times", "that", "the", "field", "represents", "or", "error", "parsing", "field", "value", ".", "A", "field", "is", "a", "comma", "-", "separated", "list", "of", "ranges", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/parser.go#L191-L202
158,241
robfig/cron
parser.go
mustParseInt
func mustParseInt(expr string) (uint, error) { num, err := strconv.Atoi(expr) if err != nil { return 0, fmt.Errorf("Failed to parse int from %s: %s", expr, err) } if num < 0 { return 0, fmt.Errorf("Negative number (%d) not allowed: %s", num, expr) } return uint(num), nil }
go
func mustParseInt(expr string) (uint, error) { num, err := strconv.Atoi(expr) if err != nil { return 0, fmt.Errorf("Failed to parse int from %s: %s", expr, err) } if num < 0 { return 0, fmt.Errorf("Negative number (%d) not allowed: %s", num, expr) } return uint(num), nil }
[ "func", "mustParseInt", "(", "expr", "string", ")", "(", "uint", ",", "error", ")", "{", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "expr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "expr", ",", "err", ")", "\n", "}", "\n", "if", "num", "<", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "num", ",", "expr", ")", "\n", "}", "\n\n", "return", "uint", "(", "num", ")", ",", "nil", "\n", "}" ]
// mustParseInt parses the given expression as an int or returns an error.
[ "mustParseInt", "parses", "the", "given", "expression", "as", "an", "int", "or", "returns", "an", "error", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/parser.go#L283-L293
158,242
robfig/cron
parser.go
parseDescriptor
func parseDescriptor(descriptor string) (Schedule, error) { switch descriptor { case "@yearly", "@annually": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: 1 << months.min, Dow: all(dow), }, nil case "@monthly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: all(months), Dow: all(dow), }, nil case "@weekly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: 1 << dow.min, }, nil case "@daily", "@midnight": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: all(dow), }, nil case "@hourly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: all(hours), Dom: all(dom), Month: all(months), Dow: all(dow), }, nil } const every = "@every " if strings.HasPrefix(descriptor, every) { duration, err := time.ParseDuration(descriptor[len(every):]) if err != nil { return nil, fmt.Errorf("Failed to parse duration %s: %s", descriptor, err) } return Every(duration), nil } return nil, fmt.Errorf("Unrecognized descriptor: %s", descriptor) }
go
func parseDescriptor(descriptor string) (Schedule, error) { switch descriptor { case "@yearly", "@annually": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: 1 << months.min, Dow: all(dow), }, nil case "@monthly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: all(months), Dow: all(dow), }, nil case "@weekly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: 1 << dow.min, }, nil case "@daily", "@midnight": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: all(dow), }, nil case "@hourly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: all(hours), Dom: all(dom), Month: all(months), Dow: all(dow), }, nil } const every = "@every " if strings.HasPrefix(descriptor, every) { duration, err := time.ParseDuration(descriptor[len(every):]) if err != nil { return nil, fmt.Errorf("Failed to parse duration %s: %s", descriptor, err) } return Every(duration), nil } return nil, fmt.Errorf("Unrecognized descriptor: %s", descriptor) }
[ "func", "parseDescriptor", "(", "descriptor", "string", ")", "(", "Schedule", ",", "error", ")", "{", "switch", "descriptor", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "&", "SpecSchedule", "{", "Second", ":", "1", "<<", "seconds", ".", "min", ",", "Minute", ":", "1", "<<", "minutes", ".", "min", ",", "Hour", ":", "1", "<<", "hours", ".", "min", ",", "Dom", ":", "1", "<<", "dom", ".", "min", ",", "Month", ":", "1", "<<", "months", ".", "min", ",", "Dow", ":", "all", "(", "dow", ")", ",", "}", ",", "nil", "\n\n", "case", "\"", "\"", ":", "return", "&", "SpecSchedule", "{", "Second", ":", "1", "<<", "seconds", ".", "min", ",", "Minute", ":", "1", "<<", "minutes", ".", "min", ",", "Hour", ":", "1", "<<", "hours", ".", "min", ",", "Dom", ":", "1", "<<", "dom", ".", "min", ",", "Month", ":", "all", "(", "months", ")", ",", "Dow", ":", "all", "(", "dow", ")", ",", "}", ",", "nil", "\n\n", "case", "\"", "\"", ":", "return", "&", "SpecSchedule", "{", "Second", ":", "1", "<<", "seconds", ".", "min", ",", "Minute", ":", "1", "<<", "minutes", ".", "min", ",", "Hour", ":", "1", "<<", "hours", ".", "min", ",", "Dom", ":", "all", "(", "dom", ")", ",", "Month", ":", "all", "(", "months", ")", ",", "Dow", ":", "1", "<<", "dow", ".", "min", ",", "}", ",", "nil", "\n\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "&", "SpecSchedule", "{", "Second", ":", "1", "<<", "seconds", ".", "min", ",", "Minute", ":", "1", "<<", "minutes", ".", "min", ",", "Hour", ":", "1", "<<", "hours", ".", "min", ",", "Dom", ":", "all", "(", "dom", ")", ",", "Month", ":", "all", "(", "months", ")", ",", "Dow", ":", "all", "(", "dow", ")", ",", "}", ",", "nil", "\n\n", "case", "\"", "\"", ":", "return", "&", "SpecSchedule", "{", "Second", ":", "1", "<<", "seconds", ".", "min", ",", "Minute", ":", "1", "<<", "minutes", ".", "min", ",", "Hour", ":", "all", "(", "hours", ")", ",", "Dom", ":", "all", "(", "dom", ")", ",", "Month", ":", "all", "(", "months", ")", ",", "Dow", ":", "all", "(", "dow", ")", ",", "}", ",", "nil", "\n", "}", "\n\n", "const", "every", "=", "\"", "\"", "\n", "if", "strings", ".", "HasPrefix", "(", "descriptor", ",", "every", ")", "{", "duration", ",", "err", ":=", "time", ".", "ParseDuration", "(", "descriptor", "[", "len", "(", "every", ")", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "descriptor", ",", "err", ")", "\n", "}", "\n", "return", "Every", "(", "duration", ")", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "descriptor", ")", "\n", "}" ]
// parseDescriptor returns a predefined schedule for the expression, or error if none matches.
[ "parseDescriptor", "returns", "a", "predefined", "schedule", "for", "the", "expression", "or", "error", "if", "none", "matches", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/parser.go#L317-L380
158,243
robfig/cron
spec.go
Next
func (s *SpecSchedule) Next(t time.Time) time.Time { // General approach: // For Month, Day, Hour, Minute, Second: // Check if the time value matches. If yes, continue to the next field. // If the field doesn't match the schedule, then increment the field until it matches. // While incrementing the field, a wrap-around brings it back to the beginning // of the field list (since it is necessary to re-verify previous field // values) // Start at the earliest possible time (the upcoming second). t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) // This flag indicates whether a field has been incremented. added := false // If no time is found within five years, return zero. yearLimit := t.Year() + 5 WRAP: if t.Year() > yearLimit { return time.Time{} } // Find the first applicable month. // If it's this month, then do nothing. for 1<<uint(t.Month())&s.Month == 0 { // If we have to add a month, reset the other parts to 0. if !added { added = true // Otherwise, set the date at the beginning (since the current time is irrelevant). t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) } t = t.AddDate(0, 1, 0) // Wrapped around. if t.Month() == time.January { goto WRAP } } // Now get a day in that month. for !dayMatches(s, t) { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) } t = t.AddDate(0, 0, 1) if t.Day() == 1 { goto WRAP } } for 1<<uint(t.Hour())&s.Hour == 0 { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()) } t = t.Add(1 * time.Hour) if t.Hour() == 0 { goto WRAP } } for 1<<uint(t.Minute())&s.Minute == 0 { if !added { added = true t = t.Truncate(time.Minute) } t = t.Add(1 * time.Minute) if t.Minute() == 0 { goto WRAP } } for 1<<uint(t.Second())&s.Second == 0 { if !added { added = true t = t.Truncate(time.Second) } t = t.Add(1 * time.Second) if t.Second() == 0 { goto WRAP } } return t }
go
func (s *SpecSchedule) Next(t time.Time) time.Time { // General approach: // For Month, Day, Hour, Minute, Second: // Check if the time value matches. If yes, continue to the next field. // If the field doesn't match the schedule, then increment the field until it matches. // While incrementing the field, a wrap-around brings it back to the beginning // of the field list (since it is necessary to re-verify previous field // values) // Start at the earliest possible time (the upcoming second). t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) // This flag indicates whether a field has been incremented. added := false // If no time is found within five years, return zero. yearLimit := t.Year() + 5 WRAP: if t.Year() > yearLimit { return time.Time{} } // Find the first applicable month. // If it's this month, then do nothing. for 1<<uint(t.Month())&s.Month == 0 { // If we have to add a month, reset the other parts to 0. if !added { added = true // Otherwise, set the date at the beginning (since the current time is irrelevant). t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) } t = t.AddDate(0, 1, 0) // Wrapped around. if t.Month() == time.January { goto WRAP } } // Now get a day in that month. for !dayMatches(s, t) { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) } t = t.AddDate(0, 0, 1) if t.Day() == 1 { goto WRAP } } for 1<<uint(t.Hour())&s.Hour == 0 { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()) } t = t.Add(1 * time.Hour) if t.Hour() == 0 { goto WRAP } } for 1<<uint(t.Minute())&s.Minute == 0 { if !added { added = true t = t.Truncate(time.Minute) } t = t.Add(1 * time.Minute) if t.Minute() == 0 { goto WRAP } } for 1<<uint(t.Second())&s.Second == 0 { if !added { added = true t = t.Truncate(time.Second) } t = t.Add(1 * time.Second) if t.Second() == 0 { goto WRAP } } return t }
[ "func", "(", "s", "*", "SpecSchedule", ")", "Next", "(", "t", "time", ".", "Time", ")", "time", ".", "Time", "{", "// General approach:", "// For Month, Day, Hour, Minute, Second:", "// Check if the time value matches. If yes, continue to the next field.", "// If the field doesn't match the schedule, then increment the field until it matches.", "// While incrementing the field, a wrap-around brings it back to the beginning", "// of the field list (since it is necessary to re-verify previous field", "// values)", "// Start at the earliest possible time (the upcoming second).", "t", "=", "t", ".", "Add", "(", "1", "*", "time", ".", "Second", "-", "time", ".", "Duration", "(", "t", ".", "Nanosecond", "(", ")", ")", "*", "time", ".", "Nanosecond", ")", "\n\n", "// This flag indicates whether a field has been incremented.", "added", ":=", "false", "\n\n", "// If no time is found within five years, return zero.", "yearLimit", ":=", "t", ".", "Year", "(", ")", "+", "5", "\n\n", "WRAP", ":", "if", "t", ".", "Year", "(", ")", ">", "yearLimit", "{", "return", "time", ".", "Time", "{", "}", "\n", "}", "\n\n", "// Find the first applicable month.", "// If it's this month, then do nothing.", "for", "1", "<<", "uint", "(", "t", ".", "Month", "(", ")", ")", "&", "s", ".", "Month", "==", "0", "{", "// If we have to add a month, reset the other parts to 0.", "if", "!", "added", "{", "added", "=", "true", "\n", "// Otherwise, set the date at the beginning (since the current time is irrelevant).", "t", "=", "time", ".", "Date", "(", "t", ".", "Year", "(", ")", ",", "t", ".", "Month", "(", ")", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "t", ".", "Location", "(", ")", ")", "\n", "}", "\n", "t", "=", "t", ".", "AddDate", "(", "0", ",", "1", ",", "0", ")", "\n\n", "// Wrapped around.", "if", "t", ".", "Month", "(", ")", "==", "time", ".", "January", "{", "goto", "WRAP", "\n", "}", "\n", "}", "\n\n", "// Now get a day in that month.", "for", "!", "dayMatches", "(", "s", ",", "t", ")", "{", "if", "!", "added", "{", "added", "=", "true", "\n", "t", "=", "time", ".", "Date", "(", "t", ".", "Year", "(", ")", ",", "t", ".", "Month", "(", ")", ",", "t", ".", "Day", "(", ")", ",", "0", ",", "0", ",", "0", ",", "0", ",", "t", ".", "Location", "(", ")", ")", "\n", "}", "\n", "t", "=", "t", ".", "AddDate", "(", "0", ",", "0", ",", "1", ")", "\n\n", "if", "t", ".", "Day", "(", ")", "==", "1", "{", "goto", "WRAP", "\n", "}", "\n", "}", "\n\n", "for", "1", "<<", "uint", "(", "t", ".", "Hour", "(", ")", ")", "&", "s", ".", "Hour", "==", "0", "{", "if", "!", "added", "{", "added", "=", "true", "\n", "t", "=", "time", ".", "Date", "(", "t", ".", "Year", "(", ")", ",", "t", ".", "Month", "(", ")", ",", "t", ".", "Day", "(", ")", ",", "t", ".", "Hour", "(", ")", ",", "0", ",", "0", ",", "0", ",", "t", ".", "Location", "(", ")", ")", "\n", "}", "\n", "t", "=", "t", ".", "Add", "(", "1", "*", "time", ".", "Hour", ")", "\n\n", "if", "t", ".", "Hour", "(", ")", "==", "0", "{", "goto", "WRAP", "\n", "}", "\n", "}", "\n\n", "for", "1", "<<", "uint", "(", "t", ".", "Minute", "(", ")", ")", "&", "s", ".", "Minute", "==", "0", "{", "if", "!", "added", "{", "added", "=", "true", "\n", "t", "=", "t", ".", "Truncate", "(", "time", ".", "Minute", ")", "\n", "}", "\n", "t", "=", "t", ".", "Add", "(", "1", "*", "time", ".", "Minute", ")", "\n\n", "if", "t", ".", "Minute", "(", ")", "==", "0", "{", "goto", "WRAP", "\n", "}", "\n", "}", "\n\n", "for", "1", "<<", "uint", "(", "t", ".", "Second", "(", ")", ")", "&", "s", ".", "Second", "==", "0", "{", "if", "!", "added", "{", "added", "=", "true", "\n", "t", "=", "t", ".", "Truncate", "(", "time", ".", "Second", ")", "\n", "}", "\n", "t", "=", "t", ".", "Add", "(", "1", "*", "time", ".", "Second", ")", "\n\n", "if", "t", ".", "Second", "(", ")", "==", "0", "{", "goto", "WRAP", "\n", "}", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// Next returns the next time this schedule is activated, greater than the given // time. If no time can be found to satisfy the schedule, return the zero time.
[ "Next", "returns", "the", "next", "time", "this", "schedule", "is", "activated", "greater", "than", "the", "given", "time", ".", "If", "no", "time", "can", "be", "found", "to", "satisfy", "the", "schedule", "return", "the", "zero", "time", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/spec.go#L55-L145
158,244
robfig/cron
spec.go
dayMatches
func dayMatches(s *SpecSchedule, t time.Time) bool { var ( domMatch bool = 1<<uint(t.Day())&s.Dom > 0 dowMatch bool = 1<<uint(t.Weekday())&s.Dow > 0 ) if s.Dom&starBit > 0 || s.Dow&starBit > 0 { return domMatch && dowMatch } return domMatch || dowMatch }
go
func dayMatches(s *SpecSchedule, t time.Time) bool { var ( domMatch bool = 1<<uint(t.Day())&s.Dom > 0 dowMatch bool = 1<<uint(t.Weekday())&s.Dow > 0 ) if s.Dom&starBit > 0 || s.Dow&starBit > 0 { return domMatch && dowMatch } return domMatch || dowMatch }
[ "func", "dayMatches", "(", "s", "*", "SpecSchedule", ",", "t", "time", ".", "Time", ")", "bool", "{", "var", "(", "domMatch", "bool", "=", "1", "<<", "uint", "(", "t", ".", "Day", "(", ")", ")", "&", "s", ".", "Dom", ">", "0", "\n", "dowMatch", "bool", "=", "1", "<<", "uint", "(", "t", ".", "Weekday", "(", ")", ")", "&", "s", ".", "Dow", ">", "0", "\n", ")", "\n", "if", "s", ".", "Dom", "&", "starBit", ">", "0", "||", "s", ".", "Dow", "&", "starBit", ">", "0", "{", "return", "domMatch", "&&", "dowMatch", "\n", "}", "\n", "return", "domMatch", "||", "dowMatch", "\n", "}" ]
// dayMatches returns true if the schedule's day-of-week and day-of-month // restrictions are satisfied by the given time.
[ "dayMatches", "returns", "true", "if", "the", "schedule", "s", "day", "-", "of", "-", "week", "and", "day", "-", "of", "-", "month", "restrictions", "are", "satisfied", "by", "the", "given", "time", "." ]
b41be1df696709bb6395fe435af20370037c0b4c
https://github.com/robfig/cron/blob/b41be1df696709bb6395fe435af20370037c0b4c/spec.go#L149-L158
158,245
360EntSecGroup-Skylar/excelize
calcchain.go
deleteCalcChain
func (f *File) deleteCalcChain(index int, axis string) { calc := f.calcChainReader() if calc != nil { calc.C = xlsxCalcChainCollection(calc.C).Filter(func(c xlsxCalcChainC) bool { return !((c.I == index && c.R == axis) || (c.I == index && axis == "")) }) } if len(calc.C) == 0 { f.CalcChain = nil delete(f.XLSX, "xl/calcChain.xml") content := f.contentTypesReader() for k, v := range content.Overrides { if v.PartName == "/xl/calcChain.xml" { content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...) } } } }
go
func (f *File) deleteCalcChain(index int, axis string) { calc := f.calcChainReader() if calc != nil { calc.C = xlsxCalcChainCollection(calc.C).Filter(func(c xlsxCalcChainC) bool { return !((c.I == index && c.R == axis) || (c.I == index && axis == "")) }) } if len(calc.C) == 0 { f.CalcChain = nil delete(f.XLSX, "xl/calcChain.xml") content := f.contentTypesReader() for k, v := range content.Overrides { if v.PartName == "/xl/calcChain.xml" { content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...) } } } }
[ "func", "(", "f", "*", "File", ")", "deleteCalcChain", "(", "index", "int", ",", "axis", "string", ")", "{", "calc", ":=", "f", ".", "calcChainReader", "(", ")", "\n", "if", "calc", "!=", "nil", "{", "calc", ".", "C", "=", "xlsxCalcChainCollection", "(", "calc", ".", "C", ")", ".", "Filter", "(", "func", "(", "c", "xlsxCalcChainC", ")", "bool", "{", "return", "!", "(", "(", "c", ".", "I", "==", "index", "&&", "c", ".", "R", "==", "axis", ")", "||", "(", "c", ".", "I", "==", "index", "&&", "axis", "==", "\"", "\"", ")", ")", "\n", "}", ")", "\n", "}", "\n", "if", "len", "(", "calc", ".", "C", ")", "==", "0", "{", "f", ".", "CalcChain", "=", "nil", "\n", "delete", "(", "f", ".", "XLSX", ",", "\"", "\"", ")", "\n", "content", ":=", "f", ".", "contentTypesReader", "(", ")", "\n", "for", "k", ",", "v", ":=", "range", "content", ".", "Overrides", "{", "if", "v", ".", "PartName", "==", "\"", "\"", "{", "content", ".", "Overrides", "=", "append", "(", "content", ".", "Overrides", "[", ":", "k", "]", ",", "content", ".", "Overrides", "[", "k", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// deleteCalcChain provides a function to remove cell reference on the // calculation chain.
[ "deleteCalcChain", "provides", "a", "function", "to", "remove", "cell", "reference", "on", "the", "calculation", "chain", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/calcchain.go#L36-L53
158,246
360EntSecGroup-Skylar/excelize
calcchain.go
Filter
func (c xlsxCalcChainCollection) Filter(fn func(v xlsxCalcChainC) bool) []xlsxCalcChainC { results := make([]xlsxCalcChainC, 0) for _, v := range c { if fn(v) { results = append(results, v) } } return results }
go
func (c xlsxCalcChainCollection) Filter(fn func(v xlsxCalcChainC) bool) []xlsxCalcChainC { results := make([]xlsxCalcChainC, 0) for _, v := range c { if fn(v) { results = append(results, v) } } return results }
[ "func", "(", "c", "xlsxCalcChainCollection", ")", "Filter", "(", "fn", "func", "(", "v", "xlsxCalcChainC", ")", "bool", ")", "[", "]", "xlsxCalcChainC", "{", "results", ":=", "make", "(", "[", "]", "xlsxCalcChainC", ",", "0", ")", "\n", "for", "_", ",", "v", ":=", "range", "c", "{", "if", "fn", "(", "v", ")", "{", "results", "=", "append", "(", "results", ",", "v", ")", "\n", "}", "\n", "}", "\n", "return", "results", "\n", "}" ]
// Filter provides a function to filter calculation chain.
[ "Filter", "provides", "a", "function", "to", "filter", "calculation", "chain", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/calcchain.go#L58-L66
158,247
360EntSecGroup-Skylar/excelize
file.go
Save
func (f *File) Save() error { if f.Path == "" { return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write") } return f.SaveAs(f.Path) }
go
func (f *File) Save() error { if f.Path == "" { return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write") } return f.SaveAs(f.Path) }
[ "func", "(", "f", "*", "File", ")", "Save", "(", ")", "error", "{", "if", "f", ".", "Path", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "f", ".", "SaveAs", "(", "f", ".", "Path", ")", "\n", "}" ]
// Save provides a function to override the xlsx file with origin path.
[ "Save", "provides", "a", "function", "to", "override", "the", "xlsx", "file", "with", "origin", "path", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/file.go#L60-L65
158,248
360EntSecGroup-Skylar/excelize
file.go
SaveAs
func (f *File) SaveAs(name string) error { file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return err } defer file.Close() return f.Write(file) }
go
func (f *File) SaveAs(name string) error { file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return err } defer file.Close() return f.Write(file) }
[ "func", "(", "f", "*", "File", ")", "SaveAs", "(", "name", "string", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_TRUNC", "|", "os", ".", "O_CREATE", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "return", "f", ".", "Write", "(", "file", ")", "\n", "}" ]
// SaveAs provides a function to create or update to an xlsx file at the // provided path.
[ "SaveAs", "provides", "a", "function", "to", "create", "or", "update", "to", "an", "xlsx", "file", "at", "the", "provided", "path", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/file.go#L69-L76
158,249
360EntSecGroup-Skylar/excelize
file.go
Write
func (f *File) Write(w io.Writer) error { _, err := f.WriteTo(w) return err }
go
func (f *File) Write(w io.Writer) error { _, err := f.WriteTo(w) return err }
[ "func", "(", "f", "*", "File", ")", "Write", "(", "w", "io", ".", "Writer", ")", "error", "{", "_", ",", "err", ":=", "f", ".", "WriteTo", "(", "w", ")", "\n", "return", "err", "\n", "}" ]
// Write provides a function to write to an io.Writer.
[ "Write", "provides", "a", "function", "to", "write", "to", "an", "io", ".", "Writer", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/file.go#L79-L82
158,250
360EntSecGroup-Skylar/excelize
file.go
WriteTo
func (f *File) WriteTo(w io.Writer) (int64, error) { buf, err := f.WriteToBuffer() if err != nil { return 0, err } return buf.WriteTo(w) }
go
func (f *File) WriteTo(w io.Writer) (int64, error) { buf, err := f.WriteToBuffer() if err != nil { return 0, err } return buf.WriteTo(w) }
[ "func", "(", "f", "*", "File", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "buf", ",", "err", ":=", "f", ".", "WriteToBuffer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "buf", ".", "WriteTo", "(", "w", ")", "\n", "}" ]
// WriteTo implements io.WriterTo to write the file.
[ "WriteTo", "implements", "io", ".", "WriterTo", "to", "write", "the", "file", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/file.go#L85-L91
158,251
360EntSecGroup-Skylar/excelize
file.go
WriteToBuffer
func (f *File) WriteToBuffer() (*bytes.Buffer, error) { buf := new(bytes.Buffer) zw := zip.NewWriter(buf) f.calcChainWriter() f.commentsWriter() f.contentTypesWriter() f.drawingRelsWriter() f.drawingsWriter() f.vmlDrawingWriter() f.workBookWriter() f.workBookRelsWriter() f.workSheetWriter() f.workSheetRelsWriter() f.styleSheetWriter() for path, content := range f.XLSX { fi, err := zw.Create(path) if err != nil { return buf, err } _, err = fi.Write(content) if err != nil { return buf, err } } return buf, zw.Close() }
go
func (f *File) WriteToBuffer() (*bytes.Buffer, error) { buf := new(bytes.Buffer) zw := zip.NewWriter(buf) f.calcChainWriter() f.commentsWriter() f.contentTypesWriter() f.drawingRelsWriter() f.drawingsWriter() f.vmlDrawingWriter() f.workBookWriter() f.workBookRelsWriter() f.workSheetWriter() f.workSheetRelsWriter() f.styleSheetWriter() for path, content := range f.XLSX { fi, err := zw.Create(path) if err != nil { return buf, err } _, err = fi.Write(content) if err != nil { return buf, err } } return buf, zw.Close() }
[ "func", "(", "f", "*", "File", ")", "WriteToBuffer", "(", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "zw", ":=", "zip", ".", "NewWriter", "(", "buf", ")", "\n", "f", ".", "calcChainWriter", "(", ")", "\n", "f", ".", "commentsWriter", "(", ")", "\n", "f", ".", "contentTypesWriter", "(", ")", "\n", "f", ".", "drawingRelsWriter", "(", ")", "\n", "f", ".", "drawingsWriter", "(", ")", "\n", "f", ".", "vmlDrawingWriter", "(", ")", "\n", "f", ".", "workBookWriter", "(", ")", "\n", "f", ".", "workBookRelsWriter", "(", ")", "\n", "f", ".", "workSheetWriter", "(", ")", "\n", "f", ".", "workSheetRelsWriter", "(", ")", "\n", "f", ".", "styleSheetWriter", "(", ")", "\n\n", "for", "path", ",", "content", ":=", "range", "f", ".", "XLSX", "{", "fi", ",", "err", ":=", "zw", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "buf", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "fi", ".", "Write", "(", "content", ")", "\n", "if", "err", "!=", "nil", "{", "return", "buf", ",", "err", "\n", "}", "\n", "}", "\n", "return", "buf", ",", "zw", ".", "Close", "(", ")", "\n", "}" ]
// WriteToBuffer provides a function to get bytes.Buffer from the saved file.
[ "WriteToBuffer", "provides", "a", "function", "to", "get", "bytes", ".", "Buffer", "from", "the", "saved", "file", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/file.go#L94-L120
158,252
360EntSecGroup-Skylar/excelize
picture.go
parseFormatPictureSet
func parseFormatPictureSet(formatSet string) (*formatPicture, error) { format := formatPicture{ FPrintsWithSheet: true, FLocksWithSheet: false, NoChangeAspect: false, OffsetX: 0, OffsetY: 0, XScale: 1.0, YScale: 1.0, } err := json.Unmarshal(parseFormatSet(formatSet), &format) return &format, err }
go
func parseFormatPictureSet(formatSet string) (*formatPicture, error) { format := formatPicture{ FPrintsWithSheet: true, FLocksWithSheet: false, NoChangeAspect: false, OffsetX: 0, OffsetY: 0, XScale: 1.0, YScale: 1.0, } err := json.Unmarshal(parseFormatSet(formatSet), &format) return &format, err }
[ "func", "parseFormatPictureSet", "(", "formatSet", "string", ")", "(", "*", "formatPicture", ",", "error", ")", "{", "format", ":=", "formatPicture", "{", "FPrintsWithSheet", ":", "true", ",", "FLocksWithSheet", ":", "false", ",", "NoChangeAspect", ":", "false", ",", "OffsetX", ":", "0", ",", "OffsetY", ":", "0", ",", "XScale", ":", "1.0", ",", "YScale", ":", "1.0", ",", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "parseFormatSet", "(", "formatSet", ")", ",", "&", "format", ")", "\n", "return", "&", "format", ",", "err", "\n", "}" ]
// parseFormatPictureSet provides a function to parse the format settings of // the picture with default value.
[ "parseFormatPictureSet", "provides", "a", "function", "to", "parse", "the", "format", "settings", "of", "the", "picture", "with", "default", "value", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/picture.go#L28-L40
158,253
360EntSecGroup-Skylar/excelize
picture.go
addDrawingPicture
func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) error { col, row, err := CellNameToCoordinates(cell) if err != nil { return err } width = int(float64(width) * formatSet.XScale) height = int(float64(height) * formatSet.YScale) col-- row-- colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height) content, cNvPrID := f.drawingParser(drawingXML) twoCellAnchor := xdrCellAnchor{} twoCellAnchor.EditAs = formatSet.Positioning from := xlsxFrom{} from.Col = colStart from.ColOff = formatSet.OffsetX * EMU from.Row = rowStart from.RowOff = formatSet.OffsetY * EMU to := xlsxTo{} to.Col = colEnd to.ColOff = x2 * EMU to.Row = rowEnd to.RowOff = y2 * EMU twoCellAnchor.From = &from twoCellAnchor.To = &to pic := xlsxPic{} pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1 pic.NvPicPr.CNvPr.Descr = file pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID) if hyperlinkRID != 0 { pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{ R: SourceRelationship, RID: "rId" + strconv.Itoa(hyperlinkRID), } } pic.BlipFill.Blip.R = SourceRelationship pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID) pic.SpPr.PrstGeom.Prst = "rect" twoCellAnchor.Pic = &pic twoCellAnchor.ClientData = &xdrClientData{ FLocksWithSheet: formatSet.FLocksWithSheet, FPrintsWithSheet: formatSet.FPrintsWithSheet, } content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor) f.Drawings[drawingXML] = content return err }
go
func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) error { col, row, err := CellNameToCoordinates(cell) if err != nil { return err } width = int(float64(width) * formatSet.XScale) height = int(float64(height) * formatSet.YScale) col-- row-- colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height) content, cNvPrID := f.drawingParser(drawingXML) twoCellAnchor := xdrCellAnchor{} twoCellAnchor.EditAs = formatSet.Positioning from := xlsxFrom{} from.Col = colStart from.ColOff = formatSet.OffsetX * EMU from.Row = rowStart from.RowOff = formatSet.OffsetY * EMU to := xlsxTo{} to.Col = colEnd to.ColOff = x2 * EMU to.Row = rowEnd to.RowOff = y2 * EMU twoCellAnchor.From = &from twoCellAnchor.To = &to pic := xlsxPic{} pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1 pic.NvPicPr.CNvPr.Descr = file pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID) if hyperlinkRID != 0 { pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{ R: SourceRelationship, RID: "rId" + strconv.Itoa(hyperlinkRID), } } pic.BlipFill.Blip.R = SourceRelationship pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID) pic.SpPr.PrstGeom.Prst = "rect" twoCellAnchor.Pic = &pic twoCellAnchor.ClientData = &xdrClientData{ FLocksWithSheet: formatSet.FLocksWithSheet, FPrintsWithSheet: formatSet.FPrintsWithSheet, } content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor) f.Drawings[drawingXML] = content return err }
[ "func", "(", "f", "*", "File", ")", "addDrawingPicture", "(", "sheet", ",", "drawingXML", ",", "cell", ",", "file", "string", ",", "width", ",", "height", ",", "rID", ",", "hyperlinkRID", "int", ",", "formatSet", "*", "formatPicture", ")", "error", "{", "col", ",", "row", ",", "err", ":=", "CellNameToCoordinates", "(", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "width", "=", "int", "(", "float64", "(", "width", ")", "*", "formatSet", ".", "XScale", ")", "\n", "height", "=", "int", "(", "float64", "(", "height", ")", "*", "formatSet", ".", "YScale", ")", "\n", "col", "--", "\n", "row", "--", "\n", "colStart", ",", "rowStart", ",", "_", ",", "_", ",", "colEnd", ",", "rowEnd", ",", "x2", ",", "y2", ":=", "f", ".", "positionObjectPixels", "(", "sheet", ",", "col", ",", "row", ",", "formatSet", ".", "OffsetX", ",", "formatSet", ".", "OffsetY", ",", "width", ",", "height", ")", "\n", "content", ",", "cNvPrID", ":=", "f", ".", "drawingParser", "(", "drawingXML", ")", "\n", "twoCellAnchor", ":=", "xdrCellAnchor", "{", "}", "\n", "twoCellAnchor", ".", "EditAs", "=", "formatSet", ".", "Positioning", "\n", "from", ":=", "xlsxFrom", "{", "}", "\n", "from", ".", "Col", "=", "colStart", "\n", "from", ".", "ColOff", "=", "formatSet", ".", "OffsetX", "*", "EMU", "\n", "from", ".", "Row", "=", "rowStart", "\n", "from", ".", "RowOff", "=", "formatSet", ".", "OffsetY", "*", "EMU", "\n", "to", ":=", "xlsxTo", "{", "}", "\n", "to", ".", "Col", "=", "colEnd", "\n", "to", ".", "ColOff", "=", "x2", "*", "EMU", "\n", "to", ".", "Row", "=", "rowEnd", "\n", "to", ".", "RowOff", "=", "y2", "*", "EMU", "\n", "twoCellAnchor", ".", "From", "=", "&", "from", "\n", "twoCellAnchor", ".", "To", "=", "&", "to", "\n", "pic", ":=", "xlsxPic", "{", "}", "\n", "pic", ".", "NvPicPr", ".", "CNvPicPr", ".", "PicLocks", ".", "NoChangeAspect", "=", "formatSet", ".", "NoChangeAspect", "\n", "pic", ".", "NvPicPr", ".", "CNvPr", ".", "ID", "=", "f", ".", "countCharts", "(", ")", "+", "f", ".", "countMedia", "(", ")", "+", "1", "\n", "pic", ".", "NvPicPr", ".", "CNvPr", ".", "Descr", "=", "file", "\n", "pic", ".", "NvPicPr", ".", "CNvPr", ".", "Name", "=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "cNvPrID", ")", "\n", "if", "hyperlinkRID", "!=", "0", "{", "pic", ".", "NvPicPr", ".", "CNvPr", ".", "HlinkClick", "=", "&", "xlsxHlinkClick", "{", "R", ":", "SourceRelationship", ",", "RID", ":", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "hyperlinkRID", ")", ",", "}", "\n", "}", "\n", "pic", ".", "BlipFill", ".", "Blip", ".", "R", "=", "SourceRelationship", "\n", "pic", ".", "BlipFill", ".", "Blip", ".", "Embed", "=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "rID", ")", "\n", "pic", ".", "SpPr", ".", "PrstGeom", ".", "Prst", "=", "\"", "\"", "\n\n", "twoCellAnchor", ".", "Pic", "=", "&", "pic", "\n", "twoCellAnchor", ".", "ClientData", "=", "&", "xdrClientData", "{", "FLocksWithSheet", ":", "formatSet", ".", "FLocksWithSheet", ",", "FPrintsWithSheet", ":", "formatSet", ".", "FPrintsWithSheet", ",", "}", "\n", "content", ".", "TwoCellAnchor", "=", "append", "(", "content", ".", "TwoCellAnchor", ",", "&", "twoCellAnchor", ")", "\n", "f", ".", "Drawings", "[", "drawingXML", "]", "=", "content", "\n", "return", "err", "\n", "}" ]
// addDrawingPicture provides a function to add picture by given sheet, // drawingXML, cell, file name, width, height relationship index and format // sets.
[ "addDrawingPicture", "provides", "a", "function", "to", "add", "picture", "by", "given", "sheet", "drawingXML", "cell", "file", "name", "width", "height", "relationship", "index", "and", "format", "sets", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/picture.go#L277-L326
158,254
360EntSecGroup-Skylar/excelize
picture.go
setContentTypePartImageExtensions
func (f *File) setContentTypePartImageExtensions() { var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false} content := f.contentTypesReader() for _, v := range content.Defaults { _, ok := imageTypes[v.Extension] if ok { imageTypes[v.Extension] = true } } for k, v := range imageTypes { if !v { content.Defaults = append(content.Defaults, xlsxDefault{ Extension: k, ContentType: "image/" + k, }) } } }
go
func (f *File) setContentTypePartImageExtensions() { var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false} content := f.contentTypesReader() for _, v := range content.Defaults { _, ok := imageTypes[v.Extension] if ok { imageTypes[v.Extension] = true } } for k, v := range imageTypes { if !v { content.Defaults = append(content.Defaults, xlsxDefault{ Extension: k, ContentType: "image/" + k, }) } } }
[ "func", "(", "f", "*", "File", ")", "setContentTypePartImageExtensions", "(", ")", "{", "var", "imageTypes", "=", "map", "[", "string", "]", "bool", "{", "\"", "\"", ":", "false", ",", "\"", "\"", ":", "false", ",", "\"", "\"", ":", "false", "}", "\n", "content", ":=", "f", ".", "contentTypesReader", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "content", ".", "Defaults", "{", "_", ",", "ok", ":=", "imageTypes", "[", "v", ".", "Extension", "]", "\n", "if", "ok", "{", "imageTypes", "[", "v", ".", "Extension", "]", "=", "true", "\n", "}", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "imageTypes", "{", "if", "!", "v", "{", "content", ".", "Defaults", "=", "append", "(", "content", ".", "Defaults", ",", "xlsxDefault", "{", "Extension", ":", "k", ",", "ContentType", ":", "\"", "\"", "+", "k", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}" ]
// setContentTypePartImageExtensions provides a function to set the content // type for relationship parts and the Main Document part.
[ "setContentTypePartImageExtensions", "provides", "a", "function", "to", "set", "the", "content", "type", "for", "relationship", "parts", "and", "the", "Main", "Document", "part", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/picture.go#L387-L404
158,255
360EntSecGroup-Skylar/excelize
picture.go
setContentTypePartVMLExtensions
func (f *File) setContentTypePartVMLExtensions() { vml := false content := f.contentTypesReader() for _, v := range content.Defaults { if v.Extension == "vml" { vml = true } } if !vml { content.Defaults = append(content.Defaults, xlsxDefault{ Extension: "vml", ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing", }) } }
go
func (f *File) setContentTypePartVMLExtensions() { vml := false content := f.contentTypesReader() for _, v := range content.Defaults { if v.Extension == "vml" { vml = true } } if !vml { content.Defaults = append(content.Defaults, xlsxDefault{ Extension: "vml", ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing", }) } }
[ "func", "(", "f", "*", "File", ")", "setContentTypePartVMLExtensions", "(", ")", "{", "vml", ":=", "false", "\n", "content", ":=", "f", ".", "contentTypesReader", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "content", ".", "Defaults", "{", "if", "v", ".", "Extension", "==", "\"", "\"", "{", "vml", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "vml", "{", "content", ".", "Defaults", "=", "append", "(", "content", ".", "Defaults", ",", "xlsxDefault", "{", "Extension", ":", "\"", "\"", ",", "ContentType", ":", "\"", "\"", ",", "}", ")", "\n", "}", "\n", "}" ]
// setContentTypePartVMLExtensions provides a function to set the content type // for relationship parts and the Main Document part.
[ "setContentTypePartVMLExtensions", "provides", "a", "function", "to", "set", "the", "content", "type", "for", "relationship", "parts", "and", "the", "Main", "Document", "part", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/picture.go#L408-L422
158,256
360EntSecGroup-Skylar/excelize
cell.go
GetCellValue
func (f *File) GetCellValue(sheet, axis string) (string, error) { return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) { val, err := c.getValueFrom(f, f.sharedStringsReader()) if err != nil { return val, false, err } return val, true, err }) }
go
func (f *File) GetCellValue(sheet, axis string) (string, error) { return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) { val, err := c.getValueFrom(f, f.sharedStringsReader()) if err != nil { return val, false, err } return val, true, err }) }
[ "func", "(", "f", "*", "File", ")", "GetCellValue", "(", "sheet", ",", "axis", "string", ")", "(", "string", ",", "error", ")", "{", "return", "f", ".", "getCellStringFunc", "(", "sheet", ",", "axis", ",", "func", "(", "x", "*", "xlsxWorksheet", ",", "c", "*", "xlsxC", ")", "(", "string", ",", "bool", ",", "error", ")", "{", "val", ",", "err", ":=", "c", ".", "getValueFrom", "(", "f", ",", "f", ".", "sharedStringsReader", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "val", ",", "false", ",", "err", "\n", "}", "\n", "return", "val", ",", "true", ",", "err", "\n", "}", ")", "\n", "}" ]
// GetCellValue provides a function to get formatted value from cell by given // worksheet name and axis in XLSX file. If it is possible to apply a format // to the cell value, it will do so, if not then an error will be returned, // along with the raw value of the cell.
[ "GetCellValue", "provides", "a", "function", "to", "get", "formatted", "value", "from", "cell", "by", "given", "worksheet", "name", "and", "axis", "in", "XLSX", "file", ".", "If", "it", "is", "possible", "to", "apply", "a", "format", "to", "the", "cell", "value", "it", "will", "do", "so", "if", "not", "then", "an", "error", "will", "be", "returned", "along", "with", "the", "raw", "value", "of", "the", "cell", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L37-L45
158,257
360EntSecGroup-Skylar/excelize
cell.go
setCellIntFunc
func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error { var err error switch v := value.(type) { case int: err = f.SetCellInt(sheet, axis, v) case int8: err = f.SetCellInt(sheet, axis, int(v)) case int16: err = f.SetCellInt(sheet, axis, int(v)) case int32: err = f.SetCellInt(sheet, axis, int(v)) case int64: err = f.SetCellInt(sheet, axis, int(v)) case uint: err = f.SetCellInt(sheet, axis, int(v)) case uint8: err = f.SetCellInt(sheet, axis, int(v)) case uint16: err = f.SetCellInt(sheet, axis, int(v)) case uint32: err = f.SetCellInt(sheet, axis, int(v)) case uint64: err = f.SetCellInt(sheet, axis, int(v)) } return err }
go
func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error { var err error switch v := value.(type) { case int: err = f.SetCellInt(sheet, axis, v) case int8: err = f.SetCellInt(sheet, axis, int(v)) case int16: err = f.SetCellInt(sheet, axis, int(v)) case int32: err = f.SetCellInt(sheet, axis, int(v)) case int64: err = f.SetCellInt(sheet, axis, int(v)) case uint: err = f.SetCellInt(sheet, axis, int(v)) case uint8: err = f.SetCellInt(sheet, axis, int(v)) case uint16: err = f.SetCellInt(sheet, axis, int(v)) case uint32: err = f.SetCellInt(sheet, axis, int(v)) case uint64: err = f.SetCellInt(sheet, axis, int(v)) } return err }
[ "func", "(", "f", "*", "File", ")", "setCellIntFunc", "(", "sheet", ",", "axis", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "int", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "v", ")", "\n", "case", "int8", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "int16", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "int32", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "int64", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "uint", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "uint8", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "uint16", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "uint32", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "case", "uint64", ":", "err", "=", "f", ".", "SetCellInt", "(", "sheet", ",", "axis", ",", "int", "(", "v", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// setCellIntFunc is a wrapper of SetCellInt.
[ "setCellIntFunc", "is", "a", "wrapper", "of", "SetCellInt", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L103-L128
158,258
360EntSecGroup-Skylar/excelize
cell.go
setCellTimeFunc
func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error { excelTime, err := timeToExcelTime(value) if err != nil { return err } if excelTime > 0 { err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(excelTime, 'f', -1, 64)) if err != nil { return err } err = f.setDefaultTimeStyle(sheet, axis, 22) if err != nil { return err } } else { err = f.SetCellStr(sheet, axis, value.Format(time.RFC3339Nano)) if err != nil { return err } } return err }
go
func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error { excelTime, err := timeToExcelTime(value) if err != nil { return err } if excelTime > 0 { err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(excelTime, 'f', -1, 64)) if err != nil { return err } err = f.setDefaultTimeStyle(sheet, axis, 22) if err != nil { return err } } else { err = f.SetCellStr(sheet, axis, value.Format(time.RFC3339Nano)) if err != nil { return err } } return err }
[ "func", "(", "f", "*", "File", ")", "setCellTimeFunc", "(", "sheet", ",", "axis", "string", ",", "value", "time", ".", "Time", ")", "error", "{", "excelTime", ",", "err", ":=", "timeToExcelTime", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "excelTime", ">", "0", "{", "err", "=", "f", ".", "SetCellDefault", "(", "sheet", ",", "axis", ",", "strconv", ".", "FormatFloat", "(", "excelTime", ",", "'f'", ",", "-", "1", ",", "64", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "f", ".", "setDefaultTimeStyle", "(", "sheet", ",", "axis", ",", "22", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "err", "=", "f", ".", "SetCellStr", "(", "sheet", ",", "axis", ",", "value", ".", "Format", "(", "time", ".", "RFC3339Nano", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// setCellTimeFunc provides a method to process time type of value for // SetCellValue.
[ "setCellTimeFunc", "provides", "a", "method", "to", "process", "time", "type", "of", "value", "for", "SetCellValue", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L132-L153
158,259
360EntSecGroup-Skylar/excelize
cell.go
SetCellInt
func (f *File) SetCellInt(sheet, axis string, value int) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "" cellData.V = strconv.Itoa(value) return err }
go
func (f *File) SetCellInt(sheet, axis string, value int) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "" cellData.V = strconv.Itoa(value) return err }
[ "func", "(", "f", "*", "File", ")", "SetCellInt", "(", "sheet", ",", "axis", "string", ",", "value", "int", ")", "error", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ",", "col", ",", "_", ",", "err", ":=", "f", ".", "prepareCell", "(", "xlsx", ",", "sheet", ",", "axis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ".", "S", "=", "f", ".", "prepareCellStyle", "(", "xlsx", ",", "col", ",", "cellData", ".", "S", ")", "\n", "cellData", ".", "T", "=", "\"", "\"", "\n", "cellData", ".", "V", "=", "strconv", ".", "Itoa", "(", "value", ")", "\n", "return", "err", "\n", "}" ]
// SetCellInt provides a function to set int type value of a cell by given // worksheet name, cell coordinates and cell value.
[ "SetCellInt", "provides", "a", "function", "to", "set", "int", "type", "value", "of", "a", "cell", "by", "given", "worksheet", "name", "cell", "coordinates", "and", "cell", "value", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L157-L170
158,260
360EntSecGroup-Skylar/excelize
cell.go
SetCellBool
func (f *File) SetCellBool(sheet, axis string, value bool) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "b" if value { cellData.V = "1" } else { cellData.V = "0" } return err }
go
func (f *File) SetCellBool(sheet, axis string, value bool) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "b" if value { cellData.V = "1" } else { cellData.V = "0" } return err }
[ "func", "(", "f", "*", "File", ")", "SetCellBool", "(", "sheet", ",", "axis", "string", ",", "value", "bool", ")", "error", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ",", "col", ",", "_", ",", "err", ":=", "f", ".", "prepareCell", "(", "xlsx", ",", "sheet", ",", "axis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ".", "S", "=", "f", ".", "prepareCellStyle", "(", "xlsx", ",", "col", ",", "cellData", ".", "S", ")", "\n", "cellData", ".", "T", "=", "\"", "\"", "\n", "if", "value", "{", "cellData", ".", "V", "=", "\"", "\"", "\n", "}", "else", "{", "cellData", ".", "V", "=", "\"", "\"", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SetCellBool provides a function to set bool type value of a cell by given // worksheet name, cell name and cell value.
[ "SetCellBool", "provides", "a", "function", "to", "set", "bool", "type", "value", "of", "a", "cell", "by", "given", "worksheet", "name", "cell", "name", "and", "cell", "value", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L174-L191
158,261
360EntSecGroup-Skylar/excelize
cell.go
SetCellStr
func (f *File) SetCellStr(sheet, axis, value string) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } if len(value) > 32767 { value = value[0:32767] } // Leading space(s) character detection. if len(value) > 0 && value[0] == 32 { cellData.XMLSpace = xml.Attr{ Name: xml.Name{Space: NameSpaceXML, Local: "space"}, Value: "preserve", } } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "str" cellData.V = value return err }
go
func (f *File) SetCellStr(sheet, axis, value string) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, col, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } if len(value) > 32767 { value = value[0:32767] } // Leading space(s) character detection. if len(value) > 0 && value[0] == 32 { cellData.XMLSpace = xml.Attr{ Name: xml.Name{Space: NameSpaceXML, Local: "space"}, Value: "preserve", } } cellData.S = f.prepareCellStyle(xlsx, col, cellData.S) cellData.T = "str" cellData.V = value return err }
[ "func", "(", "f", "*", "File", ")", "SetCellStr", "(", "sheet", ",", "axis", ",", "value", "string", ")", "error", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ",", "col", ",", "_", ",", "err", ":=", "f", ".", "prepareCell", "(", "xlsx", ",", "sheet", ",", "axis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "value", ")", ">", "32767", "{", "value", "=", "value", "[", "0", ":", "32767", "]", "\n", "}", "\n", "// Leading space(s) character detection.", "if", "len", "(", "value", ")", ">", "0", "&&", "value", "[", "0", "]", "==", "32", "{", "cellData", ".", "XMLSpace", "=", "xml", ".", "Attr", "{", "Name", ":", "xml", ".", "Name", "{", "Space", ":", "NameSpaceXML", ",", "Local", ":", "\"", "\"", "}", ",", "Value", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "cellData", ".", "S", "=", "f", ".", "prepareCellStyle", "(", "xlsx", ",", "col", ",", "cellData", ".", "S", ")", "\n", "cellData", ".", "T", "=", "\"", "\"", "\n", "cellData", ".", "V", "=", "value", "\n", "return", "err", "\n", "}" ]
// SetCellStr provides a function to set string type value of a cell. Total // number of characters that a cell can contain 32767 characters.
[ "SetCellStr", "provides", "a", "function", "to", "set", "string", "type", "value", "of", "a", "cell", ".", "Total", "number", "of", "characters", "that", "a", "cell", "can", "contain", "32767", "characters", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L219-L243
158,262
360EntSecGroup-Skylar/excelize
cell.go
GetCellFormula
func (f *File) GetCellFormula(sheet, axis string) (string, error) { return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) { if c.F == nil { return "", false, nil } if c.F.T == STCellFormulaTypeShared { return getSharedForumula(x, c.F.Si), true, nil } return c.F.Content, true, nil }) }
go
func (f *File) GetCellFormula(sheet, axis string) (string, error) { return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) { if c.F == nil { return "", false, nil } if c.F.T == STCellFormulaTypeShared { return getSharedForumula(x, c.F.Si), true, nil } return c.F.Content, true, nil }) }
[ "func", "(", "f", "*", "File", ")", "GetCellFormula", "(", "sheet", ",", "axis", "string", ")", "(", "string", ",", "error", ")", "{", "return", "f", ".", "getCellStringFunc", "(", "sheet", ",", "axis", ",", "func", "(", "x", "*", "xlsxWorksheet", ",", "c", "*", "xlsxC", ")", "(", "string", ",", "bool", ",", "error", ")", "{", "if", "c", ".", "F", "==", "nil", "{", "return", "\"", "\"", ",", "false", ",", "nil", "\n", "}", "\n", "if", "c", ".", "F", ".", "T", "==", "STCellFormulaTypeShared", "{", "return", "getSharedForumula", "(", "x", ",", "c", ".", "F", ".", "Si", ")", ",", "true", ",", "nil", "\n", "}", "\n", "return", "c", ".", "F", ".", "Content", ",", "true", ",", "nil", "\n", "}", ")", "\n", "}" ]
// GetCellFormula provides a function to get formula from cell by given // worksheet name and axis in XLSX file.
[ "GetCellFormula", "provides", "a", "function", "to", "get", "formula", "from", "cell", "by", "given", "worksheet", "name", "and", "axis", "in", "XLSX", "file", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L264-L274
158,263
360EntSecGroup-Skylar/excelize
cell.go
SetCellFormula
func (f *File) SetCellFormula(sheet, axis, formula string) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, _, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } if formula == "" { cellData.F = nil f.deleteCalcChain(f.GetSheetIndex(sheet), axis) return err } if cellData.F != nil { cellData.F.Content = formula } else { cellData.F = &xlsxF{Content: formula} } return err }
go
func (f *File) SetCellFormula(sheet, axis, formula string) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } cellData, _, _, err := f.prepareCell(xlsx, sheet, axis) if err != nil { return err } if formula == "" { cellData.F = nil f.deleteCalcChain(f.GetSheetIndex(sheet), axis) return err } if cellData.F != nil { cellData.F.Content = formula } else { cellData.F = &xlsxF{Content: formula} } return err }
[ "func", "(", "f", "*", "File", ")", "SetCellFormula", "(", "sheet", ",", "axis", ",", "formula", "string", ")", "error", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cellData", ",", "_", ",", "_", ",", "err", ":=", "f", ".", "prepareCell", "(", "xlsx", ",", "sheet", ",", "axis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "formula", "==", "\"", "\"", "{", "cellData", ".", "F", "=", "nil", "\n", "f", ".", "deleteCalcChain", "(", "f", ".", "GetSheetIndex", "(", "sheet", ")", ",", "axis", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "cellData", ".", "F", "!=", "nil", "{", "cellData", ".", "F", ".", "Content", "=", "formula", "\n", "}", "else", "{", "cellData", ".", "F", "=", "&", "xlsxF", "{", "Content", ":", "formula", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SetCellFormula provides a function to set cell formula by given string and // worksheet name.
[ "SetCellFormula", "provides", "a", "function", "to", "set", "cell", "formula", "by", "given", "string", "and", "worksheet", "name", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L278-L299
158,264
360EntSecGroup-Skylar/excelize
cell.go
formattedValue
func (f *File) formattedValue(s int, v string) string { if s == 0 { return v } styleSheet := f.stylesReader() ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID] if ok != nil { return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v) } return v }
go
func (f *File) formattedValue(s int, v string) string { if s == 0 { return v } styleSheet := f.stylesReader() ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID] if ok != nil { return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v) } return v }
[ "func", "(", "f", "*", "File", ")", "formattedValue", "(", "s", "int", ",", "v", "string", ")", "string", "{", "if", "s", "==", "0", "{", "return", "v", "\n", "}", "\n", "styleSheet", ":=", "f", ".", "stylesReader", "(", ")", "\n", "ok", ":=", "builtInNumFmtFunc", "[", "styleSheet", ".", "CellXfs", ".", "Xf", "[", "s", "]", ".", "NumFmtID", "]", "\n", "if", "ok", "!=", "nil", "{", "return", "ok", "(", "styleSheet", ".", "CellXfs", ".", "Xf", "[", "s", "]", ".", "NumFmtID", ",", "v", ")", "\n", "}", "\n", "return", "v", "\n", "}" ]
// formattedValue provides a function to returns a value after formatted. If // it is possible to apply a format to the cell value, it will do so, if not // then an error will be returned, along with the raw value of the cell.
[ "formattedValue", "provides", "a", "function", "to", "returns", "a", "value", "after", "formatted", ".", "If", "it", "is", "possible", "to", "apply", "a", "format", "to", "the", "cell", "value", "it", "will", "do", "so", "if", "not", "then", "an", "error", "will", "be", "returned", "along", "with", "the", "raw", "value", "of", "the", "cell", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L556-L566
158,265
360EntSecGroup-Skylar/excelize
cell.go
prepareCellStyle
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int { if xlsx.Cols != nil && style == 0 { for _, c := range xlsx.Cols.Col { if c.Min <= col && col <= c.Max { style = c.Style } } } return style }
go
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int { if xlsx.Cols != nil && style == 0 { for _, c := range xlsx.Cols.Col { if c.Min <= col && col <= c.Max { style = c.Style } } } return style }
[ "func", "(", "f", "*", "File", ")", "prepareCellStyle", "(", "xlsx", "*", "xlsxWorksheet", ",", "col", ",", "style", "int", ")", "int", "{", "if", "xlsx", ".", "Cols", "!=", "nil", "&&", "style", "==", "0", "{", "for", "_", ",", "c", ":=", "range", "xlsx", ".", "Cols", ".", "Col", "{", "if", "c", ".", "Min", "<=", "col", "&&", "col", "<=", "c", ".", "Max", "{", "style", "=", "c", ".", "Style", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "style", "\n", "}" ]
// prepareCellStyle provides a function to prepare style index of cell in // worksheet by given column index and style index.
[ "prepareCellStyle", "provides", "a", "function", "to", "prepare", "style", "index", "of", "cell", "in", "worksheet", "by", "given", "column", "index", "and", "style", "index", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L570-L579
158,266
360EntSecGroup-Skylar/excelize
cell.go
mergeCellsParser
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) { axis = strings.ToUpper(axis) if xlsx.MergeCells != nil { for i := 0; i < len(xlsx.MergeCells.Cells); i++ { ok, err := checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) if err != nil { return axis, err } if ok { axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0] } } } return axis, nil }
go
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) { axis = strings.ToUpper(axis) if xlsx.MergeCells != nil { for i := 0; i < len(xlsx.MergeCells.Cells); i++ { ok, err := checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) if err != nil { return axis, err } if ok { axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0] } } } return axis, nil }
[ "func", "(", "f", "*", "File", ")", "mergeCellsParser", "(", "xlsx", "*", "xlsxWorksheet", ",", "axis", "string", ")", "(", "string", ",", "error", ")", "{", "axis", "=", "strings", ".", "ToUpper", "(", "axis", ")", "\n", "if", "xlsx", ".", "MergeCells", "!=", "nil", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "xlsx", ".", "MergeCells", ".", "Cells", ")", ";", "i", "++", "{", "ok", ",", "err", ":=", "checkCellInArea", "(", "axis", ",", "xlsx", ".", "MergeCells", ".", "Cells", "[", "i", "]", ".", "Ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "axis", ",", "err", "\n", "}", "\n", "if", "ok", "{", "axis", "=", "strings", ".", "Split", "(", "xlsx", ".", "MergeCells", ".", "Cells", "[", "i", "]", ".", "Ref", ",", "\"", "\"", ")", "[", "0", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "axis", ",", "nil", "\n", "}" ]
// mergeCellsParser provides a function to check merged cells in worksheet by // given axis.
[ "mergeCellsParser", "provides", "a", "function", "to", "check", "merged", "cells", "in", "worksheet", "by", "given", "axis", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L583-L597
158,267
360EntSecGroup-Skylar/excelize
cell.go
checkCellInArea
func checkCellInArea(cell, area string) (bool, error) { col, row, err := CellNameToCoordinates(cell) if err != nil { return false, err } rng := strings.Split(area, ":") if len(rng) != 2 { return false, err } firstCol, firstRow, _ := CellNameToCoordinates(rng[0]) lastCol, lastRow, _ := CellNameToCoordinates(rng[1]) return col >= firstCol && col <= lastCol && row >= firstRow && row <= lastRow, err }
go
func checkCellInArea(cell, area string) (bool, error) { col, row, err := CellNameToCoordinates(cell) if err != nil { return false, err } rng := strings.Split(area, ":") if len(rng) != 2 { return false, err } firstCol, firstRow, _ := CellNameToCoordinates(rng[0]) lastCol, lastRow, _ := CellNameToCoordinates(rng[1]) return col >= firstCol && col <= lastCol && row >= firstRow && row <= lastRow, err }
[ "func", "checkCellInArea", "(", "cell", ",", "area", "string", ")", "(", "bool", ",", "error", ")", "{", "col", ",", "row", ",", "err", ":=", "CellNameToCoordinates", "(", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "rng", ":=", "strings", ".", "Split", "(", "area", ",", "\"", "\"", ")", "\n", "if", "len", "(", "rng", ")", "!=", "2", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "firstCol", ",", "firstRow", ",", "_", ":=", "CellNameToCoordinates", "(", "rng", "[", "0", "]", ")", "\n", "lastCol", ",", "lastRow", ",", "_", ":=", "CellNameToCoordinates", "(", "rng", "[", "1", "]", ")", "\n\n", "return", "col", ">=", "firstCol", "&&", "col", "<=", "lastCol", "&&", "row", ">=", "firstRow", "&&", "row", "<=", "lastRow", ",", "err", "\n", "}" ]
// checkCellInArea provides a function to determine if a given coordinate is // within an area.
[ "checkCellInArea", "provides", "a", "function", "to", "determine", "if", "a", "given", "coordinate", "is", "within", "an", "area", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L601-L616
158,268
360EntSecGroup-Skylar/excelize
cell.go
getSharedForumula
func getSharedForumula(xlsx *xlsxWorksheet, si string) string { for _, r := range xlsx.SheetData.Row { for _, c := range r.C { if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si { return c.F.Content } } } return "" }
go
func getSharedForumula(xlsx *xlsxWorksheet, si string) string { for _, r := range xlsx.SheetData.Row { for _, c := range r.C { if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si { return c.F.Content } } } return "" }
[ "func", "getSharedForumula", "(", "xlsx", "*", "xlsxWorksheet", ",", "si", "string", ")", "string", "{", "for", "_", ",", "r", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "{", "for", "_", ",", "c", ":=", "range", "r", ".", "C", "{", "if", "c", ".", "F", "!=", "nil", "&&", "c", ".", "F", ".", "Ref", "!=", "\"", "\"", "&&", "c", ".", "F", ".", "T", "==", "STCellFormulaTypeShared", "&&", "c", ".", "F", ".", "Si", "==", "si", "{", "return", "c", ".", "F", ".", "Content", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// getSharedForumula find a cell contains the same formula as another cell, // the "shared" value can be used for the t attribute and the si attribute can // be used to refer to the cell containing the formula. Two formulas are // considered to be the same when their respective representations in // R1C1-reference notation, are the same. // // Note that this function not validate ref tag to check the cell if or not in // allow area, and always return origin shared formula.
[ "getSharedForumula", "find", "a", "cell", "contains", "the", "same", "formula", "as", "another", "cell", "the", "shared", "value", "can", "be", "used", "for", "the", "t", "attribute", "and", "the", "si", "attribute", "can", "be", "used", "to", "refer", "to", "the", "cell", "containing", "the", "formula", ".", "Two", "formulas", "are", "considered", "to", "be", "the", "same", "when", "their", "respective", "representations", "in", "R1C1", "-", "reference", "notation", "are", "the", "same", ".", "Note", "that", "this", "function", "not", "validate", "ref", "tag", "to", "check", "the", "cell", "if", "or", "not", "in", "allow", "area", "and", "always", "return", "origin", "shared", "formula", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cell.go#L626-L635
158,269
360EntSecGroup-Skylar/excelize
comment.go
parseFormatCommentsSet
func parseFormatCommentsSet(formatSet string) (*formatComment, error) { format := formatComment{ Author: "Author:", Text: " ", } err := json.Unmarshal([]byte(formatSet), &format) return &format, err }
go
func parseFormatCommentsSet(formatSet string) (*formatComment, error) { format := formatComment{ Author: "Author:", Text: " ", } err := json.Unmarshal([]byte(formatSet), &format) return &format, err }
[ "func", "parseFormatCommentsSet", "(", "formatSet", "string", ")", "(", "*", "formatComment", ",", "error", ")", "{", "format", ":=", "formatComment", "{", "Author", ":", "\"", "\"", ",", "Text", ":", "\"", "\"", ",", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "formatSet", ")", ",", "&", "format", ")", "\n", "return", "&", "format", ",", "err", "\n", "}" ]
// parseFormatCommentsSet provides a function to parse the format settings of // the comment with default value.
[ "parseFormatCommentsSet", "provides", "a", "function", "to", "parse", "the", "format", "settings", "of", "the", "comment", "with", "default", "value", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/comment.go#L22-L29
158,270
360EntSecGroup-Skylar/excelize
comment.go
GetComments
func (f *File) GetComments() (comments map[string][]Comment) { comments = map[string][]Comment{} for n := range f.sheetMap { if d := f.commentsReader("xl" + strings.TrimPrefix(f.getSheetComments(f.GetSheetIndex(n)), "..")); d != nil { sheetComments := []Comment{} for _, comment := range d.CommentList.Comment { sheetComment := Comment{} if comment.AuthorID < len(d.Authors) { sheetComment.Author = d.Authors[comment.AuthorID].Author } sheetComment.Ref = comment.Ref sheetComment.AuthorID = comment.AuthorID for _, text := range comment.Text.R { sheetComment.Text += text.T } sheetComments = append(sheetComments, sheetComment) } comments[n] = sheetComments } } return }
go
func (f *File) GetComments() (comments map[string][]Comment) { comments = map[string][]Comment{} for n := range f.sheetMap { if d := f.commentsReader("xl" + strings.TrimPrefix(f.getSheetComments(f.GetSheetIndex(n)), "..")); d != nil { sheetComments := []Comment{} for _, comment := range d.CommentList.Comment { sheetComment := Comment{} if comment.AuthorID < len(d.Authors) { sheetComment.Author = d.Authors[comment.AuthorID].Author } sheetComment.Ref = comment.Ref sheetComment.AuthorID = comment.AuthorID for _, text := range comment.Text.R { sheetComment.Text += text.T } sheetComments = append(sheetComments, sheetComment) } comments[n] = sheetComments } } return }
[ "func", "(", "f", "*", "File", ")", "GetComments", "(", ")", "(", "comments", "map", "[", "string", "]", "[", "]", "Comment", ")", "{", "comments", "=", "map", "[", "string", "]", "[", "]", "Comment", "{", "}", "\n", "for", "n", ":=", "range", "f", ".", "sheetMap", "{", "if", "d", ":=", "f", ".", "commentsReader", "(", "\"", "\"", "+", "strings", ".", "TrimPrefix", "(", "f", ".", "getSheetComments", "(", "f", ".", "GetSheetIndex", "(", "n", ")", ")", ",", "\"", "\"", ")", ")", ";", "d", "!=", "nil", "{", "sheetComments", ":=", "[", "]", "Comment", "{", "}", "\n", "for", "_", ",", "comment", ":=", "range", "d", ".", "CommentList", ".", "Comment", "{", "sheetComment", ":=", "Comment", "{", "}", "\n", "if", "comment", ".", "AuthorID", "<", "len", "(", "d", ".", "Authors", ")", "{", "sheetComment", ".", "Author", "=", "d", ".", "Authors", "[", "comment", ".", "AuthorID", "]", ".", "Author", "\n", "}", "\n", "sheetComment", ".", "Ref", "=", "comment", ".", "Ref", "\n", "sheetComment", ".", "AuthorID", "=", "comment", ".", "AuthorID", "\n", "for", "_", ",", "text", ":=", "range", "comment", ".", "Text", ".", "R", "{", "sheetComment", ".", "Text", "+=", "text", ".", "T", "\n", "}", "\n", "sheetComments", "=", "append", "(", "sheetComments", ",", "sheetComment", ")", "\n", "}", "\n", "comments", "[", "n", "]", "=", "sheetComments", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// GetComments retrieves all comments and returns a map of worksheet name to // the worksheet comments.
[ "GetComments", "retrieves", "all", "comments", "and", "returns", "a", "map", "of", "worksheet", "name", "to", "the", "worksheet", "comments", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/comment.go#L33-L54
158,271
360EntSecGroup-Skylar/excelize
comment.go
getSheetComments
func (f *File) getSheetComments(sheetID int) string { var rels = "xl/worksheets/_rels/sheet" + strconv.Itoa(sheetID) + ".xml.rels" if sheetRels := f.workSheetRelsReader(rels); sheetRels != nil { for _, v := range sheetRels.Relationships { if v.Type == SourceRelationshipComments { return v.Target } } } return "" }
go
func (f *File) getSheetComments(sheetID int) string { var rels = "xl/worksheets/_rels/sheet" + strconv.Itoa(sheetID) + ".xml.rels" if sheetRels := f.workSheetRelsReader(rels); sheetRels != nil { for _, v := range sheetRels.Relationships { if v.Type == SourceRelationshipComments { return v.Target } } } return "" }
[ "func", "(", "f", "*", "File", ")", "getSheetComments", "(", "sheetID", "int", ")", "string", "{", "var", "rels", "=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "sheetID", ")", "+", "\"", "\"", "\n", "if", "sheetRels", ":=", "f", ".", "workSheetRelsReader", "(", "rels", ")", ";", "sheetRels", "!=", "nil", "{", "for", "_", ",", "v", ":=", "range", "sheetRels", ".", "Relationships", "{", "if", "v", ".", "Type", "==", "SourceRelationshipComments", "{", "return", "v", ".", "Target", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// getSheetComments provides the method to get the target comment reference by // given worksheet index.
[ "getSheetComments", "provides", "the", "method", "to", "get", "the", "target", "comment", "reference", "by", "given", "worksheet", "index", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/comment.go#L58-L68
158,272
360EntSecGroup-Skylar/excelize
comment.go
countComments
func (f *File) countComments() int { count := 0 for k := range f.XLSX { if strings.Contains(k, "xl/comments") { count++ } } return count }
go
func (f *File) countComments() int { count := 0 for k := range f.XLSX { if strings.Contains(k, "xl/comments") { count++ } } return count }
[ "func", "(", "f", "*", "File", ")", "countComments", "(", ")", "int", "{", "count", ":=", "0", "\n", "for", "k", ":=", "range", "f", ".", "XLSX", "{", "if", "strings", ".", "Contains", "(", "k", ",", "\"", "\"", ")", "{", "count", "++", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// countComments provides a function to get comments files count storage in // the folder xl.
[ "countComments", "provides", "a", "function", "to", "get", "comments", "files", "count", "storage", "in", "the", "folder", "xl", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/comment.go#L279-L287
158,273
360EntSecGroup-Skylar/excelize
col.go
getColWidth
func (f *File) getColWidth(sheet string, col int) int { xlsx, _ := f.workSheetReader(sheet) if xlsx.Cols != nil { var width float64 for _, v := range xlsx.Cols.Col { if v.Min <= col && col <= v.Max { width = v.Width } } if width != 0 { return int(convertColWidthToPixels(width)) } } // Optimisation for when the column widths haven't changed. return int(defaultColWidthPixels) }
go
func (f *File) getColWidth(sheet string, col int) int { xlsx, _ := f.workSheetReader(sheet) if xlsx.Cols != nil { var width float64 for _, v := range xlsx.Cols.Col { if v.Min <= col && col <= v.Max { width = v.Width } } if width != 0 { return int(convertColWidthToPixels(width)) } } // Optimisation for when the column widths haven't changed. return int(defaultColWidthPixels) }
[ "func", "(", "f", "*", "File", ")", "getColWidth", "(", "sheet", "string", ",", "col", "int", ")", "int", "{", "xlsx", ",", "_", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "xlsx", ".", "Cols", "!=", "nil", "{", "var", "width", "float64", "\n", "for", "_", ",", "v", ":=", "range", "xlsx", ".", "Cols", ".", "Col", "{", "if", "v", ".", "Min", "<=", "col", "&&", "col", "<=", "v", ".", "Max", "{", "width", "=", "v", ".", "Width", "\n", "}", "\n", "}", "\n", "if", "width", "!=", "0", "{", "return", "int", "(", "convertColWidthToPixels", "(", "width", ")", ")", "\n", "}", "\n", "}", "\n", "// Optimisation for when the column widths haven't changed.", "return", "int", "(", "defaultColWidthPixels", ")", "\n", "}" ]
// getColWidth provides a function to get column width in pixels by given // sheet name and column index.
[ "getColWidth", "provides", "a", "function", "to", "get", "column", "width", "in", "pixels", "by", "given", "sheet", "name", "and", "column", "index", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/col.go#L305-L320
158,274
360EntSecGroup-Skylar/excelize
col.go
GetColWidth
func (f *File) GetColWidth(sheet, col string) (float64, error) { colNum, err := ColumnNameToNumber(col) if err != nil { return defaultColWidthPixels, err } xlsx, err := f.workSheetReader(sheet) if err != nil { return defaultColWidthPixels, err } if xlsx.Cols != nil { var width float64 for _, v := range xlsx.Cols.Col { if v.Min <= colNum && colNum <= v.Max { width = v.Width } } if width != 0 { return width, err } } // Optimisation for when the column widths haven't changed. return defaultColWidthPixels, err }
go
func (f *File) GetColWidth(sheet, col string) (float64, error) { colNum, err := ColumnNameToNumber(col) if err != nil { return defaultColWidthPixels, err } xlsx, err := f.workSheetReader(sheet) if err != nil { return defaultColWidthPixels, err } if xlsx.Cols != nil { var width float64 for _, v := range xlsx.Cols.Col { if v.Min <= colNum && colNum <= v.Max { width = v.Width } } if width != 0 { return width, err } } // Optimisation for when the column widths haven't changed. return defaultColWidthPixels, err }
[ "func", "(", "f", "*", "File", ")", "GetColWidth", "(", "sheet", ",", "col", "string", ")", "(", "float64", ",", "error", ")", "{", "colNum", ",", "err", ":=", "ColumnNameToNumber", "(", "col", ")", "\n", "if", "err", "!=", "nil", "{", "return", "defaultColWidthPixels", ",", "err", "\n", "}", "\n", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "defaultColWidthPixels", ",", "err", "\n", "}", "\n", "if", "xlsx", ".", "Cols", "!=", "nil", "{", "var", "width", "float64", "\n", "for", "_", ",", "v", ":=", "range", "xlsx", ".", "Cols", ".", "Col", "{", "if", "v", ".", "Min", "<=", "colNum", "&&", "colNum", "<=", "v", ".", "Max", "{", "width", "=", "v", ".", "Width", "\n", "}", "\n", "}", "\n", "if", "width", "!=", "0", "{", "return", "width", ",", "err", "\n", "}", "\n", "}", "\n", "// Optimisation for when the column widths haven't changed.", "return", "defaultColWidthPixels", ",", "err", "\n", "}" ]
// GetColWidth provides a function to get column width by given worksheet name // and column index.
[ "GetColWidth", "provides", "a", "function", "to", "get", "column", "width", "by", "given", "worksheet", "name", "and", "column", "index", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/col.go#L324-L346
158,275
360EntSecGroup-Skylar/excelize
col.go
convertColWidthToPixels
func convertColWidthToPixels(width float64) float64 { var padding float64 = 5 var pixels float64 var maxDigitWidth float64 = 7 if width == 0 { return pixels } if width < 1 { pixels = (width * 12) + 0.5 return math.Ceil(pixels) } pixels = (width*maxDigitWidth + 0.5) + padding return math.Ceil(pixels) }
go
func convertColWidthToPixels(width float64) float64 { var padding float64 = 5 var pixels float64 var maxDigitWidth float64 = 7 if width == 0 { return pixels } if width < 1 { pixels = (width * 12) + 0.5 return math.Ceil(pixels) } pixels = (width*maxDigitWidth + 0.5) + padding return math.Ceil(pixels) }
[ "func", "convertColWidthToPixels", "(", "width", "float64", ")", "float64", "{", "var", "padding", "float64", "=", "5", "\n", "var", "pixels", "float64", "\n", "var", "maxDigitWidth", "float64", "=", "7", "\n", "if", "width", "==", "0", "{", "return", "pixels", "\n", "}", "\n", "if", "width", "<", "1", "{", "pixels", "=", "(", "width", "*", "12", ")", "+", "0.5", "\n", "return", "math", ".", "Ceil", "(", "pixels", ")", "\n", "}", "\n", "pixels", "=", "(", "width", "*", "maxDigitWidth", "+", "0.5", ")", "+", "padding", "\n", "return", "math", ".", "Ceil", "(", "pixels", ")", "\n", "}" ]
// convertColWidthToPixels provieds function to convert the width of a cell // from user's units to pixels. Excel rounds the column width to the nearest // pixel. If the width hasn't been set by the user we use the default value. // If the column is hidden it has a value of zero.
[ "convertColWidthToPixels", "provieds", "function", "to", "convert", "the", "width", "of", "a", "cell", "from", "user", "s", "units", "to", "pixels", ".", "Excel", "rounds", "the", "column", "width", "to", "the", "nearest", "pixel", ".", "If", "the", "width", "hasn", "t", "been", "set", "by", "the", "user", "we", "use", "the", "default", "value", ".", "If", "the", "column", "is", "hidden", "it", "has", "a", "value", "of", "zero", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/col.go#L397-L410
158,276
360EntSecGroup-Skylar/excelize
sheetpr.go
getSheetPrOption
func (o *CodeName) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = "" return } *o = CodeName(pr.CodeName) }
go
func (o *CodeName) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = "" return } *o = CodeName(pr.CodeName) }
[ "func", "(", "o", "*", "CodeName", ")", "getSheetPrOption", "(", "pr", "*", "xlsxSheetPr", ")", "{", "if", "pr", "==", "nil", "{", "*", "o", "=", "\"", "\"", "\n", "return", "\n", "}", "\n", "*", "o", "=", "CodeName", "(", "pr", ".", "CodeName", ")", "\n", "}" ]
// getSheetPrOption implements the SheetPrOptionPtr interface and get the // stable name of the sheet.
[ "getSheetPrOption", "implements", "the", "SheetPrOptionPtr", "interface", "and", "get", "the", "stable", "name", "of", "the", "sheet", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetpr.go#L64-L70
158,277
360EntSecGroup-Skylar/excelize
sheetpr.go
setSheetPrOption
func (o EnableFormatConditionsCalculation) setSheetPrOption(pr *xlsxSheetPr) { pr.EnableFormatConditionsCalculation = boolPtr(bool(o)) }
go
func (o EnableFormatConditionsCalculation) setSheetPrOption(pr *xlsxSheetPr) { pr.EnableFormatConditionsCalculation = boolPtr(bool(o)) }
[ "func", "(", "o", "EnableFormatConditionsCalculation", ")", "setSheetPrOption", "(", "pr", "*", "xlsxSheetPr", ")", "{", "pr", ".", "EnableFormatConditionsCalculation", "=", "boolPtr", "(", "bool", "(", "o", ")", ")", "\n", "}" ]
// setSheetPrOption implements the SheetPrOption interface and flag indicating // whether the conditional formatting calculations shall be evaluated.
[ "setSheetPrOption", "implements", "the", "SheetPrOption", "interface", "and", "flag", "indicating", "whether", "the", "conditional", "formatting", "calculations", "shall", "be", "evaluated", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetpr.go#L74-L76
158,278
360EntSecGroup-Skylar/excelize
sheetpr.go
getSheetPrOption
func (o *EnableFormatConditionsCalculation) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = true return } *o = EnableFormatConditionsCalculation(defaultTrue(pr.EnableFormatConditionsCalculation)) }
go
func (o *EnableFormatConditionsCalculation) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = true return } *o = EnableFormatConditionsCalculation(defaultTrue(pr.EnableFormatConditionsCalculation)) }
[ "func", "(", "o", "*", "EnableFormatConditionsCalculation", ")", "getSheetPrOption", "(", "pr", "*", "xlsxSheetPr", ")", "{", "if", "pr", "==", "nil", "{", "*", "o", "=", "true", "\n", "return", "\n", "}", "\n", "*", "o", "=", "EnableFormatConditionsCalculation", "(", "defaultTrue", "(", "pr", ".", "EnableFormatConditionsCalculation", ")", ")", "\n", "}" ]
// getSheetPrOption implements the SheetPrOptionPtr interface and get the // settings of whether the conditional formatting calculations shall be // evaluated.
[ "getSheetPrOption", "implements", "the", "SheetPrOptionPtr", "interface", "and", "get", "the", "settings", "of", "whether", "the", "conditional", "formatting", "calculations", "shall", "be", "evaluated", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetpr.go#L81-L87
158,279
360EntSecGroup-Skylar/excelize
sheetpr.go
setSheetPrOption
func (o Published) setSheetPrOption(pr *xlsxSheetPr) { pr.Published = boolPtr(bool(o)) }
go
func (o Published) setSheetPrOption(pr *xlsxSheetPr) { pr.Published = boolPtr(bool(o)) }
[ "func", "(", "o", "Published", ")", "setSheetPrOption", "(", "pr", "*", "xlsxSheetPr", ")", "{", "pr", ".", "Published", "=", "boolPtr", "(", "bool", "(", "o", ")", ")", "\n", "}" ]
// setSheetPrOption implements the SheetPrOption interface and flag indicating // whether the worksheet is published.
[ "setSheetPrOption", "implements", "the", "SheetPrOption", "interface", "and", "flag", "indicating", "whether", "the", "worksheet", "is", "published", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetpr.go#L91-L93
158,280
360EntSecGroup-Skylar/excelize
sheetpr.go
getSheetPrOption
func (o *Published) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = true return } *o = Published(defaultTrue(pr.Published)) }
go
func (o *Published) getSheetPrOption(pr *xlsxSheetPr) { if pr == nil { *o = true return } *o = Published(defaultTrue(pr.Published)) }
[ "func", "(", "o", "*", "Published", ")", "getSheetPrOption", "(", "pr", "*", "xlsxSheetPr", ")", "{", "if", "pr", "==", "nil", "{", "*", "o", "=", "true", "\n", "return", "\n", "}", "\n", "*", "o", "=", "Published", "(", "defaultTrue", "(", "pr", ".", "Published", ")", ")", "\n", "}" ]
// getSheetPrOption implements the SheetPrOptionPtr interface and get the // settings of whether the worksheet is published.
[ "getSheetPrOption", "implements", "the", "SheetPrOptionPtr", "interface", "and", "get", "the", "settings", "of", "whether", "the", "worksheet", "is", "published", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetpr.go#L97-L103
158,281
360EntSecGroup-Skylar/excelize
sheetview.go
getSheetView
func (f *File) getSheetView(sheetName string, viewIndex int) (*xlsxSheetView, error) { xlsx, err := f.workSheetReader(sheetName) if err != nil { return nil, err } if viewIndex < 0 { if viewIndex < -len(xlsx.SheetViews.SheetView) { return nil, fmt.Errorf("view index %d out of range", viewIndex) } viewIndex = len(xlsx.SheetViews.SheetView) + viewIndex } else if viewIndex >= len(xlsx.SheetViews.SheetView) { return nil, fmt.Errorf("view index %d out of range", viewIndex) } return &(xlsx.SheetViews.SheetView[viewIndex]), err }
go
func (f *File) getSheetView(sheetName string, viewIndex int) (*xlsxSheetView, error) { xlsx, err := f.workSheetReader(sheetName) if err != nil { return nil, err } if viewIndex < 0 { if viewIndex < -len(xlsx.SheetViews.SheetView) { return nil, fmt.Errorf("view index %d out of range", viewIndex) } viewIndex = len(xlsx.SheetViews.SheetView) + viewIndex } else if viewIndex >= len(xlsx.SheetViews.SheetView) { return nil, fmt.Errorf("view index %d out of range", viewIndex) } return &(xlsx.SheetViews.SheetView[viewIndex]), err }
[ "func", "(", "f", "*", "File", ")", "getSheetView", "(", "sheetName", "string", ",", "viewIndex", "int", ")", "(", "*", "xlsxSheetView", ",", "error", ")", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheetName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "viewIndex", "<", "0", "{", "if", "viewIndex", "<", "-", "len", "(", "xlsx", ".", "SheetViews", ".", "SheetView", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "viewIndex", ")", "\n", "}", "\n", "viewIndex", "=", "len", "(", "xlsx", ".", "SheetViews", ".", "SheetView", ")", "+", "viewIndex", "\n", "}", "else", "if", "viewIndex", ">=", "len", "(", "xlsx", ".", "SheetViews", ".", "SheetView", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "viewIndex", ")", "\n", "}", "\n\n", "return", "&", "(", "xlsx", ".", "SheetViews", ".", "SheetView", "[", "viewIndex", "]", ")", ",", "err", "\n", "}" ]
// getSheetView returns the SheetView object
[ "getSheetView", "returns", "the", "SheetView", "object" ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/sheetview.go#L112-L127
158,282
360EntSecGroup-Skylar/excelize
excelize.go
OpenFile
func OpenFile(filename string) (*File, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() f, err := OpenReader(file) if err != nil { return nil, err } f.Path = filename return f, nil }
go
func OpenFile(filename string) (*File, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() f, err := OpenReader(file) if err != nil { return nil, err } f.Path = filename return f, nil }
[ "func", "OpenFile", "(", "filename", "string", ")", "(", "*", "File", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "f", ",", "err", ":=", "OpenReader", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ".", "Path", "=", "filename", "\n", "return", "f", ",", "nil", "\n", "}" ]
// OpenFile take the name of an XLSX file and returns a populated XLSX file // struct for it.
[ "OpenFile", "take", "the", "name", "of", "an", "XLSX", "file", "and", "returns", "a", "populated", "XLSX", "file", "struct", "for", "it", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/excelize.go#L49-L61
158,283
360EntSecGroup-Skylar/excelize
excelize.go
OpenReader
func OpenReader(r io.Reader) (*File, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return nil, err } file, sheetCount, err := ReadZipReader(zr) if err != nil { return nil, err } f := &File{ checked: make(map[string]bool), Comments: make(map[string]*xlsxComments), DrawingRels: make(map[string]*xlsxWorkbookRels), Drawings: make(map[string]*xlsxWsDr), Sheet: make(map[string]*xlsxWorksheet), SheetCount: sheetCount, DecodeVMLDrawing: make(map[string]*decodeVmlDrawing), VMLDrawing: make(map[string]*vmlDrawing), WorkSheetRels: make(map[string]*xlsxWorkbookRels), XLSX: file, } f.CalcChain = f.calcChainReader() f.sheetMap = f.getSheetMap() f.Styles = f.stylesReader() f.Theme = f.themeReader() return f, nil }
go
func OpenReader(r io.Reader) (*File, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { return nil, err } file, sheetCount, err := ReadZipReader(zr) if err != nil { return nil, err } f := &File{ checked: make(map[string]bool), Comments: make(map[string]*xlsxComments), DrawingRels: make(map[string]*xlsxWorkbookRels), Drawings: make(map[string]*xlsxWsDr), Sheet: make(map[string]*xlsxWorksheet), SheetCount: sheetCount, DecodeVMLDrawing: make(map[string]*decodeVmlDrawing), VMLDrawing: make(map[string]*vmlDrawing), WorkSheetRels: make(map[string]*xlsxWorkbookRels), XLSX: file, } f.CalcChain = f.calcChainReader() f.sheetMap = f.getSheetMap() f.Styles = f.stylesReader() f.Theme = f.themeReader() return f, nil }
[ "func", "OpenReader", "(", "r", "io", ".", "Reader", ")", "(", "*", "File", ",", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "zr", ",", "err", ":=", "zip", ".", "NewReader", "(", "bytes", ".", "NewReader", "(", "b", ")", ",", "int64", "(", "len", "(", "b", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "file", ",", "sheetCount", ",", "err", ":=", "ReadZipReader", "(", "zr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ":=", "&", "File", "{", "checked", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "Comments", ":", "make", "(", "map", "[", "string", "]", "*", "xlsxComments", ")", ",", "DrawingRels", ":", "make", "(", "map", "[", "string", "]", "*", "xlsxWorkbookRels", ")", ",", "Drawings", ":", "make", "(", "map", "[", "string", "]", "*", "xlsxWsDr", ")", ",", "Sheet", ":", "make", "(", "map", "[", "string", "]", "*", "xlsxWorksheet", ")", ",", "SheetCount", ":", "sheetCount", ",", "DecodeVMLDrawing", ":", "make", "(", "map", "[", "string", "]", "*", "decodeVmlDrawing", ")", ",", "VMLDrawing", ":", "make", "(", "map", "[", "string", "]", "*", "vmlDrawing", ")", ",", "WorkSheetRels", ":", "make", "(", "map", "[", "string", "]", "*", "xlsxWorkbookRels", ")", ",", "XLSX", ":", "file", ",", "}", "\n", "f", ".", "CalcChain", "=", "f", ".", "calcChainReader", "(", ")", "\n", "f", ".", "sheetMap", "=", "f", ".", "getSheetMap", "(", ")", "\n", "f", ".", "Styles", "=", "f", ".", "stylesReader", "(", ")", "\n", "f", ".", "Theme", "=", "f", ".", "themeReader", "(", ")", "\n", "return", "f", ",", "nil", "\n", "}" ]
// OpenReader take an io.Reader and return a populated XLSX file.
[ "OpenReader", "take", "an", "io", ".", "Reader", "and", "return", "a", "populated", "XLSX", "file", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/excelize.go#L64-L96
158,284
360EntSecGroup-Skylar/excelize
excelize.go
setDefaultTimeStyle
func (f *File) setDefaultTimeStyle(sheet, axis string, format int) error { s, err := f.GetCellStyle(sheet, axis) if err != nil { return err } if s == 0 { style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`) f.SetCellStyle(sheet, axis, axis, style) } return err }
go
func (f *File) setDefaultTimeStyle(sheet, axis string, format int) error { s, err := f.GetCellStyle(sheet, axis) if err != nil { return err } if s == 0 { style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`) f.SetCellStyle(sheet, axis, axis, style) } return err }
[ "func", "(", "f", "*", "File", ")", "setDefaultTimeStyle", "(", "sheet", ",", "axis", "string", ",", "format", "int", ")", "error", "{", "s", ",", "err", ":=", "f", ".", "GetCellStyle", "(", "sheet", ",", "axis", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "s", "==", "0", "{", "style", ",", "_", ":=", "f", ".", "NewStyle", "(", "`{\"number_format\": `", "+", "strconv", ".", "Itoa", "(", "format", ")", "+", "`}`", ")", "\n", "f", ".", "SetCellStyle", "(", "sheet", ",", "axis", ",", "axis", ",", "style", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// setDefaultTimeStyle provides a function to set default numbers format for // time.Time type cell value by given worksheet name, cell coordinates and // number format code.
[ "setDefaultTimeStyle", "provides", "a", "function", "to", "set", "default", "numbers", "format", "for", "time", ".", "Time", "type", "cell", "value", "by", "given", "worksheet", "name", "cell", "coordinates", "and", "number", "format", "code", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/excelize.go#L101-L111
158,285
360EntSecGroup-Skylar/excelize
excelize.go
workSheetReader
func (f *File) workSheetReader(sheet string) (*xlsxWorksheet, error) { name, ok := f.sheetMap[trimSheetName(sheet)] if !ok { return nil, fmt.Errorf("sheet %s is not exist", sheet) } if f.Sheet[name] == nil { var xlsx xlsxWorksheet _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(name)), &xlsx) if f.checked == nil { f.checked = make(map[string]bool) } ok := f.checked[name] if !ok { checkSheet(&xlsx) checkRow(&xlsx) f.checked[name] = true } f.Sheet[name] = &xlsx } return f.Sheet[name], nil }
go
func (f *File) workSheetReader(sheet string) (*xlsxWorksheet, error) { name, ok := f.sheetMap[trimSheetName(sheet)] if !ok { return nil, fmt.Errorf("sheet %s is not exist", sheet) } if f.Sheet[name] == nil { var xlsx xlsxWorksheet _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(name)), &xlsx) if f.checked == nil { f.checked = make(map[string]bool) } ok := f.checked[name] if !ok { checkSheet(&xlsx) checkRow(&xlsx) f.checked[name] = true } f.Sheet[name] = &xlsx } return f.Sheet[name], nil }
[ "func", "(", "f", "*", "File", ")", "workSheetReader", "(", "sheet", "string", ")", "(", "*", "xlsxWorksheet", ",", "error", ")", "{", "name", ",", "ok", ":=", "f", ".", "sheetMap", "[", "trimSheetName", "(", "sheet", ")", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sheet", ")", "\n", "}", "\n", "if", "f", ".", "Sheet", "[", "name", "]", "==", "nil", "{", "var", "xlsx", "xlsxWorksheet", "\n", "_", "=", "xml", ".", "Unmarshal", "(", "namespaceStrictToTransitional", "(", "f", ".", "readXML", "(", "name", ")", ")", ",", "&", "xlsx", ")", "\n", "if", "f", ".", "checked", "==", "nil", "{", "f", ".", "checked", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "}", "\n", "ok", ":=", "f", ".", "checked", "[", "name", "]", "\n", "if", "!", "ok", "{", "checkSheet", "(", "&", "xlsx", ")", "\n", "checkRow", "(", "&", "xlsx", ")", "\n", "f", ".", "checked", "[", "name", "]", "=", "true", "\n", "}", "\n", "f", ".", "Sheet", "[", "name", "]", "=", "&", "xlsx", "\n", "}", "\n", "return", "f", ".", "Sheet", "[", "name", "]", ",", "nil", "\n", "}" ]
// workSheetReader provides a function to get the pointer to the structure // after deserialization by given worksheet name.
[ "workSheetReader", "provides", "a", "function", "to", "get", "the", "pointer", "to", "the", "structure", "after", "deserialization", "by", "given", "worksheet", "name", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/excelize.go#L115-L135
158,286
360EntSecGroup-Skylar/excelize
excelize.go
checkSheet
func checkSheet(xlsx *xlsxWorksheet) { row := len(xlsx.SheetData.Row) if row >= 1 { lastRow := xlsx.SheetData.Row[row-1].R if lastRow >= row { row = lastRow } } sheetData := xlsxSheetData{} existsRows := map[int]int{} for k := range xlsx.SheetData.Row { existsRows[xlsx.SheetData.Row[k].R] = k } for i := 0; i < row; i++ { _, ok := existsRows[i+1] if ok { sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]]) } else { sheetData.Row = append(sheetData.Row, xlsxRow{ R: i + 1, }) } } xlsx.SheetData = sheetData }
go
func checkSheet(xlsx *xlsxWorksheet) { row := len(xlsx.SheetData.Row) if row >= 1 { lastRow := xlsx.SheetData.Row[row-1].R if lastRow >= row { row = lastRow } } sheetData := xlsxSheetData{} existsRows := map[int]int{} for k := range xlsx.SheetData.Row { existsRows[xlsx.SheetData.Row[k].R] = k } for i := 0; i < row; i++ { _, ok := existsRows[i+1] if ok { sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]]) } else { sheetData.Row = append(sheetData.Row, xlsxRow{ R: i + 1, }) } } xlsx.SheetData = sheetData }
[ "func", "checkSheet", "(", "xlsx", "*", "xlsxWorksheet", ")", "{", "row", ":=", "len", "(", "xlsx", ".", "SheetData", ".", "Row", ")", "\n", "if", "row", ">=", "1", "{", "lastRow", ":=", "xlsx", ".", "SheetData", ".", "Row", "[", "row", "-", "1", "]", ".", "R", "\n", "if", "lastRow", ">=", "row", "{", "row", "=", "lastRow", "\n", "}", "\n", "}", "\n", "sheetData", ":=", "xlsxSheetData", "{", "}", "\n", "existsRows", ":=", "map", "[", "int", "]", "int", "{", "}", "\n", "for", "k", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "{", "existsRows", "[", "xlsx", ".", "SheetData", ".", "Row", "[", "k", "]", ".", "R", "]", "=", "k", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "row", ";", "i", "++", "{", "_", ",", "ok", ":=", "existsRows", "[", "i", "+", "1", "]", "\n", "if", "ok", "{", "sheetData", ".", "Row", "=", "append", "(", "sheetData", ".", "Row", ",", "xlsx", ".", "SheetData", ".", "Row", "[", "existsRows", "[", "i", "+", "1", "]", "]", ")", "\n", "}", "else", "{", "sheetData", ".", "Row", "=", "append", "(", "sheetData", ".", "Row", ",", "xlsxRow", "{", "R", ":", "i", "+", "1", ",", "}", ")", "\n", "}", "\n", "}", "\n", "xlsx", ".", "SheetData", "=", "sheetData", "\n", "}" ]
// checkSheet provides a function to fill each row element and make that is // continuous in a worksheet of XML.
[ "checkSheet", "provides", "a", "function", "to", "fill", "each", "row", "element", "and", "make", "that", "is", "continuous", "in", "a", "worksheet", "of", "XML", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/excelize.go#L139-L163
158,287
360EntSecGroup-Skylar/excelize
adjust.go
adjustColDimensions
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) { for rowIdx := range xlsx.SheetData.Row { for colIdx, v := range xlsx.SheetData.Row[rowIdx].C { cellCol, cellRow, _ := CellNameToCoordinates(v.R) if col <= cellCol { if newCol := cellCol + offset; newCol > 0 { xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow) } } } } }
go
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) { for rowIdx := range xlsx.SheetData.Row { for colIdx, v := range xlsx.SheetData.Row[rowIdx].C { cellCol, cellRow, _ := CellNameToCoordinates(v.R) if col <= cellCol { if newCol := cellCol + offset; newCol > 0 { xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow) } } } } }
[ "func", "(", "f", "*", "File", ")", "adjustColDimensions", "(", "xlsx", "*", "xlsxWorksheet", ",", "col", ",", "offset", "int", ")", "{", "for", "rowIdx", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "{", "for", "colIdx", ",", "v", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "[", "rowIdx", "]", ".", "C", "{", "cellCol", ",", "cellRow", ",", "_", ":=", "CellNameToCoordinates", "(", "v", ".", "R", ")", "\n", "if", "col", "<=", "cellCol", "{", "if", "newCol", ":=", "cellCol", "+", "offset", ";", "newCol", ">", "0", "{", "xlsx", ".", "SheetData", ".", "Row", "[", "rowIdx", "]", ".", "C", "[", "colIdx", "]", ".", "R", ",", "_", "=", "CoordinatesToCellName", "(", "newCol", ",", "cellRow", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// adjustColDimensions provides a function to update column dimensions when // inserting or deleting rows or columns.
[ "adjustColDimensions", "provides", "a", "function", "to", "update", "column", "dimensions", "when", "inserting", "or", "deleting", "rows", "or", "columns", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L58-L69
158,288
360EntSecGroup-Skylar/excelize
adjust.go
adjustRowDimensions
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) { for i, r := range xlsx.SheetData.Row { if newRow := r.R + offset; r.R >= row && newRow > 0 { f.ajustSingleRowDimensions(&xlsx.SheetData.Row[i], newRow) } } }
go
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) { for i, r := range xlsx.SheetData.Row { if newRow := r.R + offset; r.R >= row && newRow > 0 { f.ajustSingleRowDimensions(&xlsx.SheetData.Row[i], newRow) } } }
[ "func", "(", "f", "*", "File", ")", "adjustRowDimensions", "(", "xlsx", "*", "xlsxWorksheet", ",", "row", ",", "offset", "int", ")", "{", "for", "i", ",", "r", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "{", "if", "newRow", ":=", "r", ".", "R", "+", "offset", ";", "r", ".", "R", ">=", "row", "&&", "newRow", ">", "0", "{", "f", ".", "ajustSingleRowDimensions", "(", "&", "xlsx", ".", "SheetData", ".", "Row", "[", "i", "]", ",", "newRow", ")", "\n", "}", "\n", "}", "\n", "}" ]
// adjustRowDimensions provides a function to update row dimensions when // inserting or deleting rows or columns.
[ "adjustRowDimensions", "provides", "a", "function", "to", "update", "row", "dimensions", "when", "inserting", "or", "deleting", "rows", "or", "columns", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L73-L79
158,289
360EntSecGroup-Skylar/excelize
adjust.go
ajustSingleRowDimensions
func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) { r.R = num for i, col := range r.C { colName, _, _ := SplitCellName(col.R) r.C[i].R, _ = JoinCellName(colName, num) } }
go
func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) { r.R = num for i, col := range r.C { colName, _, _ := SplitCellName(col.R) r.C[i].R, _ = JoinCellName(colName, num) } }
[ "func", "(", "f", "*", "File", ")", "ajustSingleRowDimensions", "(", "r", "*", "xlsxRow", ",", "num", "int", ")", "{", "r", ".", "R", "=", "num", "\n", "for", "i", ",", "col", ":=", "range", "r", ".", "C", "{", "colName", ",", "_", ",", "_", ":=", "SplitCellName", "(", "col", ".", "R", ")", "\n", "r", ".", "C", "[", "i", "]", ".", "R", ",", "_", "=", "JoinCellName", "(", "colName", ",", "num", ")", "\n", "}", "\n", "}" ]
// ajustSingleRowDimensions provides a function to ajust single row dimensions.
[ "ajustSingleRowDimensions", "provides", "a", "function", "to", "ajust", "single", "row", "dimensions", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L82-L88
158,290
360EntSecGroup-Skylar/excelize
adjust.go
adjustHyperlinks
func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) { // short path if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 { return } // order is important if offset < 0 { for rowIdx, linkData := range xlsx.Hyperlinks.Hyperlink { colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref) if (dir == rows && num == rowNum) || (dir == columns && num == colNum) { f.deleteSheetRelationships(sheet, linkData.RID) if len(xlsx.Hyperlinks.Hyperlink) > 1 { xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:rowIdx], xlsx.Hyperlinks.Hyperlink[rowIdx+1:]...) } else { xlsx.Hyperlinks = nil } } } } if xlsx.Hyperlinks == nil { return } for i := range xlsx.Hyperlinks.Hyperlink { link := &xlsx.Hyperlinks.Hyperlink[i] // get reference colNum, rowNum, _ := CellNameToCoordinates(link.Ref) if dir == rows { if rowNum >= num { link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset) } } else { if colNum >= num { link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum) } } } }
go
func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) { // short path if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 { return } // order is important if offset < 0 { for rowIdx, linkData := range xlsx.Hyperlinks.Hyperlink { colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref) if (dir == rows && num == rowNum) || (dir == columns && num == colNum) { f.deleteSheetRelationships(sheet, linkData.RID) if len(xlsx.Hyperlinks.Hyperlink) > 1 { xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:rowIdx], xlsx.Hyperlinks.Hyperlink[rowIdx+1:]...) } else { xlsx.Hyperlinks = nil } } } } if xlsx.Hyperlinks == nil { return } for i := range xlsx.Hyperlinks.Hyperlink { link := &xlsx.Hyperlinks.Hyperlink[i] // get reference colNum, rowNum, _ := CellNameToCoordinates(link.Ref) if dir == rows { if rowNum >= num { link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset) } } else { if colNum >= num { link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum) } } } }
[ "func", "(", "f", "*", "File", ")", "adjustHyperlinks", "(", "xlsx", "*", "xlsxWorksheet", ",", "sheet", "string", ",", "dir", "adjustDirection", ",", "num", ",", "offset", "int", ")", "{", "// short path", "if", "xlsx", ".", "Hyperlinks", "==", "nil", "||", "len", "(", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "// order is important", "if", "offset", "<", "0", "{", "for", "rowIdx", ",", "linkData", ":=", "range", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "{", "colNum", ",", "rowNum", ",", "_", ":=", "CellNameToCoordinates", "(", "linkData", ".", "Ref", ")", "\n\n", "if", "(", "dir", "==", "rows", "&&", "num", "==", "rowNum", ")", "||", "(", "dir", "==", "columns", "&&", "num", "==", "colNum", ")", "{", "f", ".", "deleteSheetRelationships", "(", "sheet", ",", "linkData", ".", "RID", ")", "\n", "if", "len", "(", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", ")", ">", "1", "{", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "=", "append", "(", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "[", ":", "rowIdx", "]", ",", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "[", "rowIdx", "+", "1", ":", "]", "...", ")", "\n", "}", "else", "{", "xlsx", ".", "Hyperlinks", "=", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "xlsx", ".", "Hyperlinks", "==", "nil", "{", "return", "\n", "}", "\n\n", "for", "i", ":=", "range", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "{", "link", ":=", "&", "xlsx", ".", "Hyperlinks", ".", "Hyperlink", "[", "i", "]", "// get reference", "\n", "colNum", ",", "rowNum", ",", "_", ":=", "CellNameToCoordinates", "(", "link", ".", "Ref", ")", "\n\n", "if", "dir", "==", "rows", "{", "if", "rowNum", ">=", "num", "{", "link", ".", "Ref", ",", "_", "=", "CoordinatesToCellName", "(", "colNum", ",", "rowNum", "+", "offset", ")", "\n", "}", "\n", "}", "else", "{", "if", "colNum", ">=", "num", "{", "link", ".", "Ref", ",", "_", "=", "CoordinatesToCellName", "(", "colNum", "+", "offset", ",", "rowNum", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// adjustHyperlinks provides a function to update hyperlinks when inserting or // deleting rows or columns.
[ "adjustHyperlinks", "provides", "a", "function", "to", "update", "hyperlinks", "when", "inserting", "or", "deleting", "rows", "or", "columns", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L92-L133
158,291
360EntSecGroup-Skylar/excelize
adjust.go
adjustAutoFilter
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error { if xlsx.AutoFilter == nil { return nil } rng := strings.Split(xlsx.AutoFilter.Ref, ":") firstCell := rng[0] lastCell := rng[1] firstCol, firstRow, err := CellNameToCoordinates(firstCell) if err != nil { return err } lastCol, lastRow, err := CellNameToCoordinates(lastCell) if err != nil { return err } if (dir == rows && firstRow == num && offset < 0) || (dir == columns && firstCol == num && lastCol == num) { xlsx.AutoFilter = nil for rowIdx := range xlsx.SheetData.Row { rowData := &xlsx.SheetData.Row[rowIdx] if rowData.R > firstRow && rowData.R <= lastRow { rowData.Hidden = false } } return nil } if dir == rows { if firstRow >= num { firstCell, _ = CoordinatesToCellName(firstCol, firstRow+offset) } if lastRow >= num { lastCell, _ = CoordinatesToCellName(lastCol, lastRow+offset) } } else { if lastCol >= num { lastCell, _ = CoordinatesToCellName(lastCol+offset, lastRow) } } xlsx.AutoFilter.Ref = firstCell + ":" + lastCell return nil }
go
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error { if xlsx.AutoFilter == nil { return nil } rng := strings.Split(xlsx.AutoFilter.Ref, ":") firstCell := rng[0] lastCell := rng[1] firstCol, firstRow, err := CellNameToCoordinates(firstCell) if err != nil { return err } lastCol, lastRow, err := CellNameToCoordinates(lastCell) if err != nil { return err } if (dir == rows && firstRow == num && offset < 0) || (dir == columns && firstCol == num && lastCol == num) { xlsx.AutoFilter = nil for rowIdx := range xlsx.SheetData.Row { rowData := &xlsx.SheetData.Row[rowIdx] if rowData.R > firstRow && rowData.R <= lastRow { rowData.Hidden = false } } return nil } if dir == rows { if firstRow >= num { firstCell, _ = CoordinatesToCellName(firstCol, firstRow+offset) } if lastRow >= num { lastCell, _ = CoordinatesToCellName(lastCol, lastRow+offset) } } else { if lastCol >= num { lastCell, _ = CoordinatesToCellName(lastCol+offset, lastRow) } } xlsx.AutoFilter.Ref = firstCell + ":" + lastCell return nil }
[ "func", "(", "f", "*", "File", ")", "adjustAutoFilter", "(", "xlsx", "*", "xlsxWorksheet", ",", "dir", "adjustDirection", ",", "num", ",", "offset", "int", ")", "error", "{", "if", "xlsx", ".", "AutoFilter", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "rng", ":=", "strings", ".", "Split", "(", "xlsx", ".", "AutoFilter", ".", "Ref", ",", "\"", "\"", ")", "\n", "firstCell", ":=", "rng", "[", "0", "]", "\n", "lastCell", ":=", "rng", "[", "1", "]", "\n\n", "firstCol", ",", "firstRow", ",", "err", ":=", "CellNameToCoordinates", "(", "firstCell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastCol", ",", "lastRow", ",", "err", ":=", "CellNameToCoordinates", "(", "lastCell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "(", "dir", "==", "rows", "&&", "firstRow", "==", "num", "&&", "offset", "<", "0", ")", "||", "(", "dir", "==", "columns", "&&", "firstCol", "==", "num", "&&", "lastCol", "==", "num", ")", "{", "xlsx", ".", "AutoFilter", "=", "nil", "\n", "for", "rowIdx", ":=", "range", "xlsx", ".", "SheetData", ".", "Row", "{", "rowData", ":=", "&", "xlsx", ".", "SheetData", ".", "Row", "[", "rowIdx", "]", "\n", "if", "rowData", ".", "R", ">", "firstRow", "&&", "rowData", ".", "R", "<=", "lastRow", "{", "rowData", ".", "Hidden", "=", "false", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "dir", "==", "rows", "{", "if", "firstRow", ">=", "num", "{", "firstCell", ",", "_", "=", "CoordinatesToCellName", "(", "firstCol", ",", "firstRow", "+", "offset", ")", "\n", "}", "\n", "if", "lastRow", ">=", "num", "{", "lastCell", ",", "_", "=", "CoordinatesToCellName", "(", "lastCol", ",", "lastRow", "+", "offset", ")", "\n", "}", "\n", "}", "else", "{", "if", "lastCol", ">=", "num", "{", "lastCell", ",", "_", "=", "CoordinatesToCellName", "(", "lastCol", "+", "offset", ",", "lastRow", ")", "\n", "}", "\n", "}", "\n\n", "xlsx", ".", "AutoFilter", ".", "Ref", "=", "firstCell", "+", "\"", "\"", "+", "lastCell", "\n", "return", "nil", "\n", "}" ]
// adjustAutoFilter provides a function to update the auto filter when // inserting or deleting rows or columns.
[ "adjustAutoFilter", "provides", "a", "function", "to", "update", "the", "auto", "filter", "when", "inserting", "or", "deleting", "rows", "or", "columns", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L137-L182
158,292
360EntSecGroup-Skylar/excelize
adjust.go
adjustMergeCells
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error { if xlsx.MergeCells == nil { return nil } for i, areaData := range xlsx.MergeCells.Cells { rng := strings.Split(areaData.Ref, ":") firstCell := rng[0] lastCell := rng[1] firstCol, firstRow, err := CellNameToCoordinates(firstCell) if err != nil { return err } lastCol, lastRow, err := CellNameToCoordinates(lastCell) if err != nil { return err } adjust := func(v int) int { if v >= num { v += offset if v < 1 { return 1 } return v } return v } if dir == rows { firstRow = adjust(firstRow) lastRow = adjust(lastRow) } else { firstCol = adjust(firstCol) lastCol = adjust(lastCol) } if firstCol == lastCol && firstRow == lastRow { if len(xlsx.MergeCells.Cells) > 1 { xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...) xlsx.MergeCells.Count = len(xlsx.MergeCells.Cells) } else { xlsx.MergeCells = nil } } if firstCell, err = CoordinatesToCellName(firstCol, firstRow); err != nil { return err } if lastCell, err = CoordinatesToCellName(lastCol, lastRow); err != nil { return err } areaData.Ref = firstCell + ":" + lastCell } return nil }
go
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error { if xlsx.MergeCells == nil { return nil } for i, areaData := range xlsx.MergeCells.Cells { rng := strings.Split(areaData.Ref, ":") firstCell := rng[0] lastCell := rng[1] firstCol, firstRow, err := CellNameToCoordinates(firstCell) if err != nil { return err } lastCol, lastRow, err := CellNameToCoordinates(lastCell) if err != nil { return err } adjust := func(v int) int { if v >= num { v += offset if v < 1 { return 1 } return v } return v } if dir == rows { firstRow = adjust(firstRow) lastRow = adjust(lastRow) } else { firstCol = adjust(firstCol) lastCol = adjust(lastCol) } if firstCol == lastCol && firstRow == lastRow { if len(xlsx.MergeCells.Cells) > 1 { xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...) xlsx.MergeCells.Count = len(xlsx.MergeCells.Cells) } else { xlsx.MergeCells = nil } } if firstCell, err = CoordinatesToCellName(firstCol, firstRow); err != nil { return err } if lastCell, err = CoordinatesToCellName(lastCol, lastRow); err != nil { return err } areaData.Ref = firstCell + ":" + lastCell } return nil }
[ "func", "(", "f", "*", "File", ")", "adjustMergeCells", "(", "xlsx", "*", "xlsxWorksheet", ",", "dir", "adjustDirection", ",", "num", ",", "offset", "int", ")", "error", "{", "if", "xlsx", ".", "MergeCells", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "for", "i", ",", "areaData", ":=", "range", "xlsx", ".", "MergeCells", ".", "Cells", "{", "rng", ":=", "strings", ".", "Split", "(", "areaData", ".", "Ref", ",", "\"", "\"", ")", "\n", "firstCell", ":=", "rng", "[", "0", "]", "\n", "lastCell", ":=", "rng", "[", "1", "]", "\n\n", "firstCol", ",", "firstRow", ",", "err", ":=", "CellNameToCoordinates", "(", "firstCell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastCol", ",", "lastRow", ",", "err", ":=", "CellNameToCoordinates", "(", "lastCell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "adjust", ":=", "func", "(", "v", "int", ")", "int", "{", "if", "v", ">=", "num", "{", "v", "+=", "offset", "\n", "if", "v", "<", "1", "{", "return", "1", "\n", "}", "\n", "return", "v", "\n", "}", "\n", "return", "v", "\n", "}", "\n\n", "if", "dir", "==", "rows", "{", "firstRow", "=", "adjust", "(", "firstRow", ")", "\n", "lastRow", "=", "adjust", "(", "lastRow", ")", "\n", "}", "else", "{", "firstCol", "=", "adjust", "(", "firstCol", ")", "\n", "lastCol", "=", "adjust", "(", "lastCol", ")", "\n", "}", "\n\n", "if", "firstCol", "==", "lastCol", "&&", "firstRow", "==", "lastRow", "{", "if", "len", "(", "xlsx", ".", "MergeCells", ".", "Cells", ")", ">", "1", "{", "xlsx", ".", "MergeCells", ".", "Cells", "=", "append", "(", "xlsx", ".", "MergeCells", ".", "Cells", "[", ":", "i", "]", ",", "xlsx", ".", "MergeCells", ".", "Cells", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "xlsx", ".", "MergeCells", ".", "Count", "=", "len", "(", "xlsx", ".", "MergeCells", ".", "Cells", ")", "\n", "}", "else", "{", "xlsx", ".", "MergeCells", "=", "nil", "\n", "}", "\n", "}", "\n\n", "if", "firstCell", ",", "err", "=", "CoordinatesToCellName", "(", "firstCol", ",", "firstRow", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "lastCell", ",", "err", "=", "CoordinatesToCellName", "(", "lastCol", ",", "lastRow", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "areaData", ".", "Ref", "=", "firstCell", "+", "\"", "\"", "+", "lastCell", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// adjustMergeCells provides a function to update merged cells when inserting // or deleting rows or columns.
[ "adjustMergeCells", "provides", "a", "function", "to", "update", "merged", "cells", "when", "inserting", "or", "deleting", "rows", "or", "columns", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/adjust.go#L186-L245
158,293
360EntSecGroup-Skylar/excelize
cellmerged.go
GetMergeCells
func (f *File) GetMergeCells(sheet string) ([]MergeCell, error) { var mergeCells []MergeCell xlsx, err := f.workSheetReader(sheet) if err != nil { return mergeCells, err } if xlsx.MergeCells != nil { mergeCells = make([]MergeCell, 0, len(xlsx.MergeCells.Cells)) for i := range xlsx.MergeCells.Cells { ref := xlsx.MergeCells.Cells[i].Ref axis := strings.Split(ref, ":")[0] val, _ := f.GetCellValue(sheet, axis) mergeCells = append(mergeCells, []string{ref, val}) } } return mergeCells, err }
go
func (f *File) GetMergeCells(sheet string) ([]MergeCell, error) { var mergeCells []MergeCell xlsx, err := f.workSheetReader(sheet) if err != nil { return mergeCells, err } if xlsx.MergeCells != nil { mergeCells = make([]MergeCell, 0, len(xlsx.MergeCells.Cells)) for i := range xlsx.MergeCells.Cells { ref := xlsx.MergeCells.Cells[i].Ref axis := strings.Split(ref, ":")[0] val, _ := f.GetCellValue(sheet, axis) mergeCells = append(mergeCells, []string{ref, val}) } } return mergeCells, err }
[ "func", "(", "f", "*", "File", ")", "GetMergeCells", "(", "sheet", "string", ")", "(", "[", "]", "MergeCell", ",", "error", ")", "{", "var", "mergeCells", "[", "]", "MergeCell", "\n", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mergeCells", ",", "err", "\n", "}", "\n", "if", "xlsx", ".", "MergeCells", "!=", "nil", "{", "mergeCells", "=", "make", "(", "[", "]", "MergeCell", ",", "0", ",", "len", "(", "xlsx", ".", "MergeCells", ".", "Cells", ")", ")", "\n\n", "for", "i", ":=", "range", "xlsx", ".", "MergeCells", ".", "Cells", "{", "ref", ":=", "xlsx", ".", "MergeCells", ".", "Cells", "[", "i", "]", ".", "Ref", "\n", "axis", ":=", "strings", ".", "Split", "(", "ref", ",", "\"", "\"", ")", "[", "0", "]", "\n", "val", ",", "_", ":=", "f", ".", "GetCellValue", "(", "sheet", ",", "axis", ")", "\n", "mergeCells", "=", "append", "(", "mergeCells", ",", "[", "]", "string", "{", "ref", ",", "val", "}", ")", "\n", "}", "\n", "}", "\n\n", "return", "mergeCells", ",", "err", "\n", "}" ]
// GetMergeCells provides a function to get all merged cells from a worksheet currently.
[ "GetMergeCells", "provides", "a", "function", "to", "get", "all", "merged", "cells", "from", "a", "worksheet", "currently", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/cellmerged.go#L6-L24
158,294
360EntSecGroup-Skylar/excelize
table.go
parseFormatTableSet
func parseFormatTableSet(formatSet string) (*formatTable, error) { format := formatTable{ TableStyle: "", ShowRowStripes: true, } err := json.Unmarshal(parseFormatSet(formatSet), &format) return &format, err }
go
func parseFormatTableSet(formatSet string) (*formatTable, error) { format := formatTable{ TableStyle: "", ShowRowStripes: true, } err := json.Unmarshal(parseFormatSet(formatSet), &format) return &format, err }
[ "func", "parseFormatTableSet", "(", "formatSet", "string", ")", "(", "*", "formatTable", ",", "error", ")", "{", "format", ":=", "formatTable", "{", "TableStyle", ":", "\"", "\"", ",", "ShowRowStripes", ":", "true", ",", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "parseFormatSet", "(", "formatSet", ")", ",", "&", "format", ")", "\n", "return", "&", "format", ",", "err", "\n", "}" ]
// parseFormatTableSet provides a function to parse the format settings of the // table with default value.
[ "parseFormatTableSet", "provides", "a", "function", "to", "parse", "the", "format", "settings", "of", "the", "table", "with", "default", "value", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L23-L30
158,295
360EntSecGroup-Skylar/excelize
table.go
addTable
func (f *File) addTable(sheet, tableXML string, hcol, hrow, vcol, vrow, i int, formatSet *formatTable) error { // Correct the minimum number of rows, the table at least two lines. if hrow == vrow { vrow++ } // Correct table reference coordinate area, such correct C1:B3 to B1:C3. hcell, err := CoordinatesToCellName(hcol, hrow) if err != nil { return err } vcell, err := CoordinatesToCellName(vcol, vrow) if err != nil { return err } ref := hcell + ":" + vcell var tableColumn []*xlsxTableColumn idx := 0 for i := hcol; i <= vcol; i++ { idx++ cell, err := CoordinatesToCellName(i, hrow) if err != nil { return err } name, _ := f.GetCellValue(sheet, cell) if _, err := strconv.Atoi(name); err == nil { f.SetCellStr(sheet, cell, name) } if name == "" { name = "Column" + strconv.Itoa(idx) f.SetCellStr(sheet, cell, name) } tableColumn = append(tableColumn, &xlsxTableColumn{ ID: idx, Name: name, }) } name := formatSet.TableName if name == "" { name = "Table" + strconv.Itoa(i) } t := xlsxTable{ XMLNS: NameSpaceSpreadSheet, ID: i, Name: name, DisplayName: name, Ref: ref, AutoFilter: &xlsxAutoFilter{ Ref: ref, }, TableColumns: &xlsxTableColumns{ Count: idx, TableColumn: tableColumn, }, TableStyleInfo: &xlsxTableStyleInfo{ Name: formatSet.TableStyle, ShowFirstColumn: formatSet.ShowFirstColumn, ShowLastColumn: formatSet.ShowLastColumn, ShowRowStripes: formatSet.ShowRowStripes, ShowColumnStripes: formatSet.ShowColumnStripes, }, } table, _ := xml.Marshal(t) f.saveFileList(tableXML, table) return nil }
go
func (f *File) addTable(sheet, tableXML string, hcol, hrow, vcol, vrow, i int, formatSet *formatTable) error { // Correct the minimum number of rows, the table at least two lines. if hrow == vrow { vrow++ } // Correct table reference coordinate area, such correct C1:B3 to B1:C3. hcell, err := CoordinatesToCellName(hcol, hrow) if err != nil { return err } vcell, err := CoordinatesToCellName(vcol, vrow) if err != nil { return err } ref := hcell + ":" + vcell var tableColumn []*xlsxTableColumn idx := 0 for i := hcol; i <= vcol; i++ { idx++ cell, err := CoordinatesToCellName(i, hrow) if err != nil { return err } name, _ := f.GetCellValue(sheet, cell) if _, err := strconv.Atoi(name); err == nil { f.SetCellStr(sheet, cell, name) } if name == "" { name = "Column" + strconv.Itoa(idx) f.SetCellStr(sheet, cell, name) } tableColumn = append(tableColumn, &xlsxTableColumn{ ID: idx, Name: name, }) } name := formatSet.TableName if name == "" { name = "Table" + strconv.Itoa(i) } t := xlsxTable{ XMLNS: NameSpaceSpreadSheet, ID: i, Name: name, DisplayName: name, Ref: ref, AutoFilter: &xlsxAutoFilter{ Ref: ref, }, TableColumns: &xlsxTableColumns{ Count: idx, TableColumn: tableColumn, }, TableStyleInfo: &xlsxTableStyleInfo{ Name: formatSet.TableStyle, ShowFirstColumn: formatSet.ShowFirstColumn, ShowLastColumn: formatSet.ShowLastColumn, ShowRowStripes: formatSet.ShowRowStripes, ShowColumnStripes: formatSet.ShowColumnStripes, }, } table, _ := xml.Marshal(t) f.saveFileList(tableXML, table) return nil }
[ "func", "(", "f", "*", "File", ")", "addTable", "(", "sheet", ",", "tableXML", "string", ",", "hcol", ",", "hrow", ",", "vcol", ",", "vrow", ",", "i", "int", ",", "formatSet", "*", "formatTable", ")", "error", "{", "// Correct the minimum number of rows, the table at least two lines.", "if", "hrow", "==", "vrow", "{", "vrow", "++", "\n", "}", "\n\n", "// Correct table reference coordinate area, such correct C1:B3 to B1:C3.", "hcell", ",", "err", ":=", "CoordinatesToCellName", "(", "hcol", ",", "hrow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "vcell", ",", "err", ":=", "CoordinatesToCellName", "(", "vcol", ",", "vrow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ref", ":=", "hcell", "+", "\"", "\"", "+", "vcell", "\n\n", "var", "tableColumn", "[", "]", "*", "xlsxTableColumn", "\n\n", "idx", ":=", "0", "\n", "for", "i", ":=", "hcol", ";", "i", "<=", "vcol", ";", "i", "++", "{", "idx", "++", "\n", "cell", ",", "err", ":=", "CoordinatesToCellName", "(", "i", ",", "hrow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "name", ",", "_", ":=", "f", ".", "GetCellValue", "(", "sheet", ",", "cell", ")", "\n", "if", "_", ",", "err", ":=", "strconv", ".", "Atoi", "(", "name", ")", ";", "err", "==", "nil", "{", "f", ".", "SetCellStr", "(", "sheet", ",", "cell", ",", "name", ")", "\n", "}", "\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "idx", ")", "\n", "f", ".", "SetCellStr", "(", "sheet", ",", "cell", ",", "name", ")", "\n", "}", "\n", "tableColumn", "=", "append", "(", "tableColumn", ",", "&", "xlsxTableColumn", "{", "ID", ":", "idx", ",", "Name", ":", "name", ",", "}", ")", "\n", "}", "\n", "name", ":=", "formatSet", ".", "TableName", "\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "i", ")", "\n", "}", "\n", "t", ":=", "xlsxTable", "{", "XMLNS", ":", "NameSpaceSpreadSheet", ",", "ID", ":", "i", ",", "Name", ":", "name", ",", "DisplayName", ":", "name", ",", "Ref", ":", "ref", ",", "AutoFilter", ":", "&", "xlsxAutoFilter", "{", "Ref", ":", "ref", ",", "}", ",", "TableColumns", ":", "&", "xlsxTableColumns", "{", "Count", ":", "idx", ",", "TableColumn", ":", "tableColumn", ",", "}", ",", "TableStyleInfo", ":", "&", "xlsxTableStyleInfo", "{", "Name", ":", "formatSet", ".", "TableStyle", ",", "ShowFirstColumn", ":", "formatSet", ".", "ShowFirstColumn", ",", "ShowLastColumn", ":", "formatSet", ".", "ShowLastColumn", ",", "ShowRowStripes", ":", "formatSet", ".", "ShowRowStripes", ",", "ShowColumnStripes", ":", "formatSet", ".", "ShowColumnStripes", ",", "}", ",", "}", "\n", "table", ",", "_", ":=", "xml", ".", "Marshal", "(", "t", ")", "\n", "f", ".", "saveFileList", "(", "tableXML", ",", "table", ")", "\n", "return", "nil", "\n", "}" ]
// addTable provides a function to add table by given worksheet name, // coordinate area and format set.
[ "addTable", "provides", "a", "function", "to", "add", "table", "by", "given", "worksheet", "name", "coordinate", "area", "and", "format", "set", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L118-L185
158,296
360EntSecGroup-Skylar/excelize
table.go
parseAutoFilterSet
func parseAutoFilterSet(formatSet string) (*formatAutoFilter, error) { format := formatAutoFilter{} err := json.Unmarshal([]byte(formatSet), &format) return &format, err }
go
func parseAutoFilterSet(formatSet string) (*formatAutoFilter, error) { format := formatAutoFilter{} err := json.Unmarshal([]byte(formatSet), &format) return &format, err }
[ "func", "parseAutoFilterSet", "(", "formatSet", "string", ")", "(", "*", "formatAutoFilter", ",", "error", ")", "{", "format", ":=", "formatAutoFilter", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "formatSet", ")", ",", "&", "format", ")", "\n", "return", "&", "format", ",", "err", "\n", "}" ]
// parseAutoFilterSet provides a function to parse the settings of the auto // filter.
[ "parseAutoFilterSet", "provides", "a", "function", "to", "parse", "the", "settings", "of", "the", "auto", "filter", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L189-L193
158,297
360EntSecGroup-Skylar/excelize
table.go
autoFilter
func (f *File) autoFilter(sheet, ref string, refRange, col int, formatSet *formatAutoFilter) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } if xlsx.SheetPr != nil { xlsx.SheetPr.FilterMode = true } xlsx.SheetPr = &xlsxSheetPr{FilterMode: true} filter := &xlsxAutoFilter{ Ref: ref, } xlsx.AutoFilter = filter if formatSet.Column == "" || formatSet.Expression == "" { return nil } fsCol, err := ColumnNameToNumber(formatSet.Column) if err != nil { return err } offset := fsCol - col if offset < 0 || offset > refRange { return fmt.Errorf("incorrect index of column '%s'", formatSet.Column) } filter.FilterColumn = &xlsxFilterColumn{ ColID: offset, } re := regexp.MustCompile(`"(?:[^"]|"")*"|\S+`) token := re.FindAllString(formatSet.Expression, -1) if len(token) != 3 && len(token) != 7 { return fmt.Errorf("incorrect number of tokens in criteria '%s'", formatSet.Expression) } expressions, tokens, err := f.parseFilterExpression(formatSet.Expression, token) if err != nil { return err } f.writeAutoFilter(filter, expressions, tokens) xlsx.AutoFilter = filter return nil }
go
func (f *File) autoFilter(sheet, ref string, refRange, col int, formatSet *formatAutoFilter) error { xlsx, err := f.workSheetReader(sheet) if err != nil { return err } if xlsx.SheetPr != nil { xlsx.SheetPr.FilterMode = true } xlsx.SheetPr = &xlsxSheetPr{FilterMode: true} filter := &xlsxAutoFilter{ Ref: ref, } xlsx.AutoFilter = filter if formatSet.Column == "" || formatSet.Expression == "" { return nil } fsCol, err := ColumnNameToNumber(formatSet.Column) if err != nil { return err } offset := fsCol - col if offset < 0 || offset > refRange { return fmt.Errorf("incorrect index of column '%s'", formatSet.Column) } filter.FilterColumn = &xlsxFilterColumn{ ColID: offset, } re := regexp.MustCompile(`"(?:[^"]|"")*"|\S+`) token := re.FindAllString(formatSet.Expression, -1) if len(token) != 3 && len(token) != 7 { return fmt.Errorf("incorrect number of tokens in criteria '%s'", formatSet.Expression) } expressions, tokens, err := f.parseFilterExpression(formatSet.Expression, token) if err != nil { return err } f.writeAutoFilter(filter, expressions, tokens) xlsx.AutoFilter = filter return nil }
[ "func", "(", "f", "*", "File", ")", "autoFilter", "(", "sheet", ",", "ref", "string", ",", "refRange", ",", "col", "int", ",", "formatSet", "*", "formatAutoFilter", ")", "error", "{", "xlsx", ",", "err", ":=", "f", ".", "workSheetReader", "(", "sheet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "xlsx", ".", "SheetPr", "!=", "nil", "{", "xlsx", ".", "SheetPr", ".", "FilterMode", "=", "true", "\n", "}", "\n", "xlsx", ".", "SheetPr", "=", "&", "xlsxSheetPr", "{", "FilterMode", ":", "true", "}", "\n", "filter", ":=", "&", "xlsxAutoFilter", "{", "Ref", ":", "ref", ",", "}", "\n", "xlsx", ".", "AutoFilter", "=", "filter", "\n", "if", "formatSet", ".", "Column", "==", "\"", "\"", "||", "formatSet", ".", "Expression", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "fsCol", ",", "err", ":=", "ColumnNameToNumber", "(", "formatSet", ".", "Column", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "offset", ":=", "fsCol", "-", "col", "\n", "if", "offset", "<", "0", "||", "offset", ">", "refRange", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "formatSet", ".", "Column", ")", "\n", "}", "\n\n", "filter", ".", "FilterColumn", "=", "&", "xlsxFilterColumn", "{", "ColID", ":", "offset", ",", "}", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "`\"(?:[^\"]|\"\")*\"|\\S+`", ")", "\n", "token", ":=", "re", ".", "FindAllString", "(", "formatSet", ".", "Expression", ",", "-", "1", ")", "\n", "if", "len", "(", "token", ")", "!=", "3", "&&", "len", "(", "token", ")", "!=", "7", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "formatSet", ".", "Expression", ")", "\n", "}", "\n", "expressions", ",", "tokens", ",", "err", ":=", "f", ".", "parseFilterExpression", "(", "formatSet", ".", "Expression", ",", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "writeAutoFilter", "(", "filter", ",", "expressions", ",", "tokens", ")", "\n", "xlsx", ".", "AutoFilter", "=", "filter", "\n", "return", "nil", "\n", "}" ]
// autoFilter provides a function to extract the tokens from the filter // expression. The tokens are mainly non-whitespace groups.
[ "autoFilter", "provides", "a", "function", "to", "extract", "the", "tokens", "from", "the", "filter", "expression", ".", "The", "tokens", "are", "mainly", "non", "-", "whitespace", "groups", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L301-L342
158,298
360EntSecGroup-Skylar/excelize
table.go
writeAutoFilter
func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []string) { if len(exp) == 1 && exp[0] == 2 { // Single equality. var filters []*xlsxFilter filters = append(filters, &xlsxFilter{Val: tokens[0]}) filter.FilterColumn.Filters = &xlsxFilters{Filter: filters} } else if len(exp) == 3 && exp[0] == 2 && exp[1] == 1 && exp[2] == 2 { // Double equality with "or" operator. filters := []*xlsxFilter{} for _, v := range tokens { filters = append(filters, &xlsxFilter{Val: v}) } filter.FilterColumn.Filters = &xlsxFilters{Filter: filters} } else { // Non default custom filter. expRel := map[int]int{0: 0, 1: 2} andRel := map[int]bool{0: true, 1: false} for k, v := range tokens { f.writeCustomFilter(filter, exp[expRel[k]], v) if k == 1 { filter.FilterColumn.CustomFilters.And = andRel[exp[k]] } } } }
go
func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []string) { if len(exp) == 1 && exp[0] == 2 { // Single equality. var filters []*xlsxFilter filters = append(filters, &xlsxFilter{Val: tokens[0]}) filter.FilterColumn.Filters = &xlsxFilters{Filter: filters} } else if len(exp) == 3 && exp[0] == 2 && exp[1] == 1 && exp[2] == 2 { // Double equality with "or" operator. filters := []*xlsxFilter{} for _, v := range tokens { filters = append(filters, &xlsxFilter{Val: v}) } filter.FilterColumn.Filters = &xlsxFilters{Filter: filters} } else { // Non default custom filter. expRel := map[int]int{0: 0, 1: 2} andRel := map[int]bool{0: true, 1: false} for k, v := range tokens { f.writeCustomFilter(filter, exp[expRel[k]], v) if k == 1 { filter.FilterColumn.CustomFilters.And = andRel[exp[k]] } } } }
[ "func", "(", "f", "*", "File", ")", "writeAutoFilter", "(", "filter", "*", "xlsxAutoFilter", ",", "exp", "[", "]", "int", ",", "tokens", "[", "]", "string", ")", "{", "if", "len", "(", "exp", ")", "==", "1", "&&", "exp", "[", "0", "]", "==", "2", "{", "// Single equality.", "var", "filters", "[", "]", "*", "xlsxFilter", "\n", "filters", "=", "append", "(", "filters", ",", "&", "xlsxFilter", "{", "Val", ":", "tokens", "[", "0", "]", "}", ")", "\n", "filter", ".", "FilterColumn", ".", "Filters", "=", "&", "xlsxFilters", "{", "Filter", ":", "filters", "}", "\n", "}", "else", "if", "len", "(", "exp", ")", "==", "3", "&&", "exp", "[", "0", "]", "==", "2", "&&", "exp", "[", "1", "]", "==", "1", "&&", "exp", "[", "2", "]", "==", "2", "{", "// Double equality with \"or\" operator.", "filters", ":=", "[", "]", "*", "xlsxFilter", "{", "}", "\n", "for", "_", ",", "v", ":=", "range", "tokens", "{", "filters", "=", "append", "(", "filters", ",", "&", "xlsxFilter", "{", "Val", ":", "v", "}", ")", "\n", "}", "\n", "filter", ".", "FilterColumn", ".", "Filters", "=", "&", "xlsxFilters", "{", "Filter", ":", "filters", "}", "\n", "}", "else", "{", "// Non default custom filter.", "expRel", ":=", "map", "[", "int", "]", "int", "{", "0", ":", "0", ",", "1", ":", "2", "}", "\n", "andRel", ":=", "map", "[", "int", "]", "bool", "{", "0", ":", "true", ",", "1", ":", "false", "}", "\n", "for", "k", ",", "v", ":=", "range", "tokens", "{", "f", ".", "writeCustomFilter", "(", "filter", ",", "exp", "[", "expRel", "[", "k", "]", "]", ",", "v", ")", "\n", "if", "k", "==", "1", "{", "filter", ".", "FilterColumn", ".", "CustomFilters", ".", "And", "=", "andRel", "[", "exp", "[", "k", "]", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// writeAutoFilter provides a function to check for single or double custom // filters as default filters and handle them accordingly.
[ "writeAutoFilter", "provides", "a", "function", "to", "check", "for", "single", "or", "double", "custom", "filters", "as", "default", "filters", "and", "handle", "them", "accordingly", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L346-L370
158,299
360EntSecGroup-Skylar/excelize
table.go
parseFilterTokens
func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, string, error) { operators := map[string]int{ "==": 2, "=": 2, "=~": 2, "eq": 2, "!=": 5, "!~": 5, "ne": 5, "<>": 5, "<": 1, "<=": 3, ">": 4, ">=": 6, } operator, ok := operators[strings.ToLower(tokens[1])] if !ok { // Convert the operator from a number to a descriptive string. return []int{}, "", fmt.Errorf("unknown operator: %s", tokens[1]) } token := tokens[2] // Special handling for Blanks/NonBlanks. re, _ := regexp.Match("blanks|nonblanks", []byte(strings.ToLower(token))) if re { // Only allow Equals or NotEqual in this context. if operator != 2 && operator != 5 { return []int{operator}, token, fmt.Errorf("the operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression) } token = strings.ToLower(token) // The operator should always be 2 (=) to flag a "simple" equality in // the binary record. Therefore we convert <> to =. if token == "blanks" { if operator == 5 { token = " " } } else { if operator == 5 { operator = 2 token = "blanks" } else { operator = 5 token = " " } } } // if the string token contains an Excel match character then change the // operator type to indicate a non "simple" equality. re, _ = regexp.Match("[*?]", []byte(token)) if operator == 2 && re { operator = 22 } return []int{operator}, token, nil }
go
func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, string, error) { operators := map[string]int{ "==": 2, "=": 2, "=~": 2, "eq": 2, "!=": 5, "!~": 5, "ne": 5, "<>": 5, "<": 1, "<=": 3, ">": 4, ">=": 6, } operator, ok := operators[strings.ToLower(tokens[1])] if !ok { // Convert the operator from a number to a descriptive string. return []int{}, "", fmt.Errorf("unknown operator: %s", tokens[1]) } token := tokens[2] // Special handling for Blanks/NonBlanks. re, _ := regexp.Match("blanks|nonblanks", []byte(strings.ToLower(token))) if re { // Only allow Equals or NotEqual in this context. if operator != 2 && operator != 5 { return []int{operator}, token, fmt.Errorf("the operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression) } token = strings.ToLower(token) // The operator should always be 2 (=) to flag a "simple" equality in // the binary record. Therefore we convert <> to =. if token == "blanks" { if operator == 5 { token = " " } } else { if operator == 5 { operator = 2 token = "blanks" } else { operator = 5 token = " " } } } // if the string token contains an Excel match character then change the // operator type to indicate a non "simple" equality. re, _ = regexp.Match("[*?]", []byte(token)) if operator == 2 && re { operator = 22 } return []int{operator}, token, nil }
[ "func", "(", "f", "*", "File", ")", "parseFilterTokens", "(", "expression", "string", ",", "tokens", "[", "]", "string", ")", "(", "[", "]", "int", ",", "string", ",", "error", ")", "{", "operators", ":=", "map", "[", "string", "]", "int", "{", "\"", "\"", ":", "2", ",", "\"", "\"", ":", "2", ",", "\"", "\"", ":", "2", ",", "\"", "\"", ":", "2", ",", "\"", "\"", ":", "5", ",", "\"", "\"", ":", "5", ",", "\"", "\"", ":", "5", ",", "\"", "\"", ":", "5", ",", "\"", "\"", ":", "1", ",", "\"", "\"", ":", "3", ",", "\"", "\"", ":", "4", ",", "\"", "\"", ":", "6", ",", "}", "\n", "operator", ",", "ok", ":=", "operators", "[", "strings", ".", "ToLower", "(", "tokens", "[", "1", "]", ")", "]", "\n", "if", "!", "ok", "{", "// Convert the operator from a number to a descriptive string.", "return", "[", "]", "int", "{", "}", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tokens", "[", "1", "]", ")", "\n", "}", "\n", "token", ":=", "tokens", "[", "2", "]", "\n", "// Special handling for Blanks/NonBlanks.", "re", ",", "_", ":=", "regexp", ".", "Match", "(", "\"", "\"", ",", "[", "]", "byte", "(", "strings", ".", "ToLower", "(", "token", ")", ")", ")", "\n", "if", "re", "{", "// Only allow Equals or NotEqual in this context.", "if", "operator", "!=", "2", "&&", "operator", "!=", "5", "{", "return", "[", "]", "int", "{", "operator", "}", ",", "token", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tokens", "[", "1", "]", ",", "expression", ")", "\n", "}", "\n", "token", "=", "strings", ".", "ToLower", "(", "token", ")", "\n", "// The operator should always be 2 (=) to flag a \"simple\" equality in", "// the binary record. Therefore we convert <> to =.", "if", "token", "==", "\"", "\"", "{", "if", "operator", "==", "5", "{", "token", "=", "\"", "\"", "\n", "}", "\n", "}", "else", "{", "if", "operator", "==", "5", "{", "operator", "=", "2", "\n", "token", "=", "\"", "\"", "\n", "}", "else", "{", "operator", "=", "5", "\n", "token", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "}", "\n", "// if the string token contains an Excel match character then change the", "// operator type to indicate a non \"simple\" equality.", "re", ",", "_", "=", "regexp", ".", "Match", "(", "\"", "\"", ",", "[", "]", "byte", "(", "token", ")", ")", "\n", "if", "operator", "==", "2", "&&", "re", "{", "operator", "=", "22", "\n", "}", "\n", "return", "[", "]", "int", "{", "operator", "}", ",", "token", ",", "nil", "\n", "}" ]
// parseFilterTokens provides a function to parse the 3 tokens of a filter // expression and return the operator and token.
[ "parseFilterTokens", "provides", "a", "function", "to", "parse", "the", "3", "tokens", "of", "a", "filter", "expression", "and", "return", "the", "operator", "and", "token", "." ]
63e97ffc9aae35780cdbd69ad966fb101fc5217f
https://github.com/360EntSecGroup-Skylar/excelize/blob/63e97ffc9aae35780cdbd69ad966fb101fc5217f/table.go#L440-L492