text
stringlengths
2
99k
meta
dict
{ "type": "minecraft:crafting_shaped", "pattern": [ " C ", "RBR", " C " ], "key": { "B": { "item": "techreborn:advanced_storage_unit" }, "R": { "item": "techreborn:rubber" }, "C": { "item": "techreborn:cell" } }, "result": { "item": "techreborn:advanced_tank_unit" } }
{ "pile_set_name": "Github" }
name=Spellshock image=https://magiccards.info/scans/en/ex/104.jpg value=3.932 rarity=U type=Enchantment cost={2}{R} ability=Whenever a player casts a spell, SN deals 2 damage to that player. timing=enchantment oracle=Whenever a player casts a spell, Spellshock deals 2 damage to that player.
{ "pile_set_name": "Github" }
// Copyright 2015 RedHat, Inc. // Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package sdjournal provides a low-level Go interface to the // systemd journal wrapped around the sd-journal C API. // // All public read methods map closely to the sd-journal API functions. See the // sd-journal.h documentation[1] for information about each function. // // To write to the journal, see the pure-Go "journal" package // // [1] http://www.freedesktop.org/software/systemd/man/sd-journal.html package sdjournal // #include <systemd/sd-journal.h> // #include <systemd/sd-id128.h> // #include <stdlib.h> // #include <syslog.h> // // int // my_sd_journal_open(void *f, sd_journal **ret, int flags) // { // int (*sd_journal_open)(sd_journal **, int); // // sd_journal_open = f; // return sd_journal_open(ret, flags); // } // // int // my_sd_journal_open_directory(void *f, sd_journal **ret, const char *path, int flags) // { // int (*sd_journal_open_directory)(sd_journal **, const char *, int); // // sd_journal_open_directory = f; // return sd_journal_open_directory(ret, path, flags); // } // // int // my_sd_journal_open_files(void *f, sd_journal **ret, const char **paths, int flags) // { // int (*sd_journal_open_files)(sd_journal **, const char **, int); // // sd_journal_open_files = f; // return sd_journal_open_files(ret, paths, flags); // } // // void // my_sd_journal_close(void *f, sd_journal *j) // { // int (*sd_journal_close)(sd_journal *); // // sd_journal_close = f; // sd_journal_close(j); // } // // int // my_sd_journal_get_usage(void *f, sd_journal *j, uint64_t *bytes) // { // int (*sd_journal_get_usage)(sd_journal *, uint64_t *); // // sd_journal_get_usage = f; // return sd_journal_get_usage(j, bytes); // } // // int // my_sd_journal_add_match(void *f, sd_journal *j, const void *data, size_t size) // { // int (*sd_journal_add_match)(sd_journal *, const void *, size_t); // // sd_journal_add_match = f; // return sd_journal_add_match(j, data, size); // } // // int // my_sd_journal_add_disjunction(void *f, sd_journal *j) // { // int (*sd_journal_add_disjunction)(sd_journal *); // // sd_journal_add_disjunction = f; // return sd_journal_add_disjunction(j); // } // // int // my_sd_journal_add_conjunction(void *f, sd_journal *j) // { // int (*sd_journal_add_conjunction)(sd_journal *); // // sd_journal_add_conjunction = f; // return sd_journal_add_conjunction(j); // } // // void // my_sd_journal_flush_matches(void *f, sd_journal *j) // { // int (*sd_journal_flush_matches)(sd_journal *); // // sd_journal_flush_matches = f; // sd_journal_flush_matches(j); // } // // int // my_sd_journal_next(void *f, sd_journal *j) // { // int (*sd_journal_next)(sd_journal *); // // sd_journal_next = f; // return sd_journal_next(j); // } // // int // my_sd_journal_next_skip(void *f, sd_journal *j, uint64_t skip) // { // int (*sd_journal_next_skip)(sd_journal *, uint64_t); // // sd_journal_next_skip = f; // return sd_journal_next_skip(j, skip); // } // // int // my_sd_journal_previous(void *f, sd_journal *j) // { // int (*sd_journal_previous)(sd_journal *); // // sd_journal_previous = f; // return sd_journal_previous(j); // } // // int // my_sd_journal_previous_skip(void *f, sd_journal *j, uint64_t skip) // { // int (*sd_journal_previous_skip)(sd_journal *, uint64_t); // // sd_journal_previous_skip = f; // return sd_journal_previous_skip(j, skip); // } // // int // my_sd_journal_get_data(void *f, sd_journal *j, const char *field, const void **data, size_t *length) // { // int (*sd_journal_get_data)(sd_journal *, const char *, const void **, size_t *); // // sd_journal_get_data = f; // return sd_journal_get_data(j, field, data, length); // } // // int // my_sd_journal_set_data_threshold(void *f, sd_journal *j, size_t sz) // { // int (*sd_journal_set_data_threshold)(sd_journal *, size_t); // // sd_journal_set_data_threshold = f; // return sd_journal_set_data_threshold(j, sz); // } // // int // my_sd_journal_get_cursor(void *f, sd_journal *j, char **cursor) // { // int (*sd_journal_get_cursor)(sd_journal *, char **); // // sd_journal_get_cursor = f; // return sd_journal_get_cursor(j, cursor); // } // // int // my_sd_journal_test_cursor(void *f, sd_journal *j, const char *cursor) // { // int (*sd_journal_test_cursor)(sd_journal *, const char *); // // sd_journal_test_cursor = f; // return sd_journal_test_cursor(j, cursor); // } // // int // my_sd_journal_get_realtime_usec(void *f, sd_journal *j, uint64_t *usec) // { // int (*sd_journal_get_realtime_usec)(sd_journal *, uint64_t *); // // sd_journal_get_realtime_usec = f; // return sd_journal_get_realtime_usec(j, usec); // } // // int // my_sd_journal_get_monotonic_usec(void *f, sd_journal *j, uint64_t *usec, sd_id128_t *boot_id) // { // int (*sd_journal_get_monotonic_usec)(sd_journal *, uint64_t *, sd_id128_t *); // // sd_journal_get_monotonic_usec = f; // return sd_journal_get_monotonic_usec(j, usec, boot_id); // } // // int // my_sd_journal_seek_head(void *f, sd_journal *j) // { // int (*sd_journal_seek_head)(sd_journal *); // // sd_journal_seek_head = f; // return sd_journal_seek_head(j); // } // // int // my_sd_journal_seek_tail(void *f, sd_journal *j) // { // int (*sd_journal_seek_tail)(sd_journal *); // // sd_journal_seek_tail = f; // return sd_journal_seek_tail(j); // } // // // int // my_sd_journal_seek_cursor(void *f, sd_journal *j, const char *cursor) // { // int (*sd_journal_seek_cursor)(sd_journal *, const char *); // // sd_journal_seek_cursor = f; // return sd_journal_seek_cursor(j, cursor); // } // // int // my_sd_journal_seek_realtime_usec(void *f, sd_journal *j, uint64_t usec) // { // int (*sd_journal_seek_realtime_usec)(sd_journal *, uint64_t); // // sd_journal_seek_realtime_usec = f; // return sd_journal_seek_realtime_usec(j, usec); // } // // int // my_sd_journal_wait(void *f, sd_journal *j, uint64_t timeout_usec) // { // int (*sd_journal_wait)(sd_journal *, uint64_t); // // sd_journal_wait = f; // return sd_journal_wait(j, timeout_usec); // } // // void // my_sd_journal_restart_data(void *f, sd_journal *j) // { // void (*sd_journal_restart_data)(sd_journal *); // // sd_journal_restart_data = f; // sd_journal_restart_data(j); // } // // int // my_sd_journal_enumerate_data(void *f, sd_journal *j, const void **data, size_t *length) // { // int (*sd_journal_enumerate_data)(sd_journal *, const void **, size_t *); // // sd_journal_enumerate_data = f; // return sd_journal_enumerate_data(j, data, length); // } // // int // my_sd_journal_query_unique(void *f, sd_journal *j, const char *field) // { // int(*sd_journal_query_unique)(sd_journal *, const char *); // // sd_journal_query_unique = f; // return sd_journal_query_unique(j, field); // } // // int // my_sd_journal_enumerate_unique(void *f, sd_journal *j, const void **data, size_t *length) // { // int(*sd_journal_enumerate_unique)(sd_journal *, const void **, size_t *); // // sd_journal_enumerate_unique = f; // return sd_journal_enumerate_unique(j, data, length); // } // // void // my_sd_journal_restart_unique(void *f, sd_journal *j) // { // void(*sd_journal_restart_unique)(sd_journal *); // // sd_journal_restart_unique = f; // sd_journal_restart_unique(j); // } // // int // my_sd_journal_get_catalog(void *f, sd_journal *j, char **ret) // { // int(*sd_journal_get_catalog)(sd_journal *, char **); // // sd_journal_get_catalog = f; // return sd_journal_get_catalog(j, ret); // } // import "C" import ( "bytes" "errors" "fmt" "strings" "sync" "syscall" "time" "unsafe" ) // Journal entry field strings which correspond to: // http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html const ( // User Journal Fields SD_JOURNAL_FIELD_MESSAGE = "MESSAGE" SD_JOURNAL_FIELD_MESSAGE_ID = "MESSAGE_ID" SD_JOURNAL_FIELD_PRIORITY = "PRIORITY" SD_JOURNAL_FIELD_CODE_FILE = "CODE_FILE" SD_JOURNAL_FIELD_CODE_LINE = "CODE_LINE" SD_JOURNAL_FIELD_CODE_FUNC = "CODE_FUNC" SD_JOURNAL_FIELD_ERRNO = "ERRNO" SD_JOURNAL_FIELD_SYSLOG_FACILITY = "SYSLOG_FACILITY" SD_JOURNAL_FIELD_SYSLOG_IDENTIFIER = "SYSLOG_IDENTIFIER" SD_JOURNAL_FIELD_SYSLOG_PID = "SYSLOG_PID" // Trusted Journal Fields SD_JOURNAL_FIELD_PID = "_PID" SD_JOURNAL_FIELD_UID = "_UID" SD_JOURNAL_FIELD_GID = "_GID" SD_JOURNAL_FIELD_COMM = "_COMM" SD_JOURNAL_FIELD_EXE = "_EXE" SD_JOURNAL_FIELD_CMDLINE = "_CMDLINE" SD_JOURNAL_FIELD_CAP_EFFECTIVE = "_CAP_EFFECTIVE" SD_JOURNAL_FIELD_AUDIT_SESSION = "_AUDIT_SESSION" SD_JOURNAL_FIELD_AUDIT_LOGINUID = "_AUDIT_LOGINUID" SD_JOURNAL_FIELD_SYSTEMD_CGROUP = "_SYSTEMD_CGROUP" SD_JOURNAL_FIELD_SYSTEMD_SESSION = "_SYSTEMD_SESSION" SD_JOURNAL_FIELD_SYSTEMD_UNIT = "_SYSTEMD_UNIT" SD_JOURNAL_FIELD_SYSTEMD_USER_UNIT = "_SYSTEMD_USER_UNIT" SD_JOURNAL_FIELD_SYSTEMD_OWNER_UID = "_SYSTEMD_OWNER_UID" SD_JOURNAL_FIELD_SYSTEMD_SLICE = "_SYSTEMD_SLICE" SD_JOURNAL_FIELD_SELINUX_CONTEXT = "_SELINUX_CONTEXT" SD_JOURNAL_FIELD_SOURCE_REALTIME_TIMESTAMP = "_SOURCE_REALTIME_TIMESTAMP" SD_JOURNAL_FIELD_BOOT_ID = "_BOOT_ID" SD_JOURNAL_FIELD_MACHINE_ID = "_MACHINE_ID" SD_JOURNAL_FIELD_HOSTNAME = "_HOSTNAME" SD_JOURNAL_FIELD_TRANSPORT = "_TRANSPORT" // Address Fields SD_JOURNAL_FIELD_CURSOR = "__CURSOR" SD_JOURNAL_FIELD_REALTIME_TIMESTAMP = "__REALTIME_TIMESTAMP" SD_JOURNAL_FIELD_MONOTONIC_TIMESTAMP = "__MONOTONIC_TIMESTAMP" ) // Journal event constants const ( SD_JOURNAL_NOP = int(C.SD_JOURNAL_NOP) SD_JOURNAL_APPEND = int(C.SD_JOURNAL_APPEND) SD_JOURNAL_INVALIDATE = int(C.SD_JOURNAL_INVALIDATE) ) const ( // IndefiniteWait is a sentinel value that can be passed to // sdjournal.Wait() to signal an indefinite wait for new journal // events. It is implemented as the maximum value for a time.Duration: // https://github.com/golang/go/blob/e4dcf5c8c22d98ac9eac7b9b226596229624cb1d/src/time/time.go#L434 IndefiniteWait time.Duration = 1<<63 - 1 ) var ( // ErrNoTestCursor gets returned when using TestCursor function and cursor // parameter is not the same as the current cursor position. ErrNoTestCursor = errors.New("Cursor parameter is not the same as current position") ) // Journal is a Go wrapper of an sd_journal structure. type Journal struct { cjournal *C.sd_journal mu sync.Mutex } // JournalEntry represents all fields of a journal entry plus address fields. type JournalEntry struct { Fields map[string]string Cursor string RealtimeTimestamp uint64 MonotonicTimestamp uint64 } // Match is a convenience wrapper to describe filters supplied to AddMatch. type Match struct { Field string Value string } // String returns a string representation of a Match suitable for use with AddMatch. func (m *Match) String() string { return m.Field + "=" + m.Value } // NewJournal returns a new Journal instance pointing to the local journal func NewJournal() (j *Journal, err error) { j = &Journal{} sd_journal_open, err := getFunction("sd_journal_open") if err != nil { return nil, err } r := C.my_sd_journal_open(sd_journal_open, &j.cjournal, C.SD_JOURNAL_LOCAL_ONLY) if r < 0 { return nil, fmt.Errorf("failed to open journal: %d", syscall.Errno(-r)) } return j, nil } // NewJournalFromDir returns a new Journal instance pointing to a journal residing // in a given directory. func NewJournalFromDir(path string) (j *Journal, err error) { j = &Journal{} sd_journal_open_directory, err := getFunction("sd_journal_open_directory") if err != nil { return nil, err } p := C.CString(path) defer C.free(unsafe.Pointer(p)) r := C.my_sd_journal_open_directory(sd_journal_open_directory, &j.cjournal, p, 0) if r < 0 { return nil, fmt.Errorf("failed to open journal in directory %q: %d", path, syscall.Errno(-r)) } return j, nil } // NewJournalFromFiles returns a new Journal instance pointing to a journals residing // in a given files. func NewJournalFromFiles(paths ...string) (j *Journal, err error) { j = &Journal{} sd_journal_open_files, err := getFunction("sd_journal_open_files") if err != nil { return nil, err } // by making the slice 1 elem too long, we guarantee it'll be null-terminated cPaths := make([]*C.char, len(paths)+1) for idx, path := range paths { p := C.CString(path) cPaths[idx] = p defer C.free(unsafe.Pointer(p)) } r := C.my_sd_journal_open_files(sd_journal_open_files, &j.cjournal, &cPaths[0], 0) if r < 0 { return nil, fmt.Errorf("failed to open journals in paths %q: %d", paths, syscall.Errno(-r)) } return j, nil } // Close closes a journal opened with NewJournal. func (j *Journal) Close() error { sd_journal_close, err := getFunction("sd_journal_close") if err != nil { return err } j.mu.Lock() C.my_sd_journal_close(sd_journal_close, j.cjournal) j.mu.Unlock() return nil } // AddMatch adds a match by which to filter the entries of the journal. func (j *Journal) AddMatch(match string) error { sd_journal_add_match, err := getFunction("sd_journal_add_match") if err != nil { return err } m := C.CString(match) defer C.free(unsafe.Pointer(m)) j.mu.Lock() r := C.my_sd_journal_add_match(sd_journal_add_match, j.cjournal, unsafe.Pointer(m), C.size_t(len(match))) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to add match: %d", syscall.Errno(-r)) } return nil } // AddDisjunction inserts a logical OR in the match list. func (j *Journal) AddDisjunction() error { sd_journal_add_disjunction, err := getFunction("sd_journal_add_disjunction") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_add_disjunction(sd_journal_add_disjunction, j.cjournal) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to add a disjunction in the match list: %d", syscall.Errno(-r)) } return nil } // AddConjunction inserts a logical AND in the match list. func (j *Journal) AddConjunction() error { sd_journal_add_conjunction, err := getFunction("sd_journal_add_conjunction") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_add_conjunction(sd_journal_add_conjunction, j.cjournal) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to add a conjunction in the match list: %d", syscall.Errno(-r)) } return nil } // FlushMatches flushes all matches, disjunctions and conjunctions. func (j *Journal) FlushMatches() { sd_journal_flush_matches, err := getFunction("sd_journal_flush_matches") if err != nil { return } j.mu.Lock() C.my_sd_journal_flush_matches(sd_journal_flush_matches, j.cjournal) j.mu.Unlock() } // Next advances the read pointer into the journal by one entry. func (j *Journal) Next() (uint64, error) { sd_journal_next, err := getFunction("sd_journal_next") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_next(sd_journal_next, j.cjournal) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to iterate journal: %d", syscall.Errno(-r)) } return uint64(r), nil } // NextSkip advances the read pointer by multiple entries at once, // as specified by the skip parameter. func (j *Journal) NextSkip(skip uint64) (uint64, error) { sd_journal_next_skip, err := getFunction("sd_journal_next_skip") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_next_skip(sd_journal_next_skip, j.cjournal, C.uint64_t(skip)) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to iterate journal: %d", syscall.Errno(-r)) } return uint64(r), nil } // Previous sets the read pointer into the journal back by one entry. func (j *Journal) Previous() (uint64, error) { sd_journal_previous, err := getFunction("sd_journal_previous") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_previous(sd_journal_previous, j.cjournal) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to iterate journal: %d", syscall.Errno(-r)) } return uint64(r), nil } // PreviousSkip sets back the read pointer by multiple entries at once, // as specified by the skip parameter. func (j *Journal) PreviousSkip(skip uint64) (uint64, error) { sd_journal_previous_skip, err := getFunction("sd_journal_previous_skip") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_previous_skip(sd_journal_previous_skip, j.cjournal, C.uint64_t(skip)) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to iterate journal: %d", syscall.Errno(-r)) } return uint64(r), nil } func (j *Journal) getData(field string) (unsafe.Pointer, C.int, error) { sd_journal_get_data, err := getFunction("sd_journal_get_data") if err != nil { return nil, 0, err } f := C.CString(field) defer C.free(unsafe.Pointer(f)) var d unsafe.Pointer var l C.size_t j.mu.Lock() r := C.my_sd_journal_get_data(sd_journal_get_data, j.cjournal, f, &d, &l) j.mu.Unlock() if r < 0 { return nil, 0, fmt.Errorf("failed to read message: %d", syscall.Errno(-r)) } return d, C.int(l), nil } // GetData gets the data object associated with a specific field from the // the journal entry referenced by the last completed Next/Previous function // call. To call GetData, you must have first called one of these functions. func (j *Journal) GetData(field string) (string, error) { d, l, err := j.getData(field) if err != nil { return "", err } return C.GoStringN((*C.char)(d), l), nil } // GetDataValue gets the data object associated with a specific field from the // journal entry referenced by the last completed Next/Previous function call, // returning only the value of the object. To call GetDataValue, you must first // have called one of the Next/Previous functions. func (j *Journal) GetDataValue(field string) (string, error) { val, err := j.GetData(field) if err != nil { return "", err } return strings.SplitN(val, "=", 2)[1], nil } // GetDataBytes gets the data object associated with a specific field from the // journal entry referenced by the last completed Next/Previous function call. // To call GetDataBytes, you must first have called one of these functions. func (j *Journal) GetDataBytes(field string) ([]byte, error) { d, l, err := j.getData(field) if err != nil { return nil, err } return C.GoBytes(d, l), nil } // GetDataValueBytes gets the data object associated with a specific field from the // journal entry referenced by the last completed Next/Previous function call, // returning only the value of the object. To call GetDataValueBytes, you must first // have called one of the Next/Previous functions. func (j *Journal) GetDataValueBytes(field string) ([]byte, error) { val, err := j.GetDataBytes(field) if err != nil { return nil, err } return bytes.SplitN(val, []byte("="), 2)[1], nil } // GetEntry returns a full representation of the journal entry referenced by the // last completed Next/Previous function call, with all key-value pairs of data // as well as address fields (cursor, realtime timestamp and monotonic timestamp). // To call GetEntry, you must first have called one of the Next/Previous functions. func (j *Journal) GetEntry() (*JournalEntry, error) { sd_journal_get_realtime_usec, err := getFunction("sd_journal_get_realtime_usec") if err != nil { return nil, err } sd_journal_get_monotonic_usec, err := getFunction("sd_journal_get_monotonic_usec") if err != nil { return nil, err } sd_journal_get_cursor, err := getFunction("sd_journal_get_cursor") if err != nil { return nil, err } sd_journal_restart_data, err := getFunction("sd_journal_restart_data") if err != nil { return nil, err } sd_journal_enumerate_data, err := getFunction("sd_journal_enumerate_data") if err != nil { return nil, err } j.mu.Lock() defer j.mu.Unlock() var r C.int entry := &JournalEntry{Fields: make(map[string]string)} var realtimeUsec C.uint64_t r = C.my_sd_journal_get_realtime_usec(sd_journal_get_realtime_usec, j.cjournal, &realtimeUsec) if r < 0 { return nil, fmt.Errorf("failed to get realtime timestamp: %d", syscall.Errno(-r)) } entry.RealtimeTimestamp = uint64(realtimeUsec) var monotonicUsec C.uint64_t var boot_id C.sd_id128_t r = C.my_sd_journal_get_monotonic_usec(sd_journal_get_monotonic_usec, j.cjournal, &monotonicUsec, &boot_id) if r < 0 { return nil, fmt.Errorf("failed to get monotonic timestamp: %d", syscall.Errno(-r)) } entry.MonotonicTimestamp = uint64(monotonicUsec) var c *C.char // since the pointer is mutated by sd_journal_get_cursor, need to wait // until after the call to free the memory r = C.my_sd_journal_get_cursor(sd_journal_get_cursor, j.cjournal, &c) defer C.free(unsafe.Pointer(c)) if r < 0 { return nil, fmt.Errorf("failed to get cursor: %d", syscall.Errno(-r)) } entry.Cursor = C.GoString(c) // Implements the JOURNAL_FOREACH_DATA_RETVAL macro from journal-internal.h var d unsafe.Pointer var l C.size_t C.my_sd_journal_restart_data(sd_journal_restart_data, j.cjournal) for { r = C.my_sd_journal_enumerate_data(sd_journal_enumerate_data, j.cjournal, &d, &l) if r == 0 { break } if r < 0 { return nil, fmt.Errorf("failed to read message field: %d", syscall.Errno(-r)) } msg := C.GoStringN((*C.char)(d), C.int(l)) kv := strings.SplitN(msg, "=", 2) if len(kv) < 2 { return nil, fmt.Errorf("failed to parse field") } entry.Fields[kv[0]] = kv[1] } return entry, nil } // SetDataThreshold sets the data field size threshold for data returned by // GetData. To retrieve the complete data fields this threshold should be // turned off by setting it to 0, so that the library always returns the // complete data objects. func (j *Journal) SetDataThreshold(threshold uint64) error { sd_journal_set_data_threshold, err := getFunction("sd_journal_set_data_threshold") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_set_data_threshold(sd_journal_set_data_threshold, j.cjournal, C.size_t(threshold)) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to set data threshold: %d", syscall.Errno(-r)) } return nil } // GetRealtimeUsec gets the realtime (wallclock) timestamp of the journal // entry referenced by the last completed Next/Previous function call. To // call GetRealtimeUsec, you must first have called one of the Next/Previous // functions. func (j *Journal) GetRealtimeUsec() (uint64, error) { var usec C.uint64_t sd_journal_get_realtime_usec, err := getFunction("sd_journal_get_realtime_usec") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_get_realtime_usec(sd_journal_get_realtime_usec, j.cjournal, &usec) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to get realtime timestamp: %d", syscall.Errno(-r)) } return uint64(usec), nil } // GetMonotonicUsec gets the monotonic timestamp of the journal entry // referenced by the last completed Next/Previous function call. To call // GetMonotonicUsec, you must first have called one of the Next/Previous // functions. func (j *Journal) GetMonotonicUsec() (uint64, error) { var usec C.uint64_t var boot_id C.sd_id128_t sd_journal_get_monotonic_usec, err := getFunction("sd_journal_get_monotonic_usec") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_get_monotonic_usec(sd_journal_get_monotonic_usec, j.cjournal, &usec, &boot_id) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to get monotonic timestamp: %d", syscall.Errno(-r)) } return uint64(usec), nil } // GetCursor gets the cursor of the last journal entry reeferenced by the // last completed Next/Previous function call. To call GetCursor, you must // first have called one of the Next/Previous functions. func (j *Journal) GetCursor() (string, error) { sd_journal_get_cursor, err := getFunction("sd_journal_get_cursor") if err != nil { return "", err } var d *C.char // since the pointer is mutated by sd_journal_get_cursor, need to wait // until after the call to free the memory j.mu.Lock() r := C.my_sd_journal_get_cursor(sd_journal_get_cursor, j.cjournal, &d) j.mu.Unlock() defer C.free(unsafe.Pointer(d)) if r < 0 { return "", fmt.Errorf("failed to get cursor: %d", syscall.Errno(-r)) } cursor := C.GoString(d) return cursor, nil } // TestCursor checks whether the current position in the journal matches the // specified cursor func (j *Journal) TestCursor(cursor string) error { sd_journal_test_cursor, err := getFunction("sd_journal_test_cursor") if err != nil { return err } c := C.CString(cursor) defer C.free(unsafe.Pointer(c)) j.mu.Lock() r := C.my_sd_journal_test_cursor(sd_journal_test_cursor, j.cjournal, c) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to test to cursor %q: %d", cursor, syscall.Errno(-r)) } else if r == 0 { return ErrNoTestCursor } return nil } // SeekHead seeks to the beginning of the journal, i.e. the oldest available // entry. This call must be followed by a call to Next before any call to // Get* will return data about the first element. func (j *Journal) SeekHead() error { sd_journal_seek_head, err := getFunction("sd_journal_seek_head") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_seek_head(sd_journal_seek_head, j.cjournal) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to seek to head of journal: %d", syscall.Errno(-r)) } return nil } // SeekTail may be used to seek to the end of the journal, i.e. the most recent // available entry. This call must be followed by a call to Next before any // call to Get* will return data about the last element. func (j *Journal) SeekTail() error { sd_journal_seek_tail, err := getFunction("sd_journal_seek_tail") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_seek_tail(sd_journal_seek_tail, j.cjournal) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to seek to tail of journal: %d", syscall.Errno(-r)) } return nil } // SeekRealtimeUsec seeks to the entry with the specified realtime (wallclock) // timestamp, i.e. CLOCK_REALTIME. This call must be followed by a call to // Next/Previous before any call to Get* will return data about the sought entry. func (j *Journal) SeekRealtimeUsec(usec uint64) error { sd_journal_seek_realtime_usec, err := getFunction("sd_journal_seek_realtime_usec") if err != nil { return err } j.mu.Lock() r := C.my_sd_journal_seek_realtime_usec(sd_journal_seek_realtime_usec, j.cjournal, C.uint64_t(usec)) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to seek to %d: %d", usec, syscall.Errno(-r)) } return nil } // SeekCursor seeks to a concrete journal cursor. This call must be // followed by a call to Next/Previous before any call to Get* will return // data about the sought entry. func (j *Journal) SeekCursor(cursor string) error { sd_journal_seek_cursor, err := getFunction("sd_journal_seek_cursor") if err != nil { return err } c := C.CString(cursor) defer C.free(unsafe.Pointer(c)) j.mu.Lock() r := C.my_sd_journal_seek_cursor(sd_journal_seek_cursor, j.cjournal, c) j.mu.Unlock() if r < 0 { return fmt.Errorf("failed to seek to cursor %q: %d", cursor, syscall.Errno(-r)) } return nil } // Wait will synchronously wait until the journal gets changed. The maximum time // this call sleeps may be controlled with the timeout parameter. If // sdjournal.IndefiniteWait is passed as the timeout parameter, Wait will // wait indefinitely for a journal change. func (j *Journal) Wait(timeout time.Duration) int { var to uint64 sd_journal_wait, err := getFunction("sd_journal_wait") if err != nil { return -1 } if timeout == IndefiniteWait { // sd_journal_wait(3) calls for a (uint64_t) -1 to be passed to signify // indefinite wait, but using a -1 overflows our C.uint64_t, so we use an // equivalent hex value. to = 0xffffffffffffffff } else { to = uint64(timeout / time.Microsecond) } j.mu.Lock() r := C.my_sd_journal_wait(sd_journal_wait, j.cjournal, C.uint64_t(to)) j.mu.Unlock() return int(r) } // GetUsage returns the journal disk space usage, in bytes. func (j *Journal) GetUsage() (uint64, error) { var out C.uint64_t sd_journal_get_usage, err := getFunction("sd_journal_get_usage") if err != nil { return 0, err } j.mu.Lock() r := C.my_sd_journal_get_usage(sd_journal_get_usage, j.cjournal, &out) j.mu.Unlock() if r < 0 { return 0, fmt.Errorf("failed to get journal disk space usage: %d", syscall.Errno(-r)) } return uint64(out), nil } // GetUniqueValues returns all unique values for a given field. func (j *Journal) GetUniqueValues(field string) ([]string, error) { var result []string sd_journal_query_unique, err := getFunction("sd_journal_query_unique") if err != nil { return nil, err } sd_journal_enumerate_unique, err := getFunction("sd_journal_enumerate_unique") if err != nil { return nil, err } sd_journal_restart_unique, err := getFunction("sd_journal_restart_unique") if err != nil { return nil, err } j.mu.Lock() defer j.mu.Unlock() f := C.CString(field) defer C.free(unsafe.Pointer(f)) r := C.my_sd_journal_query_unique(sd_journal_query_unique, j.cjournal, f) if r < 0 { return nil, fmt.Errorf("failed to query journal: %d", syscall.Errno(-r)) } // Implements the SD_JOURNAL_FOREACH_UNIQUE macro from sd-journal.h var d unsafe.Pointer var l C.size_t C.my_sd_journal_restart_unique(sd_journal_restart_unique, j.cjournal) for { r = C.my_sd_journal_enumerate_unique(sd_journal_enumerate_unique, j.cjournal, &d, &l) if r == 0 { break } if r < 0 { return nil, fmt.Errorf("failed to read message field: %d", syscall.Errno(-r)) } msg := C.GoStringN((*C.char)(d), C.int(l)) kv := strings.SplitN(msg, "=", 2) if len(kv) < 2 { return nil, fmt.Errorf("failed to parse field") } result = append(result, kv[1]) } return result, nil } // GetCatalog retrieves a message catalog entry for the journal entry referenced // by the last completed Next/Previous function call. To call GetCatalog, you // must first have called one of these functions. func (j *Journal) GetCatalog() (string, error) { sd_journal_get_catalog, err := getFunction("sd_journal_get_catalog") if err != nil { return "", err } var c *C.char j.mu.Lock() r := C.my_sd_journal_get_catalog(sd_journal_get_catalog, j.cjournal, &c) j.mu.Unlock() defer C.free(unsafe.Pointer(c)) if r < 0 { return "", fmt.Errorf("failed to retrieve catalog entry for current journal entry: %d", syscall.Errno(-r)) } catalog := C.GoString(c) return catalog, nil }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service; import java.net.InetAddress; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import com.google.common.collect.AbstractIterator; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.RangeSliceReply; import org.apache.cassandra.db.Row; import org.apache.cassandra.net.AsyncOneResponse; import org.apache.cassandra.net.MessageIn; import org.apache.cassandra.utils.CloseableIterator; import org.apache.cassandra.utils.MergeIterator; import org.apache.cassandra.utils.Pair; /** * Turns RangeSliceReply objects into row (string -> CF) maps, resolving * to the most recent ColumnFamily and setting up read repairs as necessary. */ public class RangeSliceResponseResolver implements IResponseResolver<RangeSliceReply, Iterable<Row>> { private static final Comparator<Pair<Row,InetAddress>> pairComparator = new Comparator<Pair<Row, InetAddress>>() { public int compare(Pair<Row, InetAddress> o1, Pair<Row, InetAddress> o2) { return o1.left.key.compareTo(o2.left.key); } }; private final String keyspaceName; private final long timestamp; private List<InetAddress> sources; protected final Collection<MessageIn<RangeSliceReply>> responses = new ConcurrentLinkedQueue<MessageIn<RangeSliceReply>>(); public final List<AsyncOneResponse> repairResults = new ArrayList<AsyncOneResponse>(); public RangeSliceResponseResolver(String keyspaceName, long timestamp) { this.keyspaceName = keyspaceName; this.timestamp = timestamp; } public void setSources(List<InetAddress> endpoints) { this.sources = endpoints; } public List<Row> getData() { MessageIn<RangeSliceReply> response = responses.iterator().next(); return response.payload.rows; } // Note: this would deserialize the response a 2nd time if getData was called first. // (this is not currently an issue since we don't do read repair for range queries.) public Iterable<Row> resolve() { ArrayList<RowIterator> iters = new ArrayList<RowIterator>(responses.size()); int n = 0; for (MessageIn<RangeSliceReply> response : responses) { RangeSliceReply reply = response.payload; n = Math.max(n, reply.rows.size()); iters.add(new RowIterator(reply.rows.iterator(), response.from)); } // for each row, compute the combination of all different versions seen, and repair incomplete versions // TODO do we need to call close? CloseableIterator<Row> iter = MergeIterator.get(iters, pairComparator, new Reducer()); List<Row> resolvedRows = new ArrayList<Row>(n); while (iter.hasNext()) resolvedRows.add(iter.next()); return resolvedRows; } public void preprocess(MessageIn message) { responses.add(message); } public boolean isDataPresent() { return !responses.isEmpty(); } private static class RowIterator extends AbstractIterator<Pair<Row,InetAddress>> implements CloseableIterator<Pair<Row,InetAddress>> { private final Iterator<Row> iter; private final InetAddress source; private RowIterator(Iterator<Row> iter, InetAddress source) { this.iter = iter; this.source = source; } protected Pair<Row,InetAddress> computeNext() { return iter.hasNext() ? Pair.create(iter.next(), source) : endOfData(); } public void close() {} } public Iterable<MessageIn<RangeSliceReply>> getMessages() { return responses; } private class Reducer extends MergeIterator.Reducer<Pair<Row,InetAddress>, Row> { List<ColumnFamily> versions = new ArrayList<ColumnFamily>(sources.size()); List<InetAddress> versionSources = new ArrayList<InetAddress>(sources.size()); DecoratedKey key; public void reduce(Pair<Row,InetAddress> current) { key = current.left.key; versions.add(current.left.cf); versionSources.add(current.right); } protected Row getReduced() { ColumnFamily resolved = versions.size() > 1 ? RowDataResolver.resolveSuperset(versions, timestamp) : versions.get(0); if (versions.size() < sources.size()) { // add placeholder rows for sources that didn't have any data, so maybeScheduleRepairs sees them for (InetAddress source : sources) { if (!versionSources.contains(source)) { versions.add(null); versionSources.add(source); } } } // resolved can be null even if versions doesn't have all nulls because of the call to removeDeleted in resolveSuperSet if (resolved != null) repairResults.addAll(RowDataResolver.scheduleRepairs(resolved, keyspaceName, key, versions, versionSources)); versions.clear(); versionSources.clear(); return new Row(key, resolved); } } }
{ "pile_set_name": "Github" }
#define cross_width 14 #define cross_height 14 static char cross_bits[] = { 0x00, 0x00, 0x00, 0x00, 0x06, 0x18, 0x0e, 0x1c, 0x1c, 0x0e, 0x38, 0x07, 0xf0, 0x03, 0xe0, 0x01, 0xe0, 0x01, 0xf0, 0x03, 0x38, 0x07, 0x1c, 0x0e, 0x0e, 0x1c, 0x06, 0x18};
{ "pile_set_name": "Github" }
import '../../style/index.less'; import '../../grid/style';
{ "pile_set_name": "Github" }
freeStyleJob('update_fork_runc') { displayName('update-fork-runc') description('Rebase the primary branch (master) in jessfraz/runc fork.') checkoutRetryCount(3) properties { githubProjectUrl('https://github.com/jessfraz/runc') sidebarLinks { link('https://github.com/opencontainers/runc', 'UPSTREAM: opencontainers/runc', 'notepad.png') } } logRotator { numToKeep(100) daysToKeep(15) } scm { git { remote { url('git@github.com:jessfraz/runc.git') name('origin') credentials('ssh-github-key') refspec('+refs/heads/master:refs/remotes/origin/master') } remote { url('https://github.com/opencontainers/runc.git') name('upstream') refspec('+refs/heads/master:refs/remotes/upstream/master') } branches('master', 'upstream/master') extensions { disableRemotePoll() wipeOutWorkspace() cleanAfterCheckout() } } } triggers { cron('H H * * *') } wrappers { colorizeOutput() } steps { shell('git rebase upstream/master') } publishers { git { branch('origin', 'master') pushOnlyIfSuccess() } extendedEmail { recipientList('$DEFAULT_RECIPIENTS') contentType('text/plain') triggers { stillFailing { attachBuildLog(true) } } } wsCleanup() } }
{ "pile_set_name": "Github" }
EESchema-LIBRARY Version 2.3 DEF ESP8266EX U 0 40 Y Y 1 L N F0 "U" 150 250 60 H V R CNN F1 "ESP8266EX" 150 150 60 H V R CNN DRAW X U0RXD 25 1600 800 200 D 50 50 1 1 B X U0TXD 26 1500 800 200 D 50 50 1 1 B X XTAL_OUT 27 1400 800 200 D 50 50 1 1 B X XTAL_IN 28 1300 800 200 D 50 50 1 1 B X VDDD 29 1200 800 200 D 50 50 1 1 W X VDDA 30 1100 800 200 D 50 50 1 1 W X RES12K 31 1000 800 200 D 50 50 1 1 I X EXT_RSTB 32 900 800 200 D 50 50 1 1 I X GND_PAD 33 800 800 200 D 50 50 1 1 W X VDDPST 17 2600 -700 200 L 50 50 1 1 W X SDIO_DATA_2 18 2600 -600 200 L 50 50 1 1 B X SDIO_DATA_3 19 2600 -500 200 L 50 50 1 1 B X SDIO_CMD 20 2600 -400 200 L 50 50 1 1 B X SDIO_CLK 21 2600 -300 200 L 50 50 1 1 B X SDIO_DATA_0 22 2600 -200 200 L 50 50 1 1 B X SDIO_DATA_1 23 2600 -100 200 L 50 50 1 1 B X GPIO5 24 2600 0 200 L 50 50 1 1 B X MTMS 9 800 -1400 200 U 50 50 1 1 B X MTDI 10 900 -1400 200 U 50 50 1 1 B X VDDPST 11 1000 -1400 200 U 50 50 1 1 W X MTCK 12 1100 -1400 200 U 50 50 1 1 B X MTDO 13 1200 -1400 200 U 50 50 1 1 B X GPIO2 14 1300 -1400 200 U 50 50 1 1 B X GPIO0 15 1400 -1400 200 U 50 50 1 1 B X GPIO4 16 1500 -1400 200 U 50 50 1 1 B X VDDA 1 0 0 200 R 50 50 1 1 W X LNA 2 0 -100 200 R 50 50 1 1 P X VDD3P3 3 0 -200 200 R 50 50 1 1 W X VDD3P3 4 0 -300 200 R 50 50 1 1 W X VDD_RTC 5 0 -400 200 R 50 50 1 1 N X TOUT 6 0 -500 200 R 50 50 1 1 I X CHIP_PU 7 0 -600 200 R 50 50 1 1 I X XPD_DCDC 8 0 -700 200 R 50 50 1 1 B S 200 600 2400 -1200 1 1 12 N ENDDRAW ENDDEF DEF ESP8266EX_FULL U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP8266EX_FULL" 200 150 60 H V L CNN DRAW X VDDA 1 0 0 200 R 50 50 1 1 W X LNA 2 0 -100 200 R 50 50 1 1 P X VDD3P3 3 0 -200 200 R 50 50 1 1 W X VDD3P3 4 0 -300 200 R 50 50 1 1 W X VDD_RTC 5 0 -400 200 R 50 50 1 1 N X TOUT/ADC 6 0 -500 200 R 50 50 1 1 I X CHIP_PU 7 0 -600 200 R 50 50 1 1 I X GPIO16/XPD_DCDC/WAKE 8 0 -700 200 R 50 50 1 1 B X GPIO14/MTMS/HSPI_CLK 9 0 -800 200 R 50 50 1 1 B X GPIO12/MTDI/HSPI_MISO 10 0 -900 200 R 50 50 1 1 B X VDDPST 11 0 -1000 200 R 50 50 1 1 W X GPIO13/MTCK/HSPI_MOSI/UART0_CTS 12 0 -1100 200 R 50 50 1 1 B X GPIO15/MTDO/HSPI_CS/UART0_RTS 13 0 -1200 200 R 50 50 1 1 B X GPIO2 14 0 -1300 200 R 50 50 1 1 B X GPIO0/SPI_CS2 15 0 -1400 200 R 50 50 1 1 B X GPIO4 16 0 -1500 200 R 50 50 1 1 B X VDDPST 17 0 -1600 200 R 50 50 1 1 W X GPIO9/SDIO_DATA_2/SPIHD/HSPIHD 18 0 -1700 200 R 50 50 1 1 B X GPIO10/SDIO_DATA_3/SPIWP/HSPIWP 19 0 -1800 200 R 50 50 1 1 B X GPIO11/SDIO_CMD/SPI_CS0 20 0 -1900 200 R 50 50 1 1 B X GPIO6/SDIO_CLK/SPI_CLK 21 0 -2000 200 R 50 50 1 1 B X GPIO7/SDIO_DATA_0/SPI_MISO 22 0 -2100 200 R 50 50 1 1 B X GPIO8/SDIO_DATA_1/SPI_MOSI 23 0 -2200 200 R 50 50 1 1 B X GPIO5 24 0 -2300 200 R 50 50 1 1 B X GPIO3/U0RXD 25 0 -2400 200 R 50 50 1 1 B X GPIO1/U0TXD/SPI_CS1 26 0 -2500 200 R 50 50 1 1 B X XTAL_OUT 27 0 -2600 200 R 50 50 1 1 B X XTAL_IN 28 0 -2700 200 R 50 50 1 1 B X VDDD 29 0 -2800 200 R 50 50 1 1 W X VDDA 30 0 -2900 200 R 50 50 1 1 W X RES12K 31 0 -3000 200 R 50 50 1 1 I X EXT_RSTB 32 0 -3100 200 R 50 50 1 1 I X GND_PAD 33 0 -3200 200 R 50 50 1 1 W S 200 100 1900 -3300 1 1 12 N ENDDRAW ENDDEF DEF ESP-01 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-01" 200 150 60 H V L CNN DRAW X URXD 8 1200 -300 200 L 50 50 1 1 I X GPIO0 6 1200 -200 200 L 50 50 1 1 T X GPIO2 4 1200 -100 200 L 50 50 1 1 T X GND 2 1200 0 200 L 50 50 1 1 W X UTXD 1 0 0 200 R 50 50 1 1 O X CH_PD 3 0 -100 200 R 50 50 1 1 I X RST 5 0 -200 200 R 50 50 1 1 I X VCC 7 0 -300 200 R 50 50 1 1 W S 200 100 1000 -400 1 1 12 N ENDDRAW ENDDEF DEF ESP-02 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-02" 200 150 60 H V L CNN DRAW X VCC 5 1100 -300 200 L 50 50 1 1 W X UTXD 6 1100 -200 200 L 50 50 1 1 O X URXD 7 1100 -100 200 L 50 50 1 1 I X GND 8 1100 0 200 L 50 50 1 1 W X CH_PD 1 0 0 200 R 50 50 1 1 I X RST 2 0 -100 200 R 50 50 1 1 I X GPIO2 3 0 -200 200 R 50 50 1 1 B X GPIO0 4 0 -300 200 R 50 50 1 1 B S 200 100 900 -400 1 1 12 N ENDDRAW ENDDEF DEF ESP-03 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-03" 200 150 60 H V L CNN DRAW X GND 8 1200 -600 200 L 50 50 1 1 W X NC 9 1200 -500 200 L 50 50 1 1 N X UTXD 10 1200 -400 200 L 50 50 1 1 O X URXD 11 1200 -300 200 L 50 50 1 1 I X GPIO16 12 1200 -200 200 L 50 50 1 1 B X CH_PD 13 1200 -100 200 L 50 50 1 1 I X ANT 14 1200 0 200 L 50 50 1 1 U X VCC 1 0 0 200 R 50 50 1 1 W X GPIO14 2 0 -100 200 R 50 50 1 1 B X GPIO12 3 0 -200 200 R 50 50 1 1 B X GPIO13 4 0 -300 200 R 50 50 1 1 B X GPIO15 5 0 -400 200 R 50 50 1 1 B X GPIO2 6 0 -500 200 R 50 50 1 1 B X GPIO0 7 0 -600 200 R 50 50 1 1 B S 200 100 1000 -700 1 1 12 N ENDDRAW ENDDEF DEF ESP-04 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-04" 200 150 60 H V L CNN DRAW X GND 8 1200 -600 200 L 50 50 1 1 W X NC 9 1200 -500 200 L 50 50 1 1 N X UTXD 10 1200 -400 200 L 50 50 1 1 O X URXD 11 1200 -300 200 L 50 50 1 1 I X GPIO16 12 1200 -200 200 L 50 50 1 1 B X CH_PD 13 1200 -100 200 L 50 50 1 1 I X ANT 14 1200 0 200 L 50 50 1 1 U X VCC 1 0 0 200 R 50 50 1 1 W X GPIO14 2 0 -100 200 R 50 50 1 1 B X GPIO12 3 0 -200 200 R 50 50 1 1 B X GPIO13 4 0 -300 200 R 50 50 1 1 B X GPIO15 5 0 -400 200 R 50 50 1 1 B X GPIO2 6 0 -500 200 R 50 50 1 1 B X GPIO0 7 0 -600 200 R 50 50 1 1 B S 200 100 1000 -700 1 1 12 N ENDDRAW ENDDEF DEF ESP-05 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-05" 200 150 60 H V L CNN DRAW X RST 1 0 0 200 R 50 50 1 1 I X GND 2 0 -100 200 R 50 50 1 1 W X URXD 3 0 -200 200 R 50 50 1 1 I X UTXD 4 0 -300 200 R 50 50 1 1 O X VCC 5 0 -400 200 R 50 50 1 1 W S 200 100 500 -500 1 1 12 N ENDDRAW ENDDEF DEF ESP-07 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-07" 200 150 60 H V L CNN DRAW X GND 9 1200 -700 200 L 50 50 1 1 W X GPIO15 10 1200 -600 200 L 50 50 1 1 B X GPIO2 11 1200 -500 200 L 50 50 1 1 B X GPIO0 12 1200 -400 200 L 50 50 1 1 B X GPIO5 13 1200 -300 200 L 50 50 1 1 B X GPIO4 14 1200 -200 200 L 50 50 1 1 B X RXD0 15 1200 -100 200 L 50 50 1 1 I X TXD0 16 1200 0 200 L 50 50 1 1 O X RST 1 0 0 200 R 50 50 1 1 I X ADC 2 0 -100 200 R 50 50 1 1 P X EN 3 0 -200 200 R 50 50 1 1 I X GPIO16 4 0 -300 200 R 50 50 1 1 B X GPIO14 5 0 -400 200 R 50 50 1 1 B X GPIO12 6 0 -500 200 R 50 50 1 1 B X GPIO13 7 0 -600 200 R 50 50 1 1 B X VCC 8 0 -700 200 R 50 50 1 1 W S 200 100 1000 -800 1 1 12 N ENDDRAW ENDDEF DEF ESP-08 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-08" 200 150 60 H V L CNN DRAW X GND 9 1200 -700 200 L 50 50 1 1 W X GPIO15 10 1200 -600 200 L 50 50 1 1 B X GPIO2 11 1200 -500 200 L 50 50 1 1 B X GPIO0 12 1200 -400 200 L 50 50 1 1 B X GPIO5 13 1200 -300 200 L 50 50 1 1 B X GPIO4 14 1200 -200 200 L 50 50 1 1 B X RXD 15 1200 -100 200 L 50 50 1 1 I X TXD 16 1200 0 200 L 50 50 1 1 O X REST 1 0 0 200 R 50 50 1 1 I X ADC 2 0 -100 200 R 50 50 1 1 P X CH_PD 3 0 -200 200 R 50 50 1 1 I X GPIO16 4 0 -300 200 R 50 50 1 1 B X GPIO14 5 0 -400 200 R 50 50 1 1 B X GPIO12 6 0 -500 200 R 50 50 1 1 B X GPIO13 7 0 -600 200 R 50 50 1 1 B X VCC 8 0 -700 200 R 50 50 1 1 W S 200 100 1000 -800 1 1 12 N ENDDRAW ENDDEF DEF ESP-12 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-12" 200 150 60 H V L CNN DRAW X GND 9 1200 -700 200 L 50 50 1 1 W X GPIO15 10 1200 -600 200 L 50 50 1 1 B X GPIO2 11 1200 -500 200 L 50 50 1 1 B X GPIO0 12 1200 -400 200 L 50 50 1 1 B X GPIO4 13 1200 -300 200 L 50 50 1 1 B X GPIO5 14 1200 -200 200 L 50 50 1 1 B X RXD 15 1200 -100 200 L 50 50 1 1 I X TXD 16 1200 0 200 L 50 50 1 1 O X REST 1 0 0 200 R 50 50 1 1 I X ADC 2 0 -100 200 R 50 50 1 1 P X EN 3 0 -200 200 R 50 50 1 1 I X GPIO16 4 0 -300 200 R 50 50 1 1 B X GPIO14 5 0 -400 200 R 50 50 1 1 B X GPIO12 6 0 -500 200 R 50 50 1 1 B X GPIO13 7 0 -600 200 R 50 50 1 1 B X VCC 8 0 -700 200 R 50 50 1 1 W S 200 100 1000 -800 1 1 12 N ENDDRAW ENDDEF DEF ESP-12E U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-12E" 200 150 60 H V L CNN DRAW X GND 15 1900 -700 200 L 50 50 1 1 W X GPIO15 16 1900 -600 200 L 50 50 1 1 B X GPIO2 17 1900 -500 200 L 50 50 1 1 B X GPIO0 18 1900 -400 200 L 50 50 1 1 B X GPIO4 19 1900 -300 200 L 50 50 1 1 B X GPIO5 20 1900 -200 200 L 50 50 1 1 B X RXD 21 1900 -100 200 L 50 50 1 1 I X TXD 22 1900 0 200 L 50 50 1 1 O X CS0 9 700 -1400 200 U 50 50 1 1 B X MISO 10 800 -1400 200 U 50 50 1 1 B X GPIO9 11 900 -1400 200 U 50 50 1 1 B X GPIO10 12 1000 -1400 200 U 50 50 1 1 B X MOSI 13 1100 -1400 200 U 50 50 1 1 B X SCLK 14 1200 -1400 200 U 50 50 1 1 B X REST 1 0 0 200 R 50 50 1 1 I X ADC 2 0 -100 200 R 50 50 1 1 P X EN 3 0 -200 200 R 50 50 1 1 I X GPIO16 4 0 -300 200 R 50 50 1 1 B X GPIO14 5 0 -400 200 R 50 50 1 1 B X GPIO12 6 0 -500 200 R 50 50 1 1 B X GPIO13 7 0 -600 200 R 50 50 1 1 B X VCC 8 0 -700 200 R 50 50 1 1 W S 200 100 1700 -1200 1 1 12 N ENDDRAW ENDDEF DEF ESP-12F U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-12F" 200 150 60 H V L CNN DRAW X GND 15 1900 -700 200 L 50 50 1 1 W X GPIO15 16 1900 -600 200 L 50 50 1 1 B X GPIO2 17 1900 -500 200 L 50 50 1 1 B X GPIO0 18 1900 -400 200 L 50 50 1 1 B X GPIO4 19 1900 -300 200 L 50 50 1 1 B X GPIO5 20 1900 -200 200 L 50 50 1 1 B X RXD 21 1900 -100 200 L 50 50 1 1 I X TXD 22 1900 0 200 L 50 50 1 1 O X CS0 9 700 -1400 200 U 50 50 1 1 B X MISO 10 800 -1400 200 U 50 50 1 1 B X GPIO9 11 900 -1400 200 U 50 50 1 1 B X GPIO10 12 1000 -1400 200 U 50 50 1 1 B X MOSI 13 1100 -1400 200 U 50 50 1 1 B X SCLK 14 1200 -1400 200 U 50 50 1 1 B X RST 1 0 0 200 R 50 50 1 1 I X ADC 2 0 -100 200 R 50 50 1 1 P X EN 3 0 -200 200 R 50 50 1 1 I X GPIO16 4 0 -300 200 R 50 50 1 1 B X GPIO14 5 0 -400 200 R 50 50 1 1 B X GPIO12 6 0 -500 200 R 50 50 1 1 B X GPIO13 7 0 -600 200 R 50 50 1 1 B X VCC 8 0 -700 200 R 50 50 1 1 W S 200 100 1700 -1200 1 1 12 N ENDDRAW ENDDEF DEF ESP-13-WROOM-02 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-13-WROOM-02" 200 150 60 H V L CNN DRAW X GND_PAD PAD 700 -1600 200 U 50 50 1 1 W X GPIO4 10 1400 -800 200 L 50 50 1 1 B X RXD 11 1400 -700 200 L 50 50 1 1 B X TXD 12 1400 -600 200 L 50 50 1 1 B X GND 13 1400 -500 200 L 50 50 1 1 W X GPIO5 14 1400 -400 200 L 50 50 1 1 B X RST 15 1400 -300 200 L 50 50 1 1 I X TOUT 16 1400 -200 200 L 50 50 1 1 O X GPIO16 17 1400 -100 200 L 50 50 1 1 B X GND 18 1400 0 200 L 50 50 1 1 W X VCC 1 0 0 200 R 50 50 1 1 I X EN 2 0 -100 200 R 50 50 1 1 P X GPIO14 3 0 -200 200 R 50 50 1 1 I X GPIO12 4 0 -300 200 R 50 50 1 1 B X GPIO13 5 0 -400 200 R 50 50 1 1 B X GPIO15 6 0 -500 200 R 50 50 1 1 B X GPIO2 7 0 -600 200 R 50 50 1 1 B X GPIO0 8 0 -700 200 R 50 50 1 1 B X GND 9 0 -800 200 R 50 50 1 1 W S 200 100 1200 -1400 1 1 12 N ENDDRAW ENDDEF DEF ESP-14 U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP-14" 200 150 60 H V L CNN DRAW X M_VCAP 15 1900 -700 200 L 50 50 1 1 W X M_VDD 16 1900 -600 200 L 50 50 1 1 W X E_VDD 17 1900 -500 200 L 50 50 1 1 W X M_PA3 18 1900 -400 200 L 50 50 1 1 B X M_PB5 19 1900 -300 200 L 50 50 1 1 B X M_PB4 20 1900 -200 200 L 50 50 1 1 B X M_PC3 21 1900 -100 200 L 50 50 1 1 B X M_PC4 22 1900 0 200 L 50 50 1 1 B X M_PD2 9 700 -1500 200 U 50 50 1 1 B X M_PD5 10 800 -1500 200 U 50 50 1 1 B X M_PD6 11 900 -1500 200 U 50 50 1 1 B X M_PA1 12 1000 -1500 200 U 50 50 1 1 B X M_PA2 13 1100 -1500 200 U 50 50 1 1 B X E_GPIO0 14 1200 -1500 200 U 50 50 1 1 B X M_PC5 1 0 0 200 R 50 50 1 1 B X M_PC6 2 0 -100 200 R 50 50 1 1 B X M_PC7 3 0 -200 200 R 50 50 1 1 B X SWIM 4 0 -300 200 R 50 50 1 1 B X M_PD3 5 0 -400 200 R 50 50 1 1 B X M_PD4 6 0 -500 200 R 50 50 1 1 B X M_NRST 7 0 -600 200 R 50 50 1 1 I X GND 8 0 -700 200 R 50 50 1 1 W S 200 100 1700 -1300 1 1 12 N ENDDRAW ENDDEF DEF ESP-201 U 0 40 Y Y 1 L N F0 "U" 150 250 60 H V R CNN F1 "ESP-201" 150 150 60 H V R CNN DRAW X GND 23 1200 600 200 D 50 50 1 1 W X TX 24 1100 600 200 D 50 50 1 1 O X RX 25 1000 600 200 D 50 50 1 1 I X 3.3V 26 900 600 200 D 50 50 1 1 W X GND 12 2100 -1000 200 L 50 50 1 1 W X GND 13 2100 -900 200 L 50 50 1 1 W X GPIO5 14 2100 -800 200 L 50 50 1 1 B X T_OUT/ADC 15 2100 -700 200 L 50 50 1 1 B X RST 16 2100 -600 200 L 50 50 1 1 I X CHIP_EN 17 2100 -500 200 L 50 50 1 1 I X XPD/GPIO16 18 2100 -400 200 L 50 50 1 1 B X GPIO14 19 2100 -300 200 L 50 50 1 1 B X GPIO12 20 2100 -200 200 L 50 50 1 1 B X GPIO13 21 2100 -100 200 L 50 50 1 1 B X GPIO15 22 2100 0 200 L 50 50 1 1 B X GPIO0 1 0 0 200 R 50 50 1 1 B X GPIO2 2 0 -100 200 R 50 50 1 1 B X D2/GPIO9 3 0 -200 200 R 50 50 1 1 O X CLK/GPIO6 4 0 -300 200 R 50 50 1 1 O X CMD/GPIO11 5 0 -400 200 R 50 50 1 1 O X D0/GPIO7 6 0 -500 200 R 50 50 1 1 O X D1/GPIO8 7 0 -600 200 R 50 50 1 1 O X D3/GPIO10 8 0 -700 200 R 50 50 1 1 O X GPIO4 9 0 -800 200 R 50 50 1 1 B X 3.3V 10 0 -900 200 R 50 50 1 1 W X 3.3V 11 0 -1000 200 R 50 50 1 1 W S 200 400 1900 -1100 1 1 12 N ENDDRAW ENDDEF DEF ESP32 U 0 40 Y Y 1 L N F0 "U" 150 250 60 H V R CNN F1 "ESP32" 150 150 60 H V R CNN DRAW X VDD3P3_CPU 37 2200 900 200 D 50 50 1 1 W X GPIO19 38 2100 900 200 D 50 50 1 1 B X GPIO22 39 2000 900 200 D 50 50 1 1 B X U0RXD 40 1900 900 200 D 50 50 1 1 B X U0TXD 41 1800 900 200 D 50 50 1 1 B X GPIO21 42 1700 900 200 D 50 50 1 1 B X VDDA 43 1600 900 200 D 50 50 1 1 W X XTAL_N 44 1500 900 200 D 50 50 1 1 P X XTAL_P 45 1400 900 200 D 50 50 1 1 P X VDDA 46 1300 900 200 D 50 50 1 1 W X CAP2 47 1200 900 200 D 50 50 1 1 P X CAP1 48 1100 900 200 D 50 50 1 1 P X GND_PAD 49 1000 900 200 D 50 50 1 1 W X GPIO16 25 3100 -1100 200 L 50 50 1 1 B X VDD_SDIO 26 3100 -1000 200 L 50 50 1 1 W X GPIO17 27 3100 -900 200 L 50 50 1 1 B X SD_DATA_2 28 3100 -800 200 L 50 50 1 1 B X SD_DATA_3 29 3100 -700 200 L 50 50 1 1 B X SD_CMD 30 3100 -600 200 L 50 50 1 1 B X SD_CLK 31 3100 -500 200 L 50 50 1 1 B X SD_DATA_0 32 3100 -400 200 L 50 50 1 1 B X SD_DATA_1 33 3100 -300 200 L 50 50 1 1 B X GPIO5 34 3100 -200 200 L 50 50 1 1 B X GPIO18 35 3100 -100 200 L 50 50 1 1 B X GPIO23 36 3100 0 200 L 50 50 1 1 B X 32K_XN 13 1000 -2000 200 U 50 50 1 1 B X GPIO25 14 1100 -2000 200 U 50 50 1 1 B X GPIO26 15 1200 -2000 200 U 50 50 1 1 B X GPIO27 16 1300 -2000 200 U 50 50 1 1 B X MTMS 17 1400 -2000 200 U 50 50 1 1 B X MTDI 18 1500 -2000 200 U 50 50 1 1 B X VDD3P3_RTC 19 1600 -2000 200 U 50 50 1 1 W X MTCK 20 1700 -2000 200 U 50 50 1 1 B X MTDO 21 1800 -2000 200 U 50 50 1 1 B X GPIO2 22 1900 -2000 200 U 50 50 1 1 B X GPIO0 23 2000 -2000 200 U 50 50 1 1 B X GPIO4 24 2100 -2000 200 U 50 50 1 1 B X VDDA 1 0 0 200 R 50 50 1 1 W X LNA_IN 2 0 -100 200 R 50 50 1 1 U X VDD3P3 3 0 -200 200 R 50 50 1 1 W X VDD3P3 4 0 -300 200 R 50 50 1 1 W X SENSOR_VP 5 0 -400 200 R 50 50 1 1 I X SENSOR_CAPP 6 0 -500 200 R 50 50 1 1 I X SENSOR_CAPN 7 0 -600 200 R 50 50 1 1 I X SENSOR_VN 8 0 -700 200 R 50 50 1 1 I X CHIP_PU 9 0 -800 200 R 50 50 1 1 I X VDET_1 10 0 -900 200 R 50 50 1 1 I X VDET_2 11 0 -1000 200 R 50 50 1 1 I X 32K_XP 12 0 -1100 200 R 50 50 1 1 B S 200 700 2900 -1800 1 1 12 N ENDDRAW ENDDEF DEF ESP32_FULL U 0 40 Y Y 1 L N F0 "U" 200 250 60 H V L CNN F1 "ESP32_FULL" 200 150 60 H V L CNN DRAW X VDDA 1 0 0 200 R 50 50 1 1 W X LNA_IN 2 0 -100 200 R 50 50 1 1 U X VDD3P3 3 0 -200 200 R 50 50 1 1 W X VDD3P3 4 0 -300 200 R 50 50 1 1 W X SENSOR_VP/ADC_H/ADC1_CH0/RTC_GPIO0/GPIO36 5 0 -400 200 R 50 50 1 1 I X SENSOR_CAPP/ADC_H/ADC1_CH1/RTC_GPIO1/GPIO37 6 0 -500 200 R 50 50 1 1 I X SENSOR_CAPN/ADC_H/ADC1_CH2/RTC_GPIO2/GPIO38 7 0 -600 200 R 50 50 1 1 I X SENSOR_VN/ADC_H/ADC1_CH3/RTC_GPIO3/GPIO39 8 0 -700 200 R 50 50 1 1 I X CHIP_PU 9 0 -800 200 R 50 50 1 1 I X VDET_1/ADC1_CH6/RTC_GPIO4/GPIO34 10 0 -900 200 R 50 50 1 1 I X VDET_2/ADC1_CH7/RTC_GPIO5/GPIO35 11 0 -1000 200 R 50 50 1 1 I X 32K_XP/XTAL_32K_P/ADC1_CH4/TOUCH9/RTC_GPIO9//GPIO32 12 0 -1100 200 R 50 50 1 1 B X 32K_XN/XTAL_32K_N/ADC1_CH5/TOUCH8/RTC_GPIO8/GPIO33 13 0 -1200 200 R 50 50 1 1 B X GPIO25/DAC_1/ADC2_CH8/RTC_GPIO6/EMAC_RXD0 14 0 -1300 200 R 50 50 1 1 B X GPIO26/DAC_2/ADC2_CH9/RTC_GPIO7/EMAC_RXD1 15 0 -1400 200 R 50 50 1 1 B X GPIO27/ADC2_CH7/TOUCH7/RTC_GPIO17/EMAC_RX_DV 16 0 -1500 200 R 50 50 1 1 B X MTMS/ADC2_CH6/TOUCH6/RTC_GPIO16/HSPICLK/GPIO14/HS2_CLK/SD_CLK/EMAC_TXD2 17 0 -1600 200 R 50 50 1 1 B X MTDI/ADC2_CH5/TOUCH5/RTC_GPIO15/HSPIQ/GPIO12/HS2_DATA2/SD_DATA2/EMAC_TXD3 18 0 -1700 200 R 50 50 1 1 B X VDD3P3_RTC 19 0 -1800 200 R 50 50 1 1 W X MTCK/ADC2_CH4/TOUCH4/RTC_GPIO14/HSPID/GPIO13/HS2_DATA3/SD_DATA3/EMAC_RX_ER 20 0 -1900 200 R 50 50 1 1 B X MTDO/ADC2_CH3/TOUCH3/RTC_GPIO13/HSPICS0/GPIO15/HS2_CMD/SD_CMD/EMAC_RXD3 21 0 -2000 200 R 50 50 1 1 B X GPIO2/ADC2_CH2/TOUCH2/RTC_GPIO12/HSPIWP/HS2_DATA0/SD_DATA0 22 0 -2100 200 R 50 50 1 1 B X GPIO0/ADC2_CH1/TOUCH1/RTC_GPIO11/CLK_OUT1/EMAC_TX_CLK 23 0 -2200 200 R 50 50 1 1 B X GPIO4/ADC2_CH0/TOUCH0/RTC_GPIO10/HSPIHD/HS2_DATA1/SD_DATA1/EMAC_TX_ER 24 0 -2300 200 R 50 50 1 1 B X GPIO16/HS1_DATA4/U2RXD/EMAC_CLK_OUT 25 0 -2400 200 R 50 50 1 1 B X VDD_SDIO 26 0 -2500 200 R 50 50 1 1 W X GPIO17/HS1_DATA5/U2TXD/EMAC_CLK_OUT_180 27 0 -2600 200 R 50 50 1 1 B X SD_DATA_2/SPIHD/GPIO9/HS1_DATA2/U1RXD 28 0 -2700 200 R 50 50 1 1 B X SD_DATA_3/SPIWP/GPIO10/HS1_DATA3/U1TXD 29 0 -2800 200 R 50 50 1 1 B X SD_CMD/SPICS0/GPIO11/HS1_CMD/U1RTS 30 0 -2900 200 R 50 50 1 1 B X SD_CLK/SPICLK/GPIO6/HS1_CLK/U1CTS 31 0 -3000 200 R 50 50 1 1 B X SD_DATA_0/SPIQ/GPIO7/HS1_DATA0/U2RTS 32 0 -3100 200 R 50 50 1 1 B X SD_DATA_1/SPID/GPIO8/HS1_DATA1/U2CTS 33 0 -3200 200 R 50 50 1 1 B X GPIO5/VSPICS0/HS1_DATA6/EMAC_RX_CLK 34 0 -3300 200 R 50 50 1 1 B X GPIO18/VSPICLK/GPIO18/HS1_DATA7 35 0 -3400 200 R 50 50 1 1 B X GPIO23/VSPID/HS1_STROBE 36 0 -3500 200 R 50 50 1 1 B X VDD3P3_CPU 37 0 -3600 200 R 50 50 1 1 W X GPIO19/VSPIQ/GPIO19/U0CTS/EMAC_TXD0 38 0 -3700 200 R 50 50 1 1 B X GPIO22/VSPIWP/U0RTS/EMAC_TXD1 39 0 -3800 200 R 50 50 1 1 B X U0RXD/CLK_OUT2/GPIO3/ 40 0 -3900 200 R 50 50 1 1 B X U0TXD/CLK_OUT3/GPIO1/EMAC_RXD2 41 0 -4000 200 R 50 50 1 1 B X GPIO21/VSPIHD/EMAC_TX_EN 42 0 -4100 200 R 50 50 1 1 B X VDDA 43 0 -4200 200 R 50 50 1 1 W X XTAL_N 44 0 -4300 200 R 50 50 1 1 P X XTAL_P 45 0 -4400 200 R 50 50 1 1 P X VDDA 46 0 -4500 200 R 50 50 1 1 W X CAP2 47 0 -4600 200 R 50 50 1 1 P X CAP1 48 0 -4700 200 R 50 50 1 1 P X GND_PAD 49 0 -4800 200 R 50 50 1 1 W S 200 100 4000 -4900 1 1 12 N ENDDRAW ENDDEF DEF ESP32-WROOM U 0 40 Y Y 1 L N F0 "U" 150 250 60 H V R CNN F1 "ESP32-WROOM" 150 150 60 H V R CNN DRAW X GND_PAD 39 1800 800 200 D 50 50 1 1 W X IO0 25 2400 -1300 200 L 50 50 1 1 B X IO4 26 2400 -1200 200 L 50 50 1 1 B X IO16 27 2400 -1100 200 L 50 50 1 1 B X IO17 28 2400 -1000 200 L 50 50 1 1 B X IO5 29 2400 -900 200 L 50 50 1 1 B X IO18 30 2400 -800 200 L 50 50 1 1 B X IO19 31 2400 -700 200 L 50 50 1 1 B X NC 32 2400 -600 200 L 50 50 1 1 N X IO21 33 2400 -500 200 L 50 50 1 1 B X RXD0 34 2400 -400 200 L 50 50 1 1 B X TXD0 35 2400 -300 200 L 50 50 1 1 B X IO22 36 2400 -200 200 L 50 50 1 1 B X IO23 37 2400 -100 200 L 50 50 1 1 B X GND 38 2400 0 200 L 50 50 1 1 W X GND 15 900 -2100 200 U 50 50 1 1 W X IO13 16 1000 -2100 200 U 50 50 1 1 B X SD2/IO9 17 1100 -2100 200 U 50 50 1 1 B X SD3/IO10 18 1200 -2100 200 U 50 50 1 1 B X CMD/IO11 19 1300 -2100 200 U 50 50 1 1 B X CLK/IO6 20 1400 -2100 200 U 50 50 1 1 B X SD0/IO7 21 1500 -2100 200 U 50 50 1 1 B X SD1/IO8 22 1600 -2100 200 U 50 50 1 1 B X IO15 23 1700 -2100 200 U 50 50 1 1 B X IO2 24 1800 -2100 200 U 50 50 1 1 B X GND 1 0 0 200 R 50 50 1 1 W X VCC 2 0 -100 200 R 50 50 1 1 W X EN 3 0 -200 200 R 50 50 1 1 I X SENSOR_VP 4 0 -300 200 R 50 50 1 1 I X SENSOR_VN 5 0 -400 200 R 50 50 1 1 I X IO34 6 0 -500 200 R 50 50 1 1 B X IO35 7 0 -600 200 R 50 50 1 1 B X IO32 8 0 -700 200 R 50 50 1 1 B X IO33 9 0 -800 200 R 50 50 1 1 B X IO25 10 0 -900 200 R 50 50 1 1 B X IO26 11 0 -1000 200 R 50 50 1 1 I X IO27 12 0 -1100 200 R 50 50 1 1 B X IO14 13 0 -1200 200 R 50 50 1 1 B X IO12 14 0 -1300 200 R 50 50 1 1 B S 200 600 2200 -1900 1 1 12 N ENDDRAW ENDDEF DEF ESP32S U 0 40 Y Y 1 L N F0 "U" 150 250 60 H V R CNN F1 "ESP32S" 150 150 60 H V R CNN DRAW X GND_PAD 39 1800 800 200 D 50 50 1 1 W X IO0 25 2400 -1300 200 L 50 50 1 1 B X IO4 26 2400 -1200 200 L 50 50 1 1 B X IO16 27 2400 -1100 200 L 50 50 1 1 B X IO17 28 2400 -1000 200 L 50 50 1 1 B X IO5 29 2400 -900 200 L 50 50 1 1 B X IO18 30 2400 -800 200 L 50 50 1 1 B X IO19 31 2400 -700 200 L 50 50 1 1 B X NC 32 2400 -600 200 L 50 50 1 1 N X IO21 33 2400 -500 200 L 50 50 1 1 B X RXD0 34 2400 -400 200 L 50 50 1 1 B X TXD0 35 2400 -300 200 L 50 50 1 1 B X IO22 36 2400 -200 200 L 50 50 1 1 B X IO23 37 2400 -100 200 L 50 50 1 1 B X GND 38 2400 0 200 L 50 50 1 1 W X GND 15 900 -2100 200 U 50 50 1 1 W X IO13 16 1000 -2100 200 U 50 50 1 1 B X SD2/IO9 17 1100 -2100 200 U 50 50 1 1 B X SD3/IO10 18 1200 -2100 200 U 50 50 1 1 B X CMD/IO11 19 1300 -2100 200 U 50 50 1 1 B X CLK/IO6 20 1400 -2100 200 U 50 50 1 1 B X SD0/IO7 21 1500 -2100 200 U 50 50 1 1 B X SD1/IO8 22 1600 -2100 200 U 50 50 1 1 B X IO15 23 1700 -2100 200 U 50 50 1 1 B X IO2 24 1800 -2100 200 U 50 50 1 1 B X GND 1 0 0 200 R 50 50 1 1 W X VCC 2 0 -100 200 R 50 50 1 1 W X EN 3 0 -200 200 R 50 50 1 1 I X SENSOR_VP 4 0 -300 200 R 50 50 1 1 I X SENSOR_VN 5 0 -400 200 R 50 50 1 1 I X IO34 6 0 -500 200 R 50 50 1 1 B X IO35 7 0 -600 200 R 50 50 1 1 B X IO32 8 0 -700 200 R 50 50 1 1 B X IO33 9 0 -800 200 R 50 50 1 1 B X IO25 10 0 -900 200 R 50 50 1 1 B X IO26 11 0 -1000 200 R 50 50 1 1 I X IO27 12 0 -1100 200 R 50 50 1 1 B X IO14 13 0 -1200 200 R 50 50 1 1 B X IO12 14 0 -1300 200 R 50 50 1 1 B S 200 600 2200 -1900 1 1 12 N ENDDRAW ENDDEF
{ "pile_set_name": "Github" }
/****************************************************************************** * * Copyright(c) 2013 - 2017 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * *****************************************************************************/ #include <drv_types.h> #include <hal_data.h> #ifdef CONFIG_BT_COEXIST #include <hal_btcoex.h> void rtw_btcoex_Initialize(PADAPTER padapter) { hal_btcoex_Initialize(padapter); } void rtw_btcoex_PowerOnSetting(PADAPTER padapter) { hal_btcoex_PowerOnSetting(padapter); } void rtw_btcoex_AntInfoSetting(PADAPTER padapter) { hal_btcoex_AntInfoSetting(padapter); } void rtw_btcoex_PowerOffSetting(PADAPTER padapter) { hal_btcoex_PowerOffSetting(padapter); } void rtw_btcoex_PreLoadFirmware(PADAPTER padapter) { hal_btcoex_PreLoadFirmware(padapter); } void rtw_btcoex_HAL_Initialize(PADAPTER padapter, u8 bWifiOnly) { hal_btcoex_InitHwConfig(padapter, bWifiOnly); } void rtw_btcoex_IpsNotify(PADAPTER padapter, u8 type) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_IpsNotify(padapter, type); } void rtw_btcoex_LpsNotify(PADAPTER padapter, u8 type) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_LpsNotify(padapter, type); } void rtw_btcoex_ScanNotify(PADAPTER padapter, u8 type) { PHAL_DATA_TYPE pHalData; #ifdef CONFIG_BT_COEXIST_SOCKET_TRX struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; #endif /* CONFIG_BT_COEXIST_SOCKET_TRX */ pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; if (_FALSE == type) { #ifdef CONFIG_CONCURRENT_MODE if (rtw_mi_buddy_check_fwstate(padapter, WIFI_SITE_MONITOR)) return; #endif if (DEV_MGMT_TX_NUM(adapter_to_dvobj(padapter)) || DEV_ROCH_NUM(adapter_to_dvobj(padapter))) return; } #ifdef CONFIG_BT_COEXIST_SOCKET_TRX if (pBtMgnt->ExtConfig.bEnableWifiScanNotify) rtw_btcoex_SendScanNotify(padapter, type); #endif /* CONFIG_BT_COEXIST_SOCKET_TRX */ hal_btcoex_ScanNotify(padapter, type); } void rtw_btcoex_ConnectNotify(PADAPTER padapter, u8 action) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; #ifdef DBG_CONFIG_ERROR_RESET if (_TRUE == rtw_hal_sreset_inprogress(padapter)) { RTW_INFO(FUNC_ADPT_FMT ": [BTCoex] under reset, skip notify!\n", FUNC_ADPT_ARG(padapter)); return; } #endif /* DBG_CONFIG_ERROR_RESET */ #ifdef CONFIG_CONCURRENT_MODE if (_FALSE == action) { if (rtw_mi_buddy_check_fwstate(padapter, WIFI_UNDER_LINKING)) return; } #endif hal_btcoex_ConnectNotify(padapter, action); } void rtw_btcoex_MediaStatusNotify(PADAPTER padapter, u8 mediaStatus) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; #ifdef DBG_CONFIG_ERROR_RESET if (_TRUE == rtw_hal_sreset_inprogress(padapter)) { RTW_INFO(FUNC_ADPT_FMT ": [BTCoex] under reset, skip notify!\n", FUNC_ADPT_ARG(padapter)); return; } #endif /* DBG_CONFIG_ERROR_RESET */ #ifdef CONFIG_CONCURRENT_MODE if (RT_MEDIA_DISCONNECT == mediaStatus) { if (rtw_mi_buddy_check_fwstate(padapter, WIFI_ASOC_STATE)) return; } #endif /* CONFIG_CONCURRENT_MODE */ if ((RT_MEDIA_CONNECT == mediaStatus) && (check_fwstate(&padapter->mlmepriv, WIFI_AP_STATE) == _TRUE)) rtw_hal_set_hwreg(padapter, HW_VAR_DL_RSVD_PAGE, NULL); hal_btcoex_MediaStatusNotify(padapter, mediaStatus); } void rtw_btcoex_SpecialPacketNotify(PADAPTER padapter, u8 pktType) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_SpecialPacketNotify(padapter, pktType); } void rtw_btcoex_IQKNotify(PADAPTER padapter, u8 state) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_IQKNotify(padapter, state); } void rtw_btcoex_BtInfoNotify(PADAPTER padapter, u8 length, u8 *tmpBuf) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_BtInfoNotify(padapter, length, tmpBuf); } void rtw_btcoex_BtMpRptNotify(PADAPTER padapter, u8 length, u8 *tmpBuf) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; if (padapter->registrypriv.mp_mode == 1) return; hal_btcoex_BtMpRptNotify(padapter, length, tmpBuf); } void rtw_btcoex_SuspendNotify(PADAPTER padapter, u8 state) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_SuspendNotify(padapter, state); } void rtw_btcoex_HaltNotify(PADAPTER padapter) { PHAL_DATA_TYPE pHalData; u8 do_halt = 1; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) do_halt = 0; if (_FALSE == padapter->bup) { RTW_INFO(FUNC_ADPT_FMT ": bup=%d Skip!\n", FUNC_ADPT_ARG(padapter), padapter->bup); do_halt = 0; } if (rtw_is_surprise_removed(padapter)) { RTW_INFO(FUNC_ADPT_FMT ": bSurpriseRemoved=%s Skip!\n", FUNC_ADPT_ARG(padapter), rtw_is_surprise_removed(padapter) ? "True" : "False"); do_halt = 0; } hal_btcoex_HaltNotify(padapter, do_halt); } void rtw_btcoex_switchband_notify(u8 under_scan, u8 band_type) { hal_btcoex_switchband_notify(under_scan, band_type); } void rtw_btcoex_WlFwDbgInfoNotify(PADAPTER padapter, u8* tmpBuf, u8 length) { hal_btcoex_WlFwDbgInfoNotify(padapter, tmpBuf, length); } void rtw_btcoex_rx_rate_change_notify(PADAPTER padapter, u8 is_data_frame, u8 rate_id) { hal_btcoex_rx_rate_change_notify(padapter, is_data_frame, rate_id); } void rtw_btcoex_SwitchBtTRxMask(PADAPTER padapter) { hal_btcoex_SwitchBtTRxMask(padapter); } void rtw_btcoex_Switch(PADAPTER padapter, u8 enable) { hal_btcoex_SetBTCoexist(padapter, enable); } u8 rtw_btcoex_IsBtDisabled(PADAPTER padapter) { return hal_btcoex_IsBtDisabled(padapter); } void rtw_btcoex_Handler(PADAPTER padapter) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); if (_FALSE == pHalData->EEPROMBluetoothCoexist) return; hal_btcoex_Hanlder(padapter); } s32 rtw_btcoex_IsBTCoexRejectAMPDU(PADAPTER padapter) { s32 coexctrl; coexctrl = hal_btcoex_IsBTCoexRejectAMPDU(padapter); return coexctrl; } s32 rtw_btcoex_IsBTCoexCtrlAMPDUSize(PADAPTER padapter) { s32 coexctrl; coexctrl = hal_btcoex_IsBTCoexCtrlAMPDUSize(padapter); return coexctrl; } u32 rtw_btcoex_GetAMPDUSize(PADAPTER padapter) { u32 size; size = hal_btcoex_GetAMPDUSize(padapter); return size; } void rtw_btcoex_SetManualControl(PADAPTER padapter, u8 manual) { if (_TRUE == manual) hal_btcoex_SetManualControl(padapter, _TRUE); else hal_btcoex_SetManualControl(padapter, _FALSE); } u8 rtw_btcoex_1Ant(PADAPTER padapter) { return hal_btcoex_1Ant(padapter); } u8 rtw_btcoex_IsBtControlLps(PADAPTER padapter) { return hal_btcoex_IsBtControlLps(padapter); } u8 rtw_btcoex_IsLpsOn(PADAPTER padapter) { return hal_btcoex_IsLpsOn(padapter); } u8 rtw_btcoex_RpwmVal(PADAPTER padapter) { return hal_btcoex_RpwmVal(padapter); } u8 rtw_btcoex_LpsVal(PADAPTER padapter) { return hal_btcoex_LpsVal(padapter); } u32 rtw_btcoex_GetRaMask(PADAPTER padapter) { return hal_btcoex_GetRaMask(padapter); } void rtw_btcoex_RecordPwrMode(PADAPTER padapter, u8 *pCmdBuf, u8 cmdLen) { hal_btcoex_RecordPwrMode(padapter, pCmdBuf, cmdLen); } void rtw_btcoex_DisplayBtCoexInfo(PADAPTER padapter, u8 *pbuf, u32 bufsize) { hal_btcoex_DisplayBtCoexInfo(padapter, pbuf, bufsize); } void rtw_btcoex_SetDBG(PADAPTER padapter, u32 *pDbgModule) { hal_btcoex_SetDBG(padapter, pDbgModule); } u32 rtw_btcoex_GetDBG(PADAPTER padapter, u8 *pStrBuf, u32 bufSize) { return hal_btcoex_GetDBG(padapter, pStrBuf, bufSize); } u8 rtw_btcoex_IncreaseScanDeviceNum(PADAPTER padapter) { return hal_btcoex_IncreaseScanDeviceNum(padapter); } u8 rtw_btcoex_IsBtLinkExist(PADAPTER padapter) { return hal_btcoex_IsBtLinkExist(padapter); } void rtw_btcoex_SetBtPatchVersion(PADAPTER padapter, u16 btHciVer, u16 btPatchVer) { hal_btcoex_SetBtPatchVersion(padapter, btHciVer, btPatchVer); } void rtw_btcoex_SetHciVersion(PADAPTER padapter, u16 hciVersion) { hal_btcoex_SetHciVersion(padapter, hciVersion); } void rtw_btcoex_StackUpdateProfileInfo(void) { hal_btcoex_StackUpdateProfileInfo(); } void rtw_btcoex_pta_off_on_notify(PADAPTER padapter, u8 bBTON) { hal_btcoex_pta_off_on_notify(padapter, bBTON); } #ifdef CONFIG_RF4CE_COEXIST void rtw_btcoex_SetRf4ceLinkState(PADAPTER padapter, u8 state) { hal_btcoex_set_rf4ce_link_state(state); } u8 rtw_btcoex_GetRf4ceLinkState(PADAPTER padapter) { return hal_btcoex_get_rf4ce_link_state(); } #endif /* ================================================== * Below Functions are called by BT-Coex * ================================================== */ void rtw_btcoex_rx_ampdu_apply(PADAPTER padapter) { rtw_rx_ampdu_apply(padapter); } void rtw_btcoex_LPS_Enter(PADAPTER padapter) { struct pwrctrl_priv *pwrpriv; u8 lpsVal; pwrpriv = adapter_to_pwrctl(padapter); pwrpriv->bpower_saving = _TRUE; lpsVal = rtw_btcoex_LpsVal(padapter); rtw_set_ps_mode(padapter, PS_MODE_MIN, 0, lpsVal, "BTCOEX"); } u8 rtw_btcoex_LPS_Leave(PADAPTER padapter) { struct pwrctrl_priv *pwrpriv; pwrpriv = adapter_to_pwrctl(padapter); if (pwrpriv->pwr_mode != PS_MODE_ACTIVE) { rtw_set_ps_mode(padapter, PS_MODE_ACTIVE, 0, 0, "BTCOEX"); pwrpriv->bpower_saving = _FALSE; } return _TRUE; } u16 rtw_btcoex_btreg_read(PADAPTER padapter, u8 type, u16 addr, u32 *data) { return hal_btcoex_btreg_read(padapter, type, addr, data); } u16 rtw_btcoex_btreg_write(PADAPTER padapter, u8 type, u16 addr, u16 val) { return hal_btcoex_btreg_write(padapter, type, addr, val); } u8 rtw_btcoex_get_bt_coexist(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); return pHalData->EEPROMBluetoothCoexist; } u8 rtw_btcoex_get_chip_type(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); return pHalData->EEPROMBluetoothType; } u8 rtw_btcoex_get_pg_ant_num(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); return pHalData->EEPROMBluetoothAntNum == Ant_x2 ? 2 : 1; } u8 rtw_btcoex_get_pg_single_ant_path(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); return pHalData->ant_path; } u8 rtw_btcoex_get_pg_rfe_type(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); return pHalData->rfe_type; } u8 rtw_btcoex_is_tfbga_package_type(PADAPTER padapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(padapter); #ifdef CONFIG_RTL8723B if ((pHalData->PackageType == PACKAGE_TFBGA79) || (pHalData->PackageType == PACKAGE_TFBGA80) || (pHalData->PackageType == PACKAGE_TFBGA90)) return _TRUE; #endif return _FALSE; } u8 rtw_btcoex_get_ant_div_cfg(PADAPTER padapter) { PHAL_DATA_TYPE pHalData; pHalData = GET_HAL_DATA(padapter); return (pHalData->AntDivCfg == 0) ? _FALSE : _TRUE; } /* ================================================== * Below Functions are BT-Coex socket related function * ================================================== */ #ifdef CONFIG_BT_COEXIST_SOCKET_TRX _adapter *pbtcoexadapter; /* = NULL; */ /* do not initialise globals to 0 or NULL */ u8 rtw_btcoex_btinfo_cmd(_adapter *adapter, u8 *buf, u16 len) { struct cmd_obj *ph2c; struct drvextra_cmd_parm *pdrvextra_cmd_parm; u8 *btinfo; struct cmd_priv *pcmdpriv = &adapter->cmdpriv; u8 res = _SUCCESS; ph2c = (struct cmd_obj *)rtw_zmalloc(sizeof(struct cmd_obj)); if (ph2c == NULL) { res = _FAIL; goto exit; } pdrvextra_cmd_parm = (struct drvextra_cmd_parm *)rtw_zmalloc(sizeof(struct drvextra_cmd_parm)); if (pdrvextra_cmd_parm == NULL) { rtw_mfree((u8 *)ph2c, sizeof(struct cmd_obj)); res = _FAIL; goto exit; } btinfo = rtw_zmalloc(len); if (btinfo == NULL) { rtw_mfree((u8 *)ph2c, sizeof(struct cmd_obj)); rtw_mfree((u8 *)pdrvextra_cmd_parm, sizeof(struct drvextra_cmd_parm)); res = _FAIL; goto exit; } pdrvextra_cmd_parm->ec_id = BTINFO_WK_CID; pdrvextra_cmd_parm->type = 0; pdrvextra_cmd_parm->size = len; pdrvextra_cmd_parm->pbuf = btinfo; _rtw_memcpy(btinfo, buf, len); init_h2fwcmd_w_parm_no_rsp(ph2c, pdrvextra_cmd_parm, GEN_CMD_CODE(_Set_Drv_Extra)); res = rtw_enqueue_cmd(pcmdpriv, ph2c); exit: return res; } u8 rtw_btcoex_send_event_to_BT(_adapter *padapter, u8 status, u8 event_code, u8 opcode_low, u8 opcode_high, u8 *dbg_msg) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = event_code; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = opcode_low; pEvent->Data[2] = opcode_high; len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, dbg_msg); #endif status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; } /* Ref: Realtek Wi-Fi Driver Host Controller Interface for Bluetooth 3.0 + HS V1.4 2013/02/07 Window team code & BT team code */ u8 rtw_btcoex_parse_BT_info_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { #define BT_INFO_LENGTH 8 u8 curPollEnable = pcmd[0]; u8 curPollTime = pcmd[1]; u8 btInfoReason = pcmd[2]; u8 btInfoLen = pcmd[3]; u8 btinfo[BT_INFO_LENGTH]; u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; rtw_HCI_event *pEvent; /* RTW_INFO("%s\n",__func__); RTW_INFO("current Poll Enable: %d, currrent Poll Time: %d\n",curPollEnable,curPollTime); RTW_INFO("BT Info reason: %d, BT Info length: %d\n",btInfoReason,btInfoLen); RTW_INFO("%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n" ,pcmd[4],pcmd[5],pcmd[6],pcmd[7],pcmd[8],pcmd[9],pcmd[10],pcmd[11]);*/ _rtw_memset(btinfo, 0, BT_INFO_LENGTH); #if 1 if (BT_INFO_LENGTH != btInfoLen) { status = HCI_STATUS_INVALID_HCI_CMD_PARA_VALUE; RTW_INFO("Error BT Info Length: %d\n", btInfoLen); /* return _FAIL; */ } else #endif { if (0x1 == btInfoReason || 0x2 == btInfoReason) { _rtw_memcpy(btinfo, &pcmd[4], btInfoLen); btinfo[0] = btInfoReason; rtw_btcoex_btinfo_cmd(padapter, btinfo, btInfoLen); } else RTW_INFO("Other BT info reason\n"); } /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_INFO_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_INFO_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, "BT_info_event"); #endif status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_BT_patch_ver_info_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; u16 btPatchVer = 0x0, btHciVer = 0x0; /* u16 *pU2tmp; */ u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; btHciVer = pcmd[0] | pcmd[1] << 8; btPatchVer = pcmd[2] | pcmd[3] << 8; RTW_INFO("%s, cmd:%02x %02x %02x %02x\n", __func__, pcmd[0] , pcmd[1] , pcmd[2] , pcmd[3]); RTW_INFO("%s, HCI Ver:%d, Patch Ver:%d\n", __func__, btHciVer, btPatchVer); rtw_btcoex_SetBtPatchVersion(padapter, btHciVer, btPatchVer); /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_PATCH_VERSION_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_PATCH_VERSION_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, "BT_patch_event"); #endif status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_Ver_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; u16 hciver = pcmd[0] | pcmd[1] << 8; u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; pBtMgnt->ExtConfig.HCIExtensionVer = hciver; RTW_INFO("%s, HCI Version: %d\n", __func__, pBtMgnt->ExtConfig.HCIExtensionVer); if (pBtMgnt->ExtConfig.HCIExtensionVer < 4) { status = HCI_STATUS_INVALID_HCI_CMD_PARA_VALUE; RTW_INFO("%s, Version = %d, HCI Version < 4\n", __func__, pBtMgnt->ExtConfig.HCIExtensionVer); } else rtw_btcoex_SetHciVersion(padapter, hciver); /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_EXTENSION_VERSION_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_EXTENSION_VERSION_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_WIFI_scan_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; pBtMgnt->ExtConfig.bEnableWifiScanNotify = pcmd[0]; RTW_INFO("%s, bEnableWifiScanNotify: %d\n", __func__, pBtMgnt->ExtConfig.bEnableWifiScanNotify); /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_ENABLE_WIFI_SCAN_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_ENABLE_WIFI_SCAN_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_link_status_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; /* PBT_DBG pBtDbg=&padapter->MgntInfo.BtInfo.BtDbg; */ u8 i, numOfHandle = 0, numOfAcl = 0; u16 conHandle; u8 btProfile, btCoreSpec, linkRole; u8 *pTriple; u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; /* pBtDbg->dbgHciInfo.hciCmdCntLinkStatusNotify++; */ /* RT_DISP_DATA(FIOCTL, IOCTL_BT_HCICMD_EXT, "LinkStatusNotify, Hex Data :\n", */ /* &pHciCmd->Data[0], pHciCmd->Length); */ RTW_INFO("BTLinkStatusNotify\n"); /* Current only RTL8723 support this command. */ /* pBtMgnt->bSupportProfile = TRUE; */ pBtMgnt->bSupportProfile = _FALSE; pBtMgnt->ExtConfig.NumberOfACL = 0; pBtMgnt->ExtConfig.NumberOfSCO = 0; numOfHandle = pcmd[0]; /* RT_DISP(FIOCTL, IOCTL_BT_HCICMD_EXT, ("numOfHandle = 0x%x\n", numOfHandle)); */ /* RT_DISP(FIOCTL, IOCTL_BT_HCICMD_EXT, ("HCIExtensionVer = %d\n", pBtMgnt->ExtConfig.HCIExtensionVer)); */ RTW_INFO("numOfHandle = 0x%x\n", numOfHandle); RTW_INFO("HCIExtensionVer = %d\n", pBtMgnt->ExtConfig.HCIExtensionVer); pTriple = &pcmd[1]; for (i = 0; i < numOfHandle; i++) { if (pBtMgnt->ExtConfig.HCIExtensionVer < 1) { conHandle = *((u8 *)&pTriple[0]); btProfile = pTriple[2]; btCoreSpec = pTriple[3]; if (BT_PROFILE_SCO == btProfile) pBtMgnt->ExtConfig.NumberOfSCO++; else { pBtMgnt->ExtConfig.NumberOfACL++; pBtMgnt->ExtConfig.aclLink[i].ConnectHandle = conHandle; pBtMgnt->ExtConfig.aclLink[i].BTProfile = btProfile; pBtMgnt->ExtConfig.aclLink[i].BTCoreSpec = btCoreSpec; } /* RT_DISP(FIOCTL, IOCTL_BT_HCICMD_EXT, */ /* ("Connection_Handle=0x%x, BTProfile=%d, BTSpec=%d\n", */ /* conHandle, btProfile, btCoreSpec)); */ RTW_INFO("Connection_Handle=0x%x, BTProfile=%d, BTSpec=%d\n", conHandle, btProfile, btCoreSpec); pTriple += 4; } else if (pBtMgnt->ExtConfig.HCIExtensionVer >= 1) { conHandle = *((pu2Byte)&pTriple[0]); btProfile = pTriple[2]; btCoreSpec = pTriple[3]; linkRole = pTriple[4]; if (BT_PROFILE_SCO == btProfile) pBtMgnt->ExtConfig.NumberOfSCO++; else { pBtMgnt->ExtConfig.NumberOfACL++; pBtMgnt->ExtConfig.aclLink[i].ConnectHandle = conHandle; pBtMgnt->ExtConfig.aclLink[i].BTProfile = btProfile; pBtMgnt->ExtConfig.aclLink[i].BTCoreSpec = btCoreSpec; pBtMgnt->ExtConfig.aclLink[i].linkRole = linkRole; } /* RT_DISP(FIOCTL, IOCTL_BT_HCICMD_EXT, */ RTW_INFO("Connection_Handle=0x%x, BTProfile=%d, BTSpec=%d, LinkRole=%d\n", conHandle, btProfile, btCoreSpec, linkRole); pTriple += 5; } } rtw_btcoex_StackUpdateProfileInfo(); /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_LINK_STATUS_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_LINK_STATUS_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_BT_coex_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_COEX_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_COEX_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_BT_operation_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; RTW_INFO("%s, OP code: %d\n", __func__, pcmd[0]); switch (pcmd[0]) { case HCI_BT_OP_NONE: RTW_INFO("[bt operation] : Operation None!!\n"); break; case HCI_BT_OP_INQUIRY_START: RTW_INFO("[bt operation] : Inquiry start!!\n"); break; case HCI_BT_OP_INQUIRY_FINISH: RTW_INFO("[bt operation] : Inquiry finished!!\n"); break; case HCI_BT_OP_PAGING_START: RTW_INFO("[bt operation] : Paging is started!!\n"); break; case HCI_BT_OP_PAGING_SUCCESS: RTW_INFO("[bt operation] : Paging complete successfully!!\n"); break; case HCI_BT_OP_PAGING_UNSUCCESS: RTW_INFO("[bt operation] : Paging complete unsuccessfully!!\n"); break; case HCI_BT_OP_PAIRING_START: RTW_INFO("[bt operation] : Pairing start!!\n"); break; case HCI_BT_OP_PAIRING_FINISH: RTW_INFO("[bt operation] : Pairing finished!!\n"); break; case HCI_BT_OP_BT_DEV_ENABLE: RTW_INFO("[bt operation] : BT Device is enabled!!\n"); break; case HCI_BT_OP_BT_DEV_DISABLE: RTW_INFO("[bt operation] : BT Device is disabled!!\n"); break; default: RTW_INFO("[bt operation] : Unknown, error!!\n"); break; } /* send complete event to BT */ { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_OPERATION_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_OPERATION_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_BT_AFH_MAP_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_AFH_MAP_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_AFH_MAP_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_BT_register_val_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_REGISTER_VALUE_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_REGISTER_VALUE_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_BT_abnormal_notify_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_BT_ABNORMAL_NOTIFY, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_BT_ABNORMAL_NOTIFY, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } u8 rtw_btcoex_parse_HCI_query_RF_status_cmd(_adapter *padapter, u8 *pcmd, u16 cmdlen) { u8 localBuf[6] = ""; u8 *pRetPar; u8 len = 0, tx_event_length = 0; rtw_HCI_event *pEvent; RTW_HCI_STATUS status = HCI_STATUS_SUCCESS; { pEvent = (rtw_HCI_event *)(&localBuf[0]); pEvent->EventCode = HCI_EVENT_COMMAND_COMPLETE; pEvent->Data[0] = 0x1; /* packet # */ pEvent->Data[1] = HCIOPCODELOW(HCI_QUERY_RF_STATUS, OGF_EXTENSION); pEvent->Data[2] = HCIOPCODEHIGHT(HCI_QUERY_RF_STATUS, OGF_EXTENSION); len = len + 3; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; pRetPar[0] = status; /* status */ len++; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; status = rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); return status; /* bthci_IndicateEvent(Adapter, PPacketIrpEvent, len+2); */ } } /***************************************** * HCI cmd format : *| 15 - 0 | *| OPcode (OCF|OGF<<10) | *| 15 - 8 |7 - 0 | *|Cmd para |Cmd para Length | *|Cmd para...... | ******************************************/ /* bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 * | OCF | OGF | */ void rtw_btcoex_parse_hci_extend_cmd(_adapter *padapter, u8 *pcmd, u16 len, const u16 hci_OCF) { RTW_INFO("%s: OCF: %x\n", __func__, hci_OCF); switch (hci_OCF) { case HCI_EXTENSION_VERSION_NOTIFY: RTW_INFO("HCI_EXTENSION_VERSION_NOTIFY\n"); rtw_btcoex_parse_HCI_Ver_notify_cmd(padapter, pcmd, len); break; case HCI_LINK_STATUS_NOTIFY: RTW_INFO("HCI_LINK_STATUS_NOTIFY\n"); rtw_btcoex_parse_HCI_link_status_notify_cmd(padapter, pcmd, len); break; case HCI_BT_OPERATION_NOTIFY: /* only for 8723a 2ant */ RTW_INFO("HCI_BT_OPERATION_NOTIFY\n"); rtw_btcoex_parse_HCI_BT_operation_notify_cmd(padapter, pcmd, len); /* */ break; case HCI_ENABLE_WIFI_SCAN_NOTIFY: RTW_INFO("HCI_ENABLE_WIFI_SCAN_NOTIFY\n"); rtw_btcoex_parse_WIFI_scan_notify_cmd(padapter, pcmd, len); break; case HCI_QUERY_RF_STATUS: /* only for 8723b 2ant */ RTW_INFO("HCI_QUERY_RF_STATUS\n"); rtw_btcoex_parse_HCI_query_RF_status_cmd(padapter, pcmd, len); break; case HCI_BT_ABNORMAL_NOTIFY: RTW_INFO("HCI_BT_ABNORMAL_NOTIFY\n"); rtw_btcoex_parse_HCI_BT_abnormal_notify_cmd(padapter, pcmd, len); break; case HCI_BT_INFO_NOTIFY: RTW_INFO("HCI_BT_INFO_NOTIFY\n"); rtw_btcoex_parse_BT_info_notify_cmd(padapter, pcmd, len); break; case HCI_BT_COEX_NOTIFY: RTW_INFO("HCI_BT_COEX_NOTIFY\n"); rtw_btcoex_parse_HCI_BT_coex_notify_cmd(padapter, pcmd, len); break; case HCI_BT_PATCH_VERSION_NOTIFY: RTW_INFO("HCI_BT_PATCH_VERSION_NOTIFY\n"); rtw_btcoex_parse_BT_patch_ver_info_cmd(padapter, pcmd, len); break; case HCI_BT_AFH_MAP_NOTIFY: RTW_INFO("HCI_BT_AFH_MAP_NOTIFY\n"); rtw_btcoex_parse_BT_AFH_MAP_notify_cmd(padapter, pcmd, len); break; case HCI_BT_REGISTER_VALUE_NOTIFY: RTW_INFO("HCI_BT_REGISTER_VALUE_NOTIFY\n"); rtw_btcoex_parse_BT_register_val_notify_cmd(padapter, pcmd, len); break; default: RTW_INFO("ERROR!!! Unknown OCF: %x\n", hci_OCF); break; } } void rtw_btcoex_parse_hci_cmd(_adapter *padapter, u8 *pcmd, u16 len) { u16 opcode = pcmd[0] | pcmd[1] << 8; u16 hci_OGF = HCI_OGF(opcode); u16 hci_OCF = HCI_OCF(opcode); u8 cmdlen = len - 3; u8 pare_len = pcmd[2]; RTW_INFO("%s OGF: %x,OCF: %x\n", __func__, hci_OGF, hci_OCF); switch (hci_OGF) { case OGF_EXTENSION: RTW_INFO("HCI_EXTENSION_CMD_OGF\n"); rtw_btcoex_parse_hci_extend_cmd(padapter, &pcmd[3], cmdlen, hci_OCF); break; default: RTW_INFO("Other OGF: %x\n", hci_OGF); break; } } u16 rtw_btcoex_parse_recv_data(u8 *msg, u8 msg_size) { u8 cmp_msg1[32] = attend_ack; u8 cmp_msg2[32] = leave_ack; u8 cmp_msg3[32] = bt_leave; u8 cmp_msg4[32] = invite_req; u8 cmp_msg5[32] = attend_req; u8 cmp_msg6[32] = invite_rsp; u8 res = OTHER; if (_rtw_memcmp(cmp_msg1, msg, msg_size) == _TRUE) { /*RTW_INFO("%s, msg:%s\n",__func__,msg);*/ res = RX_ATTEND_ACK; } else if (_rtw_memcmp(cmp_msg2, msg, msg_size) == _TRUE) { /*RTW_INFO("%s, msg:%s\n",__func__,msg);*/ res = RX_LEAVE_ACK; } else if (_rtw_memcmp(cmp_msg3, msg, msg_size) == _TRUE) { /*RTW_INFO("%s, msg:%s\n",__func__,msg);*/ res = RX_BT_LEAVE; } else if (_rtw_memcmp(cmp_msg4, msg, msg_size) == _TRUE) { /*RTW_INFO("%s, msg:%s\n",__func__,msg);*/ res = RX_INVITE_REQ; } else if (_rtw_memcmp(cmp_msg5, msg, msg_size) == _TRUE) res = RX_ATTEND_REQ; else if (_rtw_memcmp(cmp_msg6, msg, msg_size) == _TRUE) res = RX_INVITE_RSP; else { /*RTW_INFO("%s, %s\n", __func__, msg);*/ res = OTHER; } /*RTW_INFO("%s, res:%d\n", __func__, res);*/ return res; } void rtw_btcoex_recvmsgbysocket(void *data) { u8 recv_data[255]; u8 tx_msg[255] = leave_ack; u32 len = 0; u16 recv_length = 0; u16 parse_res = 0; #if 0 u8 para_len = 0, polling_enable = 0, poling_interval = 0, reason = 0, btinfo_len = 0; u8 btinfo[BT_INFO_LEN] = {0}; #endif struct bt_coex_info *pcoex_info = NULL; struct sock *sk = NULL; struct sk_buff *skb = NULL; /*RTW_INFO("%s\n",__func__);*/ if (pbtcoexadapter == NULL) { RTW_INFO("%s: btcoexadapter NULL!\n", __func__); return; } pcoex_info = &pbtcoexadapter->coex_info; sk = pcoex_info->sk_store; if (sk == NULL) { RTW_INFO("%s: critical error when receive socket data!\n", __func__); return; } len = skb_queue_len(&sk->sk_receive_queue); while (len > 0) { skb = skb_dequeue(&sk->sk_receive_queue); /*important: cut the udp header from skb->data! header length is 8 byte*/ recv_length = skb->len - 8; _rtw_memset(recv_data, 0, sizeof(recv_data)); _rtw_memcpy(recv_data, skb->data + 8, recv_length); parse_res = rtw_btcoex_parse_recv_data(recv_data, recv_length); #if 0 if (RX_ATTEND_ACK == parse_res) { /* attend ack */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_ATTEND_ACK!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); } else if (RX_ATTEND_REQ == parse_res) { /* attend req from BT */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_BT_ATTEND_REQ!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_sendmsgbysocket(pbtcoexadapter, attend_ack, sizeof(attend_ack), _FALSE); } else if (RX_INVITE_REQ == parse_res) { /* invite req from BT */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_INVITE_REQ!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_sendmsgbysocket(pbtcoexadapter, invite_rsp, sizeof(invite_rsp), _FALSE); } else if (RX_INVITE_RSP == parse_res) { /* invite rsp */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_INVITE_RSP!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); } else if (RX_LEAVE_ACK == parse_res) { /* mean BT know wifi will leave */ pcoex_info->BT_attend = _FALSE; RTW_INFO("RX_LEAVE_ACK!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); } else if (RX_BT_LEAVE == parse_res) { /* BT leave */ rtw_btcoex_sendmsgbysocket(pbtcoexadapter, leave_ack, sizeof(leave_ack), _FALSE); /* no ack */ pcoex_info->BT_attend = _FALSE; RTW_INFO("RX_BT_LEAVE!sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); } else { /* todo: check if recv data are really hci cmds */ if (_TRUE == pcoex_info->BT_attend) rtw_btcoex_parse_hci_cmd(pbtcoexadapter, recv_data, recv_length); } #endif switch (parse_res) { case RX_ATTEND_ACK: /* attend ack */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_ATTEND_ACK!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; case RX_ATTEND_REQ: pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_BT_ATTEND_REQ!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_sendmsgbysocket(pbtcoexadapter, attend_ack, sizeof(attend_ack), _FALSE); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; case RX_INVITE_REQ: /* invite req from BT */ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_INVITE_REQ!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_sendmsgbysocket(pbtcoexadapter, invite_rsp, sizeof(invite_rsp), _FALSE); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; case RX_INVITE_RSP: /*invite rsp*/ pcoex_info->BT_attend = _TRUE; RTW_INFO("RX_INVITE_RSP!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; case RX_LEAVE_ACK: /* mean BT know wifi will leave */ pcoex_info->BT_attend = _FALSE; RTW_INFO("RX_LEAVE_ACK!,sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; case RX_BT_LEAVE: /* BT leave */ rtw_btcoex_sendmsgbysocket(pbtcoexadapter, leave_ack, sizeof(leave_ack), _FALSE); /* no ack */ pcoex_info->BT_attend = _FALSE; RTW_INFO("RX_BT_LEAVE!sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, pcoex_info->BT_attend); break; default: if (_TRUE == pcoex_info->BT_attend) rtw_btcoex_parse_hci_cmd(pbtcoexadapter, recv_data, recv_length); else RTW_INFO("ERROR!! BT is UP\n"); break; } len--; kfree_skb(skb); } } #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)) void rtw_btcoex_recvmsg_init(struct sock *sk_in, s32 bytes) #else void rtw_btcoex_recvmsg_init(struct sock *sk_in) #endif { struct bt_coex_info *pcoex_info = NULL; if (pbtcoexadapter == NULL) { RTW_INFO("%s: btcoexadapter NULL\n", __func__); return; } pcoex_info = &pbtcoexadapter->coex_info; pcoex_info->sk_store = sk_in; if (pcoex_info->btcoex_wq != NULL) queue_delayed_work(pcoex_info->btcoex_wq, &pcoex_info->recvmsg_work, 0); else RTW_INFO("%s: BTCOEX workqueue NULL\n", __func__); } u8 rtw_btcoex_sendmsgbysocket(_adapter *padapter, u8 *msg, u8 msg_size, bool force) { u8 error; struct msghdr udpmsg; mm_segment_t oldfs; struct iovec iov; struct bt_coex_info *pcoex_info = &padapter->coex_info; /* RTW_INFO("%s: msg:%s, force:%s\n", __func__, msg, force == _TRUE?"TRUE":"FALSE"); */ if (_FALSE == force) { if (_FALSE == pcoex_info->BT_attend) { RTW_INFO("TX Blocked: WiFi-BT disconnected\n"); return _FAIL; } } iov.iov_base = (void *)msg; iov.iov_len = msg_size; udpmsg.msg_name = &pcoex_info->bt_sockaddr; udpmsg.msg_namelen = sizeof(struct sockaddr_in); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0)) /* referece:sock_xmit in kernel code * WRITE for sock_sendmsg, READ for sock_recvmsg * third parameter for msg_iovlen * last parameter for iov_len */ iov_iter_init(&udpmsg.msg_iter, WRITE, &iov, 1, msg_size); #else udpmsg.msg_iov = &iov; udpmsg.msg_iovlen = 1; #endif udpmsg.msg_control = NULL; udpmsg.msg_controllen = 0; udpmsg.msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL; oldfs = get_fs(); set_fs(KERNEL_DS); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 1, 0)) error = sock_sendmsg(pcoex_info->udpsock, &udpmsg); #else error = sock_sendmsg(pcoex_info->udpsock, &udpmsg, msg_size); #endif set_fs(oldfs); if (error < 0) { RTW_INFO("Error when sendimg msg, error:%d\n", error); return _FAIL; } else return _SUCCESS; } u8 rtw_btcoex_create_kernel_socket(_adapter *padapter) { s8 kernel_socket_err; u8 tx_msg[255] = attend_req; struct bt_coex_info *pcoex_info = &padapter->coex_info; s32 sock_reuse = 1; u8 status = _FAIL; RTW_INFO("%s CONNECT_PORT %d\n", __func__, CONNECT_PORT); if (NULL == pcoex_info) { RTW_INFO("coex_info: NULL\n"); status = _FAIL; } kernel_socket_err = sock_create(PF_INET, SOCK_DGRAM, 0, &pcoex_info->udpsock); if (kernel_socket_err < 0) { RTW_INFO("Error during creation of socket error:%d\n", kernel_socket_err); status = _FAIL; } else { _rtw_memset(&(pcoex_info->wifi_sockaddr), 0, sizeof(pcoex_info->wifi_sockaddr)); pcoex_info->wifi_sockaddr.sin_family = AF_INET; pcoex_info->wifi_sockaddr.sin_port = htons(CONNECT_PORT); pcoex_info->wifi_sockaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); _rtw_memset(&(pcoex_info->bt_sockaddr), 0, sizeof(pcoex_info->bt_sockaddr)); pcoex_info->bt_sockaddr.sin_family = AF_INET; pcoex_info->bt_sockaddr.sin_port = htons(CONNECT_PORT_BT); pcoex_info->bt_sockaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); pcoex_info->sk_store = NULL; kernel_socket_err = pcoex_info->udpsock->ops->bind(pcoex_info->udpsock, (struct sockaddr *)&pcoex_info->wifi_sockaddr, sizeof(pcoex_info->wifi_sockaddr)); if (kernel_socket_err == 0) { RTW_INFO("binding socket success\n"); pcoex_info->udpsock->sk->sk_data_ready = rtw_btcoex_recvmsg_init; pcoex_info->sock_open |= KERNEL_SOCKET_OK; pcoex_info->BT_attend = _FALSE; RTW_INFO("WIFI sending attend_req\n"); rtw_btcoex_sendmsgbysocket(padapter, attend_req, sizeof(attend_req), _TRUE); status = _SUCCESS; } else { pcoex_info->BT_attend = _FALSE; sock_release(pcoex_info->udpsock); /* bind fail release socket */ RTW_INFO("Error binding socket: %d\n", kernel_socket_err); status = _FAIL; } } return status; } void rtw_btcoex_close_kernel_socket(_adapter *padapter) { struct bt_coex_info *pcoex_info = &padapter->coex_info; if (pcoex_info->sock_open & KERNEL_SOCKET_OK) { RTW_INFO("release kernel socket\n"); sock_release(pcoex_info->udpsock); pcoex_info->sock_open &= ~(KERNEL_SOCKET_OK); if (_TRUE == pcoex_info->BT_attend) pcoex_info->BT_attend = _FALSE; RTW_INFO("sock_open:%d, BT_attend:%d\n", pcoex_info->sock_open, pcoex_info->BT_attend); } } void rtw_btcoex_init_socket(_adapter *padapter) { u8 is_invite = _FALSE; struct bt_coex_info *pcoex_info = &padapter->coex_info; RTW_INFO("%s\n", __func__); if (_FALSE == pcoex_info->is_exist) { _rtw_memset(pcoex_info, 0, sizeof(struct bt_coex_info)); pcoex_info->btcoex_wq = create_workqueue("BTCOEX"); INIT_DELAYED_WORK(&pcoex_info->recvmsg_work, (void *)rtw_btcoex_recvmsgbysocket); pbtcoexadapter = padapter; /* We expect BT is off if BT don't send ack to wifi */ RTW_INFO("We expect BT is off if BT send ack to wifi\n"); rtw_btcoex_pta_off_on_notify(pbtcoexadapter, _FALSE); if (rtw_btcoex_create_kernel_socket(padapter) == _SUCCESS) pcoex_info->is_exist = _TRUE; else { pcoex_info->is_exist = _FALSE; pbtcoexadapter = NULL; } RTW_INFO("%s: pbtcoexadapter:%p, coex_info->is_exist: %s\n" , __func__, pbtcoexadapter, pcoex_info->is_exist == _TRUE ? "TRUE" : "FALSE"); } } void rtw_btcoex_close_socket(_adapter *padapter) { struct bt_coex_info *pcoex_info = &padapter->coex_info; RTW_INFO("%s--coex_info->is_exist: %s, pcoex_info->BT_attend:%s\n" , __func__, pcoex_info->is_exist == _TRUE ? "TRUE" : "FALSE", pcoex_info->BT_attend == _TRUE ? "TRUE" : "FALSE"); if (_TRUE == pcoex_info->is_exist) { if (_TRUE == pcoex_info->BT_attend) { /*inform BT wifi leave*/ rtw_btcoex_sendmsgbysocket(padapter, wifi_leave, sizeof(wifi_leave), _FALSE); msleep(50); } if (pcoex_info->btcoex_wq != NULL) { flush_workqueue(pcoex_info->btcoex_wq); destroy_workqueue(pcoex_info->btcoex_wq); } rtw_btcoex_close_kernel_socket(padapter); pbtcoexadapter = NULL; pcoex_info->is_exist = _FALSE; } } void rtw_btcoex_dump_tx_msg(u8 *tx_msg, u8 len, u8 *msg_name) { u8 i = 0; RTW_INFO("======> Msg name: %s\n", msg_name); for (i = 0; i < len; i++) printk("%02x ", tx_msg[i]); printk("\n"); RTW_INFO("Msg name: %s <======\n", msg_name); } /* Porting from Windows team */ void rtw_btcoex_SendEventExtBtCoexControl(PADAPTER padapter, u8 bNeedDbgRsp, u8 dataLen, void *pData) { u8 len = 0, tx_event_length = 0; u8 localBuf[32] = ""; u8 *pRetPar; u8 opCode = 0; u8 *pInBuf = (pu1Byte)pData; u8 *pOpCodeContent; rtw_HCI_event *pEvent; opCode = pInBuf[0]; RTW_INFO("%s, OPCode:%02x\n", __func__, opCode); pEvent = (rtw_HCI_event *)(&localBuf[0]); /* len += bthci_ExtensionEventHeaderRtk(&localBuf[0], */ /* HCI_EVENT_EXT_BT_COEX_CONTROL); */ pEvent->EventCode = HCI_EVENT_EXTENSION_RTK; pEvent->Data[0] = HCI_EVENT_EXT_BT_COEX_CONTROL; /* extension event code */ len++; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; _rtw_memcpy(&pRetPar[0], pData, dataLen); len += dataLen; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, "BT COEX CONTROL", _FALSE); #endif rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); } /* Porting from Windows team */ void rtw_btcoex_SendEventExtBtInfoControl(PADAPTER padapter, u8 dataLen, void *pData) { rtw_HCI_event *pEvent; u8 *pRetPar; u8 len = 0, tx_event_length = 0; u8 localBuf[32] = ""; struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; /* RTW_INFO("%s\n",__func__);*/ if (pBtMgnt->ExtConfig.HCIExtensionVer < 4) { /* not support */ RTW_INFO("ERROR: HCIExtensionVer = %d, HCIExtensionVer<4 !!!!\n", pBtMgnt->ExtConfig.HCIExtensionVer); return; } pEvent = (rtw_HCI_event *)(&localBuf[0]); /* len += bthci_ExtensionEventHeaderRtk(&localBuf[0], */ /* HCI_EVENT_EXT_BT_INFO_CONTROL); */ pEvent->EventCode = HCI_EVENT_EXTENSION_RTK; pEvent->Data[0] = HCI_EVENT_EXT_BT_INFO_CONTROL; /* extension event code */ len++; /* Return parameters starts from here */ pRetPar = &pEvent->Data[len]; _rtw_memcpy(&pRetPar[0], pData, dataLen); len += dataLen; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, "BT INFO CONTROL"); #endif rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); } void rtw_btcoex_SendScanNotify(PADAPTER padapter, u8 scanType) { u8 len = 0, tx_event_length = 0; u8 localBuf[7] = ""; u8 *pRetPar; u8 *pu1Temp; rtw_HCI_event *pEvent; struct bt_coex_info *pcoex_info = &padapter->coex_info; PBT_MGNT pBtMgnt = &pcoex_info->BtMgnt; /* if(!pBtMgnt->BtOperationOn) * return; */ pEvent = (rtw_HCI_event *)(&localBuf[0]); /* len += bthci_ExtensionEventHeaderRtk(&localBuf[0], * HCI_EVENT_EXT_WIFI_SCAN_NOTIFY); */ pEvent->EventCode = HCI_EVENT_EXTENSION_RTK; pEvent->Data[0] = HCI_EVENT_EXT_WIFI_SCAN_NOTIFY; /* extension event code */ len++; /* Return parameters starts from here */ /* pRetPar = &PPacketIrpEvent->Data[len]; */ /* pu1Temp = (u8 *)&pRetPar[0]; */ /* *pu1Temp = scanType; */ pEvent->Data[len] = scanType; len += 1; pEvent->Length = len; /* total tx event length + EventCode length + sizeof(length) */ tx_event_length = pEvent->Length + 2; #if 0 rtw_btcoex_dump_tx_msg((u8 *)pEvent, tx_event_length, "WIFI SCAN OPERATION"); #endif rtw_btcoex_sendmsgbysocket(padapter, (u8 *)pEvent, tx_event_length, _FALSE); } #endif /* CONFIG_BT_COEXIST_SOCKET_TRX */ #endif /* CONFIG_BT_COEXIST */ void rtw_btcoex_set_ant_info(PADAPTER padapter) { #ifdef CONFIG_BT_COEXIST PHAL_DATA_TYPE hal = GET_HAL_DATA(padapter); if (hal->EEPROMBluetoothCoexist == _TRUE) { u8 bMacPwrCtrlOn = _FALSE; rtw_btcoex_AntInfoSetting(padapter); rtw_hal_get_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn); if (bMacPwrCtrlOn == _TRUE) rtw_btcoex_PowerOnSetting(padapter); } else #endif rtw_btcoex_wifionly_AntInfoSetting(padapter); }
{ "pile_set_name": "Github" }
// Code generated by gocc; DO NOT EDIT. package errors import ( "fmt" "strings" "github.com/awalterschulze/gographviz/internal/token" ) type ErrorSymbol interface { } type Error struct { Err error ErrorToken *token.Token ErrorSymbols []ErrorSymbol ExpectedTokens []string StackTop int } func (e *Error) String() string { w := new(strings.Builder) fmt.Fprintf(w, "Error") if e.Err != nil { fmt.Fprintf(w, " %s\n", e.Err) } else { fmt.Fprintf(w, "\n") } fmt.Fprintf(w, "Token: type=%d, lit=%s\n", e.ErrorToken.Type, e.ErrorToken.Lit) fmt.Fprintf(w, "Pos: offset=%d, line=%d, column=%d\n", e.ErrorToken.Pos.Offset, e.ErrorToken.Pos.Line, e.ErrorToken.Pos.Column) fmt.Fprintf(w, "Expected one of: ") for _, sym := range e.ExpectedTokens { fmt.Fprintf(w, "%s ", sym) } fmt.Fprintf(w, "ErrorSymbol:\n") for _, sym := range e.ErrorSymbols { fmt.Fprintf(w, "%v\n", sym) } return w.String() } func (e *Error) Error() string { w := new(strings.Builder) fmt.Fprintf(w, "Error in S%d: %s, %s", e.StackTop, token.TokMap.TokenString(e.ErrorToken), e.ErrorToken.Pos.String()) if e.Err != nil { fmt.Fprintf(w, ": %+v", e.Err) } else { fmt.Fprintf(w, ", expected one of: ") for _, expected := range e.ExpectedTokens { fmt.Fprintf(w, "%s ", expected) } } return w.String() }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2011 Talend Inc. - www.talend.com --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <!-- Restaurant Reservations Application --> <!-- WebClient which Restaurant Reservations uses to access Social.com users' calendars at Social.com. Note that the Social.com address provided to this service is different from the one used by Social.com users themselves, which is "http://localhost:${http.port}/services/social/calendar". Social.com is OAuth-protected at "http://localhost:${http.port}/services/thirdPartyAccess/calendar" while "http://localhost:${http.port}/services/social/calendar" is protected by a Basic Authentication filter. --> <bean id="socialServiceClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create"> <constructor-arg type="java.lang.String" value="http://localhost:${http.port}/examples/thirdPartyAccess/calendar"/> </bean> <!-- WebClient for requesting a temporarily Access OAuth token, it is used after the authorization service (in socialApp context) redirects the user back to the callback URI. Once the access token is obtained, the service uses it to access the user's calendar --> <bean id="atServiceClientFactory" class="org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean"> <property name="address" value="http://localhost:${http.port}/examples/oauth/token"/> <property name="headers"> <map> <entry key="Accept" value="application/json"/> </map> </property> </bean> <bean id="atServiceClient" factory-bean="atServiceClientFactory" factory-method="createWebClient"/> <!-- WebClient for talking to a partner Restaurant application, it is used after a user calendar's has been checked --> <bean id="restaurantServiceClientFactory" class="org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean"> <property name="address" value="http://localhost:${http.port}/examples/restaurant/reception"/> <property name="headers"> <map> <entry key="Content-Type" value="application/x-www-form-urlencoded"/> <entry key="Accept" value="text/plain"/> </map> </property> </bean> <bean id="restaurantServiceClient" factory-bean="restaurantServiceClientFactory" factory-method="createWebClient"/> <!-- Utility OAuthClientManager which encapsulates the interaction with the OAuth Server --> <bean id="oauthClient" class="oauth2.thirdparty.OAuthClientManager"> <property name="authorizationURI" value="http://localhost:${http.port}/examples/social/authorize"/> <property name="accessTokenService" ref="atServiceClient"/> </bean> <!-- Restaurant Reservations Service Bean --> <bean id="restaurantReserveService" class="oauth2.thirdparty.RestaurantReservationService"> <property name="oAuthClientManager" ref="oauthClient"/> <property name="socialService" ref="socialServiceClient"/> <property name="restaurantService" ref="restaurantServiceClient"/> </bean> <!-- The security filter for Restaurant Reservations --> <!-- It's a primitive implementation which only recognizes a single user, to be improved... --> <bean id="thirdPartySecurityContext" class="oauth2.thirdparty.SecurityContextFilter"> <property name="users"> <map> <entry key="barry@restaurant.com" value="5678"/> </map> </property> <property name="realm" value="Reservations"/> </bean> <!-- The Restaurant Reservations View Support Responses to requests with URIs ending with /reservations/reserve/complete and /reservations/reserve/failure will be redirected to "/forms/reservationConfirm.jsp" and "/forms/reservationFailure.jsp" respectively. In both cases the response beans (oauth.common.ReservationConfirmation and oauth.common.ReservationFailure) will be available to view handlers as HttpServletRequest "data" attribute. Note that restaurantReserveService will use JAX-RS Response.seeOther() call to redirect a user to a failure handler if a /complete reservation requests fails for whatever reasons (no authorization key is available after the authorization service redirects the user back to it, no access token can be obtained, etc) --> <bean id="reserveRegistrationViews" class="org.apache.cxf.jaxrs.provider.RequestDispatcherProvider"> <property name="resourcePaths"> <map> <entry key="/reservations/reserve/complete" value="/forms/reservationConfirm.jsp"/> <entry key="/reservations/reserve/failure" value="/forms/reservationFailure.jsp"/> </map> </property> <property name="beanName" value="data"/> <!-- <property name="logRedirects" value="true"/> --> </bean> <!-- Restaurant Reservations Service Endpoint --> <jaxrs:server id="reservationsServer" address="/reservations"> <jaxrs:serviceBeans> <ref bean="restaurantReserveService"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="thirdPartySecurityContext"/> <ref bean="reserveRegistrationViews"/> </jaxrs:providers> </jaxrs:server> </beans>
{ "pile_set_name": "Github" }
<defines> ENTROPY_SRC_RDSEED -> 20151218 </defines> <isa> rdseed sse2 # for mm_pause see #2139 </isa> <header:internal> rdseed.h </header:internal> <cc> gcc clang icc msvc </cc>
{ "pile_set_name": "Github" }
{# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. -#} {% extends "privacy/base-protocol.html" %} {% block string_data %} data-details-open-text="{{ ftl('ui-learn-more') }}" data-details-close-text="{{ ftl('ui-show-less') }}" {% endblock %} {% do doc.select('body > section > section > p')|htmlattr(class='summary') %} {% do doc.select('body > section > section ul')|htmlattr(class="mzp-u-list-styled") %} {% do doc.select('body > section > section ol')|htmlattr(class="mzp-u-list-styled") %} {% block page_title %}{{ doc.h1.string|join|safe }}{% endblock %} {% block body_id %}firefox-notice{% endblock %} {% block body_class %}{{ super() }} format-paragraphs{% endblock %} {% block title %}{{ doc.h1.string|join|safe }}{% endblock%} {% block time %} {% if doc.select('[datetime]') %} <time datetime="{{ doc.select('[datetime]')[0]['datetime'] }}" itemprop="dateModified">{{ doc.select('[datetime]')[0].string }}</time> {% endif %} {% endblock %} {% block lead_in %} {% if doc.select('[datetime]') %} {{ doc.select('body > section > [datetime] ~ p')|join|safe }} {% else %} {{ doc.select('body > section > p')|join|safe }} {% endif %} {% endblock %} {% block sections %} {{ doc.select('body > section > section:nth-of-type(1)')|join|safe }} {{ doc.select('body > section > section:nth-of-type(1) ~ *')|join|safe }} {% endblock %} {% block js %} {{ js_bundle('privacy_protocol') }} {% endblock %}
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * sst_ipc.c - Intel SST Driver for audio engine * * Copyright (C) 2008-14 Intel Corporation * Authors: Vinod Koul <vinod.koul@intel.com> * Harsha Priya <priya.harsha@intel.com> * Dharageswari R <dharageswari.r@intel.com> * KP Jeeja <jeeja.kp@intel.com> * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include <linux/pci.h> #include <linux/firmware.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/compress_driver.h> #include <asm/intel-mid.h> #include <asm/platform_sst_audio.h> #include "../sst-mfld-platform.h" #include "sst.h" #include "../../common/sst-dsp.h" struct sst_block *sst_create_block(struct intel_sst_drv *ctx, u32 msg_id, u32 drv_id) { struct sst_block *msg = NULL; dev_dbg(ctx->dev, "Enter\n"); msg = kzalloc(sizeof(*msg), GFP_KERNEL); if (!msg) return NULL; msg->condition = false; msg->on = true; msg->msg_id = msg_id; msg->drv_id = drv_id; spin_lock_bh(&ctx->block_lock); list_add_tail(&msg->node, &ctx->block_list); spin_unlock_bh(&ctx->block_lock); return msg; } /* * while handling the interrupts, we need to check for message status and * then if we are blocking for a message * * here we are unblocking the blocked ones, this is based on id we have * passed and search that for block threads. * We will not find block in two cases * a) when its small message and block in not there, so silently ignore * them * b) when we are actually not able to find the block (bug perhaps) * * Since we have bit of small messages we can spam kernel log with err * print on above so need to keep as debug prints which should be enabled * via dynamic debug while debugging IPC issues */ int sst_wake_up_block(struct intel_sst_drv *ctx, int result, u32 drv_id, u32 ipc, void *data, u32 size) { struct sst_block *block = NULL; dev_dbg(ctx->dev, "Enter\n"); spin_lock_bh(&ctx->block_lock); list_for_each_entry(block, &ctx->block_list, node) { dev_dbg(ctx->dev, "Block ipc %d, drv_id %d\n", block->msg_id, block->drv_id); if (block->msg_id == ipc && block->drv_id == drv_id) { dev_dbg(ctx->dev, "free up the block\n"); block->ret_code = result; block->data = data; block->size = size; block->condition = true; spin_unlock_bh(&ctx->block_lock); wake_up(&ctx->wait_queue); return 0; } } spin_unlock_bh(&ctx->block_lock); dev_dbg(ctx->dev, "Block not found or a response received for a short msg for ipc %d, drv_id %d\n", ipc, drv_id); return -EINVAL; } int sst_free_block(struct intel_sst_drv *ctx, struct sst_block *freed) { struct sst_block *block = NULL, *__block; dev_dbg(ctx->dev, "Enter\n"); spin_lock_bh(&ctx->block_lock); list_for_each_entry_safe(block, __block, &ctx->block_list, node) { if (block == freed) { pr_debug("pvt_id freed --> %d\n", freed->drv_id); /* toggle the index position of pvt_id */ list_del(&freed->node); spin_unlock_bh(&ctx->block_lock); kfree(freed->data); freed->data = NULL; kfree(freed); return 0; } } spin_unlock_bh(&ctx->block_lock); dev_err(ctx->dev, "block is already freed!!!\n"); return -EINVAL; } int sst_post_message_mrfld(struct intel_sst_drv *sst_drv_ctx, struct ipc_post *ipc_msg, bool sync) { struct ipc_post *msg = ipc_msg; union ipc_header_mrfld header; unsigned int loop_count = 0; int retval = 0; unsigned long irq_flags; dev_dbg(sst_drv_ctx->dev, "Enter: sync: %d\n", sync); spin_lock_irqsave(&sst_drv_ctx->ipc_spin_lock, irq_flags); header.full = sst_shim_read64(sst_drv_ctx->shim, SST_IPCX); if (sync) { while (header.p.header_high.part.busy) { if (loop_count > 25) { dev_err(sst_drv_ctx->dev, "sst: Busy wait failed, cant send this msg\n"); retval = -EBUSY; goto out; } cpu_relax(); loop_count++; header.full = sst_shim_read64(sst_drv_ctx->shim, SST_IPCX); } } else { if (list_empty(&sst_drv_ctx->ipc_dispatch_list)) { /* queue is empty, nothing to send */ spin_unlock_irqrestore(&sst_drv_ctx->ipc_spin_lock, irq_flags); dev_dbg(sst_drv_ctx->dev, "Empty msg queue... NO Action\n"); return 0; } if (header.p.header_high.part.busy) { spin_unlock_irqrestore(&sst_drv_ctx->ipc_spin_lock, irq_flags); dev_dbg(sst_drv_ctx->dev, "Busy not free... post later\n"); return 0; } /* copy msg from list */ msg = list_entry(sst_drv_ctx->ipc_dispatch_list.next, struct ipc_post, node); list_del(&msg->node); } dev_dbg(sst_drv_ctx->dev, "sst: Post message: header = %x\n", msg->mrfld_header.p.header_high.full); dev_dbg(sst_drv_ctx->dev, "sst: size = 0x%x\n", msg->mrfld_header.p.header_low_payload); if (msg->mrfld_header.p.header_high.part.large) memcpy_toio(sst_drv_ctx->mailbox + SST_MAILBOX_SEND, msg->mailbox_data, msg->mrfld_header.p.header_low_payload); sst_shim_write64(sst_drv_ctx->shim, SST_IPCX, msg->mrfld_header.full); out: spin_unlock_irqrestore(&sst_drv_ctx->ipc_spin_lock, irq_flags); kfree(msg->mailbox_data); kfree(msg); return retval; } void intel_sst_clear_intr_mrfld(struct intel_sst_drv *sst_drv_ctx) { union interrupt_reg_mrfld isr; union interrupt_reg_mrfld imr; union ipc_header_mrfld clear_ipc; unsigned long irq_flags; spin_lock_irqsave(&sst_drv_ctx->ipc_spin_lock, irq_flags); imr.full = sst_shim_read64(sst_drv_ctx->shim, SST_IMRX); isr.full = sst_shim_read64(sst_drv_ctx->shim, SST_ISRX); /* write 1 to clear*/ isr.part.busy_interrupt = 1; sst_shim_write64(sst_drv_ctx->shim, SST_ISRX, isr.full); /* Set IA done bit */ clear_ipc.full = sst_shim_read64(sst_drv_ctx->shim, SST_IPCD); clear_ipc.p.header_high.part.busy = 0; clear_ipc.p.header_high.part.done = 1; clear_ipc.p.header_low_payload = IPC_ACK_SUCCESS; sst_shim_write64(sst_drv_ctx->shim, SST_IPCD, clear_ipc.full); /* un mask busy interrupt */ imr.part.busy_interrupt = 0; sst_shim_write64(sst_drv_ctx->shim, SST_IMRX, imr.full); spin_unlock_irqrestore(&sst_drv_ctx->ipc_spin_lock, irq_flags); } /* * process_fw_init - process the FW init msg * * @msg: IPC message mailbox data from FW * * This function processes the FW init msg from FW * marks FW state and prints debug info of loaded FW */ static void process_fw_init(struct intel_sst_drv *sst_drv_ctx, void *msg) { struct ipc_header_fw_init *init = (struct ipc_header_fw_init *)msg; int retval = 0; dev_dbg(sst_drv_ctx->dev, "*** FW Init msg came***\n"); if (init->result) { sst_set_fw_state_locked(sst_drv_ctx, SST_RESET); dev_err(sst_drv_ctx->dev, "FW Init failed, Error %x\n", init->result); retval = init->result; goto ret; } if (memcmp(&sst_drv_ctx->fw_version, &init->fw_version, sizeof(init->fw_version))) dev_info(sst_drv_ctx->dev, "FW Version %02x.%02x.%02x.%02x\n", init->fw_version.type, init->fw_version.major, init->fw_version.minor, init->fw_version.build); dev_dbg(sst_drv_ctx->dev, "Build date %s Time %s\n", init->build_info.date, init->build_info.time); /* Save FW version */ sst_drv_ctx->fw_version.type = init->fw_version.type; sst_drv_ctx->fw_version.major = init->fw_version.major; sst_drv_ctx->fw_version.minor = init->fw_version.minor; sst_drv_ctx->fw_version.build = init->fw_version.build; ret: sst_wake_up_block(sst_drv_ctx, retval, FW_DWNL_ID, 0 , NULL, 0); } static void process_fw_async_msg(struct intel_sst_drv *sst_drv_ctx, struct ipc_post *msg) { u32 msg_id; int str_id; u32 data_size, i; void *data_offset; struct stream_info *stream; u32 msg_low, pipe_id; msg_low = msg->mrfld_header.p.header_low_payload; msg_id = ((struct ipc_dsp_hdr *)msg->mailbox_data)->cmd_id; data_offset = (msg->mailbox_data + sizeof(struct ipc_dsp_hdr)); data_size = msg_low - (sizeof(struct ipc_dsp_hdr)); switch (msg_id) { case IPC_SST_PERIOD_ELAPSED_MRFLD: pipe_id = ((struct ipc_dsp_hdr *)msg->mailbox_data)->pipe_id; str_id = get_stream_id_mrfld(sst_drv_ctx, pipe_id); if (str_id > 0) { dev_dbg(sst_drv_ctx->dev, "Period elapsed rcvd for pipe id 0x%x\n", pipe_id); stream = &sst_drv_ctx->streams[str_id]; /* If stream is dropped, skip processing this message*/ if (stream->status == STREAM_INIT) break; if (stream->period_elapsed) stream->period_elapsed(stream->pcm_substream); if (stream->compr_cb) stream->compr_cb(stream->compr_cb_param); } break; case IPC_IA_DRAIN_STREAM_MRFLD: pipe_id = ((struct ipc_dsp_hdr *)msg->mailbox_data)->pipe_id; str_id = get_stream_id_mrfld(sst_drv_ctx, pipe_id); if (str_id > 0) { stream = &sst_drv_ctx->streams[str_id]; if (stream->drain_notify) stream->drain_notify(stream->drain_cb_param); } break; case IPC_IA_FW_ASYNC_ERR_MRFLD: dev_err(sst_drv_ctx->dev, "FW sent async error msg:\n"); for (i = 0; i < (data_size/4); i++) print_hex_dump(KERN_DEBUG, NULL, DUMP_PREFIX_NONE, 16, 4, data_offset, data_size, false); break; case IPC_IA_FW_INIT_CMPLT_MRFLD: process_fw_init(sst_drv_ctx, data_offset); break; case IPC_IA_BUF_UNDER_RUN_MRFLD: pipe_id = ((struct ipc_dsp_hdr *)msg->mailbox_data)->pipe_id; str_id = get_stream_id_mrfld(sst_drv_ctx, pipe_id); if (str_id > 0) dev_err(sst_drv_ctx->dev, "Buffer under-run for pipe:%#x str_id:%d\n", pipe_id, str_id); break; default: dev_err(sst_drv_ctx->dev, "Unrecognized async msg from FW msg_id %#x\n", msg_id); } } void sst_process_reply_mrfld(struct intel_sst_drv *sst_drv_ctx, struct ipc_post *msg) { unsigned int drv_id; void *data; union ipc_header_high msg_high; u32 msg_low; struct ipc_dsp_hdr *dsp_hdr; msg_high = msg->mrfld_header.p.header_high; msg_low = msg->mrfld_header.p.header_low_payload; dev_dbg(sst_drv_ctx->dev, "IPC process message header %x payload %x\n", msg->mrfld_header.p.header_high.full, msg->mrfld_header.p.header_low_payload); drv_id = msg_high.part.drv_id; /* Check for async messages first */ if (drv_id == SST_ASYNC_DRV_ID) { /*FW sent async large message*/ process_fw_async_msg(sst_drv_ctx, msg); return; } /* FW sent short error response for an IPC */ if (msg_high.part.result && drv_id && !msg_high.part.large) { /* 32-bit FW error code in msg_low */ dev_err(sst_drv_ctx->dev, "FW sent error response 0x%x", msg_low); sst_wake_up_block(sst_drv_ctx, msg_high.part.result, msg_high.part.drv_id, msg_high.part.msg_id, NULL, 0); return; } /* * Process all valid responses * if it is a large message, the payload contains the size to * copy from mailbox **/ if (msg_high.part.large) { data = kmemdup((void *)msg->mailbox_data, msg_low, GFP_KERNEL); if (!data) return; /* Copy command id so that we can use to put sst to reset */ dsp_hdr = (struct ipc_dsp_hdr *)data; dev_dbg(sst_drv_ctx->dev, "cmd_id %d\n", dsp_hdr->cmd_id); if (sst_wake_up_block(sst_drv_ctx, msg_high.part.result, msg_high.part.drv_id, msg_high.part.msg_id, data, msg_low)) kfree(data); } else { sst_wake_up_block(sst_drv_ctx, msg_high.part.result, msg_high.part.drv_id, msg_high.part.msg_id, NULL, 0); } }
{ "pile_set_name": "Github" }
// Copyright (c) Alex Ellis 2017. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package metrics import ( "net/http" "sync" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) // MetricOptions to be used by web handlers type MetricOptions struct { GatewayFunctionInvocation *prometheus.CounterVec GatewayFunctionsHistogram *prometheus.HistogramVec GatewayFunctionInvocationStarted *prometheus.CounterVec ServiceReplicasGauge *prometheus.GaugeVec ServiceMetrics *ServiceMetricOptions } // ServiceMetricOptions provides RED metrics type ServiceMetricOptions struct { Histogram *prometheus.HistogramVec Counter *prometheus.CounterVec } // Synchronize to make sure MustRegister only called once var once = sync.Once{} // RegisterExporter registers with Prometheus for tracking func RegisterExporter(exporter *Exporter) { once.Do(func() { prometheus.MustRegister(exporter) }) } // PrometheusHandler Bootstraps prometheus for metrics collection func PrometheusHandler() http.Handler { return promhttp.Handler() } // BuildMetricsOptions builds metrics for tracking functions in the API gateway func BuildMetricsOptions() MetricOptions { gatewayFunctionsHistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "gateway_functions_seconds", Help: "Function time taken", }, []string{"function_name"}) gatewayFunctionInvocation := prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "gateway", Subsystem: "function", Name: "invocation_total", Help: "Function metrics", }, []string{"function_name", "code"}, ) serviceReplicas := prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: "gateway", Name: "service_count", Help: "Service replicas", }, []string{"function_name"}, ) // For automatic monitoring and alerting (RED method) histogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{ Subsystem: "http", Name: "request_duration_seconds", Help: "Seconds spent serving HTTP requests.", Buckets: prometheus.DefBuckets, }, []string{"method", "path", "status"}) // Can be used Kubernetes HPA v2 counter := prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: "http", Name: "requests_total", Help: "The total number of HTTP requests.", }, []string{"method", "path", "status"}, ) gatewayFunctionInvocationStarted := prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "gateway", Subsystem: "function", Name: "invocation_started", Help: "The total number of function HTTP requests started.", }, []string{"function_name"}, ) serviceMetricOptions := &ServiceMetricOptions{ Counter: counter, Histogram: histogram, } metricsOptions := MetricOptions{ GatewayFunctionsHistogram: gatewayFunctionsHistogram, GatewayFunctionInvocation: gatewayFunctionInvocation, ServiceReplicasGauge: serviceReplicas, ServiceMetrics: serviceMetricOptions, GatewayFunctionInvocationStarted: gatewayFunctionInvocationStarted, } return metricsOptions }
{ "pile_set_name": "Github" }
<?php /** * Copyright Enalean (c) 2013. All rights reserved. * * Tuleap and Enalean names and logos are registrated trademarks owned by * Enalean SAS. All other trademarks or names are properties of their respective * owners. * * This file is a part of Tuleap. * * Tuleap is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Tuleap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tuleap. If not, see <http://www.gnu.org/licenses/>. */ /** * Analyze a push a provide a high level object (PushDetails) that knows if push * is a branch creation or a tag deletion, etc. */ class Git_Hook_LogAnalyzer { public const FAKE_EMPTY_COMMIT = '0000000000000000000000000000000000000000'; /** @var Git_Exec */ private $exec_repo; /** @var \Psr\Log\LoggerInterface */ private $logger; public function __construct(Git_Exec $git_exec, \Psr\Log\LoggerInterface $logger) { $this->exec_repo = $git_exec; $this->logger = $logger; } /** * * Behaviour extracted from official email hook prep_for_email() function * * @param type $oldrev * @param type $newrev * @param type $refname * @return Git_Hook_PushDetails */ public function getPushDetails(GitRepository $repository, PFUser $user, $oldrev, $newrev, $refname) { $change_type = Git_Hook_PushDetails::ACTION_ERROR; $revision_list = []; $rev_type = ''; try { if ($oldrev == self::FAKE_EMPTY_COMMIT) { $revision_list = $this->exec_repo->revListSinceStart($refname, $newrev); $change_type = Git_Hook_PushDetails::ACTION_CREATE; } elseif ($newrev == self::FAKE_EMPTY_COMMIT) { $change_type = Git_Hook_PushDetails::ACTION_DELETE; } else { $revision_list = $this->exec_repo->revList($oldrev, $newrev); $change_type = Git_Hook_PushDetails::ACTION_UPDATE; } if ($change_type == Git_Hook_PushDetails::ACTION_DELETE) { $rev_type = $this->exec_repo->getObjectType($oldrev); } else { $rev_type = $this->exec_repo->getObjectType($newrev); } } catch (Git_Command_Exception $exception) { $this->logger->error(self::class . " {$repository->getFullName()} $refname $oldrev $newrev " . $exception->getMessage()); } return new Git_Hook_PushDetails( $repository, $user, $refname, $change_type, $rev_type, $revision_list ); } }
{ "pile_set_name": "Github" }
vcodec=libvpx g=120 lag-in-frames=25 deadline=good cpu-used=0 vprofile=1 qmax=51 qmin=11 slices=4 b=2M #ignored unless using -pass 2 maxrate=24M minrate=100k auto-alt-ref=1 arnr-maxframes=7 arnr-strength=5 arnr-type=centered
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <extension version="3.1" type="plugin" group="finder" method="upgrade"> <name>plg_finder_categories</name> <author>Joomla! Project</author> <creationDate>August 2011</creationDate> <copyright>(C) 2005 - 2015 Open Source Matters. All rights reserved.</copyright> <license>GNU General Public License version 2 or later; see LICENSE.txt</license> <authorEmail>admin@joomla.org</authorEmail> <authorUrl>www.joomla.org</authorUrl> <version>3.0.0</version> <description>PLG_FINDER_CATEGORIES_XML_DESCRIPTION</description> <files> <filename plugin="categories">categories.php</filename> </files> <languages> <language tag="en-GB">language/en-GB/en-GB.plg_finder_categories.ini</language> <language tag="en-GB">language/en-GB/en-GB.plg_finder_categories.sys.ini</language> </languages> </extension>
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 15.3. Analyzing real-valued functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sympy import *\n", "init_printing()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "var('x z')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We define a new function depending on x." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f = 1/(1+x**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's evaluate this function in 1." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f.subs(x, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can compute the derivative of this function..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "diff(f, x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "limits..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "limit(f, x, oo)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Taylor series..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "series(f, x0=0, n=9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Definite integrals..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "integrate(f, (x, -oo, oo))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "indefinite integrals..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "integrate(f, x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and even Fourier transforms!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fourier_transform(f, x, z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).\n", "\n", "> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.2" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "pile_set_name": "Github" }
package info.nightscout.android.medtronic.message; import java.io.IOException; import java.util.concurrent.TimeoutException; import info.nightscout.android.USB.UsbHidDriver; import info.nightscout.android.medtronic.MedtronicCnlSession; import info.nightscout.android.medtronic.exception.ChecksumException; import info.nightscout.android.medtronic.exception.EncryptionException; import info.nightscout.android.medtronic.exception.UnexpectedMessageException; /** * Created by Pogman on 8.11.17. */ public class BolusWizardTargetsRequestMessage extends MedtronicSendMessageRequestMessage<BolusWizardTargetsResponseMessage> { private static final String TAG = BolusWizardTargetsRequestMessage.class.getSimpleName(); public BolusWizardTargetsRequestMessage(MedtronicCnlSession pumpSession) throws EncryptionException, ChecksumException { super(MessageType.READ_BOLUS_WIZARD_BG_TARGETS, pumpSession, null); } public BolusWizardTargetsResponseMessage send(UsbHidDriver mDevice, int millis) throws IOException, TimeoutException, ChecksumException, EncryptionException, UnexpectedMessageException { sendToPump(mDevice, TAG); return getResponse(readFromPump(mDevice, mPumpSession, TAG)); } @Override protected BolusWizardTargetsResponseMessage getResponse(byte[] payload) throws ChecksumException, EncryptionException, IOException, UnexpectedMessageException { return new BolusWizardTargetsResponseMessage(mPumpSession, payload); } }
{ "pile_set_name": "Github" }
# # Author: Hari Sekhon # Date: Tue Feb 4 09:53:28 2020 +0000 # # vim:ts=2:sts=2:sw=2:et # # https://github.com/harisekhon/nagios-plugins # # If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback # # https://www.linkedin.com/in/harisekhon # name: CI Debian 7 #env: # DEBUG: 1 on: # [push] push: branches: - master schedule: # * is a special character in YAML so you have to quote this string - cron: '0 7 * * *' jobs: build: #name: build timeout-minutes: 180 runs-on: ubuntu-latest container: debian:7-slim env: repo: nagios-plugins steps: # untars repo in docker container so git submodule update fails #- uses: actions/checkout@v2 - name: install git & make run: | ls -l /.dockerenv echo "pwd is $PWD" cat /etc/*release apt-get update && apt-get install -y git make - name: git clone run: | cd /tmp && git clone "https://github.com/harisekhon/$repo" - name: build run: | cd "/tmp/$repo" && make - name: zookeeper run: | cd "/tmp/$repo" && make zookeeper - name: fatpacks run: | cd "/tmp/$repo" && make fatpacks - name: test run: | cd "/tmp/$repo" && make test
{ "pile_set_name": "Github" }
{ "objects": [ { "attributes": { "description": "", "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"index\":\"protologbeat-*\",\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[]}" }, "title": "Temperature Timeline", "uiStateJSON": "{}", "version": 1, "visState": "{\"title\":\"Temperature Timeline\",\"type\":\"line\",\"params\":{\"type\":\"line\",\"grid\":{\"categoryLines\":true,\"style\":{\"color\":\"#eee\"}},\"categoryAxes\":[{\"id\":\"CategoryAxis-1\",\"type\":\"category\",\"position\":\"bottom\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\"},\"labels\":{\"show\":true,\"truncate\":100},\"title\":{}}],\"valueAxes\":[{\"id\":\"ValueAxis-1\",\"name\":\"LeftAxis-1\",\"type\":\"value\",\"position\":\"left\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\",\"mode\":\"normal\"},\"labels\":{\"show\":true,\"rotate\":0,\"filter\":false,\"truncate\":100},\"title\":{\"text\":\"Max cpu_temp_avg\"}}],\"seriesParams\":[{\"show\":\"true\",\"type\":\"line\",\"mode\":\"normal\",\"data\":{\"label\":\"Maximum CPU °C\",\"id\":\"1\"},\"valueAxis\":\"ValueAxis-1\",\"drawLinesBetweenPoints\":true,\"showCircles\":false,\"interpolate\":\"cardinal\"},{\"show\":true,\"mode\":\"normal\",\"type\":\"line\",\"drawLinesBetweenPoints\":true,\"showCircles\":false,\"interpolate\":\"cardinal\",\"data\":{\"id\":\"3\",\"label\":\"Maximum Other °C\"},\"valueAxis\":\"ValueAxis-1\"},{\"show\":true,\"mode\":\"normal\",\"type\":\"line\",\"drawLinesBetweenPoints\":true,\"showCircles\":false,\"interpolate\":\"cardinal\",\"data\":{\"id\":\"4\",\"label\":\"Maximum GPU °C\"},\"valueAxis\":\"ValueAxis-1\"},{\"show\":true,\"mode\":\"normal\",\"type\":\"line\",\"drawLinesBetweenPoints\":true,\"showCircles\":false,\"interpolate\":\"cardinal\",\"data\":{\"id\":\"8\",\"label\":\"Maximum Storage °C\"},\"valueAxis\":\"ValueAxis-1\"}],\"addTooltip\":true,\"addLegend\":true,\"legendPosition\":\"bottom\",\"times\":[],\"addTimeMarker\":false},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"cpu_temp_avg\",\"customLabel\":\"Maximum CPU °C\"}},{\"id\":\"2\",\"enabled\":true,\"type\":\"date_histogram\",\"schema\":\"segment\",\"params\":{\"field\":\"@timestamp\",\"timeRange\":{\"from\":\"now-12h\",\"to\":\"now\",\"mode\":\"quick\"},\"useNormalizedEsInterval\":true,\"interval\":\"auto\",\"time_zone\":\"America/Denver\",\"drop_partials\":false,\"customInterval\":\"2h\",\"min_doc_count\":1,\"extended_bounds\":{}}},{\"id\":\"3\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"other_temp_avg\",\"customLabel\":\"Maximum Other °C\"}},{\"id\":\"4\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"gpu_temp_avg\",\"customLabel\":\"Maximum GPU °C\"}},{\"id\":\"8\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"hdd_temp_avg\",\"customLabel\":\"Maximum Storage °C\"}}]}" }, "id": "752a7e30-03af-11e9-bf7f-6138c205dfb3", "type": "visualization", "updated_at": "2018-12-20T18:16:43.966Z", "version": 1 }, { "attributes": { "description": "", "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[]}" }, "title": "Host Chooser", "uiStateJSON": "{}", "version": 1, "visState": "{\"title\":\"Host Chooser\",\"type\":\"input_control_vis\",\"params\":{\"controls\":[{\"id\":\"1545248066352\",\"indexPattern\":\"protologbeat-*\",\"fieldName\":\"host.name\",\"parent\":\"\",\"label\":\"Host\",\"type\":\"list\",\"options\":{\"type\":\"terms\",\"multiselect\":true,\"dynamicOptions\":true,\"size\":5,\"order\":\"desc\"}}],\"updateFiltersOnChange\":false,\"useTimeFilter\":false,\"pinFilters\":false},\"aggs\":[]}" }, "id": "293d13a0-03c5-11e9-b42b-a7822d24ca20", "type": "visualization", "updated_at": "2018-12-19T19:34:54.681Z", "version": 1 }, { "attributes": { "columns": [ "host.name", "cpu_temp_avg", "hdd_temp_avg", "other_temp_avg" ], "description": "", "hits": 0, "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"index\":\"protologbeat-*\",\"highlightAll\":true,\"version\":true,\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[]}" }, "sort": [ "@timestamp", "desc" ], "title": "Protologbeat search", "version": 1 }, "id": "65345580-03c5-11e9-b42b-a7822d24ca20", "type": "search", "updated_at": "2018-12-20T18:16:42.939Z", "version": 1 }, { "attributes": { "description": "", "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"index\":\"protologbeat-*\",\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[]}" }, "title": "CPU and Storage Temperature Gauge", "uiStateJSON": "{\"vis\":{\"defaultColors\":{\"0 - 60\":\"rgb(0,104,55)\",\"60 - 70\":\"rgb(255,255,190)\",\"70 - 90\":\"rgb(165,0,38)\"}}}", "version": 1, "visState": "{\"title\":\"CPU and Storage Temperature Gauge\",\"type\":\"gauge\",\"params\":{\"type\":\"gauge\",\"addTooltip\":true,\"addLegend\":false,\"isDisplayWarning\":false,\"gauge\":{\"verticalSplit\":false,\"extendRange\":true,\"percentageMode\":false,\"gaugeType\":\"Arc\",\"gaugeStyle\":\"Full\",\"backStyle\":\"Full\",\"orientation\":\"vertical\",\"colorSchema\":\"Green to Red\",\"gaugeColorMode\":\"Labels\",\"colorsRange\":[{\"from\":0,\"to\":60},{\"from\":60,\"to\":70},{\"from\":70,\"to\":90}],\"invertColors\":false,\"labels\":{\"show\":true,\"color\":\"black\"},\"scale\":{\"show\":true,\"labels\":false,\"color\":\"#333\"},\"type\":\"meter\",\"style\":{\"bgWidth\":0.9,\"width\":0.9,\"mask\":false,\"bgMask\":false,\"maskBars\":50,\"bgFill\":\"#eee\",\"bgColor\":false,\"subText\":\"\",\"fontSize\":60,\"labelColor\":true}}},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"cpu_temp_avg\",\"customLabel\":\"Maximum CPU °C\"}},{\"id\":\"2\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"hdd_temp_avg\",\"customLabel\":\"Maximum Storage °C\"}}]}" }, "id": "db628ba0-03c5-11e9-b42b-a7822d24ca20", "type": "visualization", "updated_at": "2018-12-20T18:16:43.991Z", "version": 1 }, { "attributes": { "description": "", "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"index\":\"protologbeat-*\",\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[]}" }, "title": "Maximum Sensor CPU and Storage Temperatures", "uiStateJSON": "{}", "version": 1, "visState": "{\"title\":\"Maximum Sensor CPU and Storage Temperatures\",\"type\":\"histogram\",\"params\":{\"type\":\"histogram\",\"grid\":{\"categoryLines\":false,\"style\":{\"color\":\"#eee\"},\"valueAxis\":\"ValueAxis-1\"},\"categoryAxes\":[{\"id\":\"CategoryAxis-1\",\"type\":\"category\",\"position\":\"bottom\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\"},\"labels\":{\"show\":true,\"truncate\":100,\"rotate\":0},\"title\":{}}],\"valueAxes\":[{\"id\":\"ValueAxis-1\",\"name\":\"LeftAxis-1\",\"type\":\"value\",\"position\":\"left\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\",\"mode\":\"normal\",\"defaultYExtents\":false},\"labels\":{\"show\":true,\"rotate\":0,\"filter\":false,\"truncate\":100},\"title\":{\"text\":\"Maximum CPU °C\"}}],\"seriesParams\":[{\"show\":\"true\",\"type\":\"histogram\",\"mode\":\"normal\",\"data\":{\"label\":\"Maximum CPU °C\",\"id\":\"1\"},\"valueAxis\":\"ValueAxis-1\",\"drawLinesBetweenPoints\":true,\"showCircles\":true},{\"show\":true,\"mode\":\"normal\",\"type\":\"histogram\",\"drawLinesBetweenPoints\":true,\"showCircles\":true,\"data\":{\"id\":\"3\",\"label\":\"Maximum Storage °C\"},\"valueAxis\":\"ValueAxis-1\"}],\"addTooltip\":true,\"addLegend\":true,\"legendPosition\":\"bottom\",\"times\":[],\"addTimeMarker\":false,\"orderBucketsBySum\":true},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"cpu_temp_avg\",\"customLabel\":\"Maximum CPU °C\"}},{\"id\":\"2\",\"enabled\":true,\"type\":\"terms\",\"schema\":\"segment\",\"params\":{\"field\":\"host.name\",\"size\":10,\"order\":\"desc\",\"orderBy\":\"1\",\"otherBucket\":true,\"otherBucketLabel\":\"Other\",\"missingBucket\":false,\"missingBucketLabel\":\"Missing\",\"customLabel\":\"Sensor Name\"}},{\"id\":\"3\",\"enabled\":true,\"type\":\"max\",\"schema\":\"metric\",\"params\":{\"field\":\"hdd_temp_avg\",\"customLabel\":\"Maximum Storage °C\"}}]}" }, "id": "923c3ce0-03c6-11e9-b42b-a7822d24ca20", "type": "visualization", "updated_at": "2018-12-20T18:16:43.961Z", "version": 1 }, { "attributes": { "description": "", "hits": 0, "kibanaSavedObjectMeta": { "searchSourceJSON": "{\"query\":{\"language\":\"lucene\",\"query\":\"\"},\"filter\":[]}" }, "optionsJSON": "{\"darkTheme\":true,\"hidePanelTitles\":false,\"useMargins\":false}", "panelsJSON": "[{\"embeddableConfig\":{},\"gridData\":{\"x\":0,\"y\":31,\"w\":48,\"h\":35,\"i\":\"1\"},\"id\":\"752a7e30-03af-11e9-bf7f-6138c205dfb3\",\"panelIndex\":\"1\",\"type\":\"visualization\",\"version\":\"6.5.3\"},{\"embeddableConfig\":{},\"gridData\":{\"x\":0,\"y\":0,\"w\":20,\"h\":11,\"i\":\"2\"},\"id\":\"293d13a0-03c5-11e9-b42b-a7822d24ca20\",\"panelIndex\":\"2\",\"title\":\"Sensor Filter\",\"type\":\"visualization\",\"version\":\"6.5.3\"},{\"embeddableConfig\":{},\"gridData\":{\"x\":0,\"y\":66,\"w\":48,\"h\":29,\"i\":\"3\"},\"id\":\"65345580-03c5-11e9-b42b-a7822d24ca20\",\"panelIndex\":\"3\",\"title\":\"Sensor Metrics\",\"type\":\"search\",\"version\":\"6.5.3\"},{\"embeddableConfig\":{},\"gridData\":{\"x\":0,\"y\":11,\"w\":20,\"h\":20,\"i\":\"4\"},\"id\":\"db628ba0-03c5-11e9-b42b-a7822d24ca20\",\"panelIndex\":\"4\",\"type\":\"visualization\",\"version\":\"6.5.3\"},{\"embeddableConfig\":{},\"gridData\":{\"x\":20,\"y\":0,\"w\":28,\"h\":31,\"i\":\"5\"},\"id\":\"923c3ce0-03c6-11e9-b42b-a7822d24ca20\",\"panelIndex\":\"5\",\"type\":\"visualization\",\"version\":\"6.5.3\"}]", "timeRestore": false, "title": "Sensor Temperature dashboard", "version": 1 }, "id": "3c519150-03c5-11e9-b42b-a7822d24ca20", "type": "dashboard", "updated_at": "2018-12-20T18:16:43.882Z", "version": 1 } ], "version": "6.5.3" }
{ "pile_set_name": "Github" }
## geoip - Geolocation using GeoIP ### 作者 digoal ### 日期 2015-04-27 ### 标签 PostgreSQL , geoIP , IP地址转经纬度 ---- ## 背景 geoip是使用IP地址查询地理位置的一个插件,提供了以下几个查询函数。 ``` geoip_country_code(inet) - returns country code (2 chars) geoip_country(inet) - returns all country info (code, name, ...) geoip_city_location(inet) - returns just location ID (INT) geoip_city(inet) - returns all the city info (GPS, ZIP code, ...) geoip_asn(inet) - retusn ASN name and IP range ``` 这个插件需要用到IP地址库,地址库可以到 www.maxmind.com下载。 安装 ``` wget http://api.pgxn.org/dist/geoip/0.2.3/geoip-0.2.3.zip unzip geoip-0.2.3.zip export PATH=/opt/pgsql/bin:$PATH cd geoip-0.2.3 gmake clean; gmake; gmake install psql =# create extension geoip; ``` 导入地址库: ``` wget http://download.maxmind.com/download/geoip/database/asnum/GeoIPASNum2.zip wget http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity-latest.zip unzip ... $ sed 's/^\("[^"]*","[^"]*",\)"[^"]*","[^"]*",\("[^"]*","[^"]*"\)/\1\2/' GeoIPCountryWhois.csv > countries.csv $ tail -$((`wc -l GeoLiteCity-Location.csv | awk '{print $1}'`-2)) GeoLiteCity-Location.csv > locations.csv $ cd GeoLiteCity_20150407 $ tail -$((`wc -l GeoLiteCity-Blocks.csv | awk '{print $1}'`-2)) GeoLiteCity-Blocks.csv > blocks.csv $ tail -$((`wc -l GeoLiteCity-Location.csv | awk '{print $1}'`-2)) GeoLiteCity-Location.csv > locations.csv postgres@db-172-16-3-150-> psql psql (9.4.1) Type "help" for help. postgres=# COPY geoip_country FROM '/home/postgres/countries.csv' WITH csv DELIMITER ',' NULL '' QUOTE '"' ENCODING 'ISO-8859-2'; COPY 104679 postgres=# CREATE TEMPORARY TABLE geoip_city_block_tmp ( postgres(# begin_ip BIGINT NOT NULL, postgres(# end_ip BIGINT NOT NULL, postgres(# loc_id INTEGER NOT NULL postgres(# ); CREATE TABLE postgres=# CREATE TEMPORARY TABLE geoip_asn_tmp ( postgres(# begin_ip BIGINT NOT NULL, postgres(# end_ip BIGINT NOT NULL, postgres(# name TEXT NOT NULL postgres(# ); CREATE TABLE postgres=# COPY geoip_city_block_tmp FROM '/home/postgres/GeoLiteCity_20150407/blocks.csv' WITH csv DELIMITER ',' NULL '' QUOTE '"' ENCODING 'ISO-8859-2'; COPY 2018008 postgres=# COPY geoip_city_location FROM '/home/postgres/GeoLiteCity_20150407/locations.csv' WITH csv DELIMITER ',' NULL '' QUOTE '"' ENCODING 'ISO-8859-2'; COPY 658951 postgres=# COPY geoip_asn_tmp FROM '/home/postgres/GeoIPASNum2.csv' WITH csv DELIMITER ',' NULL '' QUOTE '"' ENCODING 'ISO-8859-2'; COPY 224846 postgres=# INSERT INTO geoip_city_block postgres-# SELECT geoip_bigint_to_inet(begin_ip), postgres-# geoip_bigint_to_inet(end_ip), loc_id postgres-# FROM geoip_city_block_tmp; INSERT 0 2018008 postgres=# INSERT INTO geoip_asn postgres-# SELECT geoip_bigint_to_inet(begin_ip), postgres-# geoip_bigint_to_inet(end_ip), name postgres-# FROM geoip_asn_tmp; INSERT 0 224846 ``` 测试: ``` postgres=# SELECT * FROM geoip_city('78.45.133.255'::inet); loc_id | country | region | city | postal_code | latitude | longitude | metro_code | area_code --------+---------+--------+-------+-------------+----------+-----------+------------+----------- 54219 | CZ | 78 | Ceska | | 49.2814 | 16.5648 | | (1 row) postgres=# SELECT * FROM geoip_city('202.101.172.35'::inet); loc_id | country | region | city | postal_code | latitude | longitude | metro_code | area_code --------+---------+--------+----------+-------------+----------+-----------+------------+----------- 68433 | CN | 02 | Hangzhou | | 30.2936 | 120.1614 | | (1 row) postgres=# SELECT * FROM geoip_asn('202.101.172.37'::inet); begin_ip | end_ip | name --------------+----------------+----------------- 202.101.64.0 | 202.102.51.255 | AS4134 Chinanet (1 row) ``` 性能: ``` postgres=# select count(*) from (SELECT geoip_asn('202.101.172.37'::inet) from generate_series(1,1000000)) t; count --------- 1000000 (1 row) Time: 57561.637 ms ``` 单次查询约0.057毫秒。 ``` postgres=# select count(*) from (SELECT geoip_city('202.101.172.37'::inet) from generate_series(1,100000)) t; count -------- 100000 (1 row) Time: 10020.797 ms ``` 单次查询约0.1毫秒。 ``` postgres=# select count(*) from (SELECT geoip_country('202.101.172.37'::inet) from generate_series(1,100000)) t; count -------- 100000 (1 row) Time: 2977.582 ms ``` 单次查询约0.03毫秒。 其他: ``` postgres=# select count(*) from (SELECT geoip_city_location('202.101.172.37'::inet) from generate_series(1,100000)) t; count -------- 100000 (1 row) Time: 8339.120 ms postgres=# select count(*) from (SELECT geoip_country_code('202.101.172.37'::inet) from generate_series(1,100000)) t; count -------- 100000 (1 row) Time: 2931.577 ms ``` ## 参考 1\. http://pgxn.org/dist/geoip/0.2.3/ 2\. http://dev.maxmind.com/geoip/legacy/geolite/ #### [PostgreSQL 许愿链接](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216") 您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。[开不开森](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216"). #### [9.9元购买3个月阿里云RDS PostgreSQL实例](https://www.aliyun.com/database/postgresqlactivity "57258f76c37864c6e6d23383d05714ea") #### [PostgreSQL 解决方案集合](https://yq.aliyun.com/topic/118 "40cff096e9ed7122c512b35d8561d9c8") #### [德哥 / digoal's github - 公益是一辈子的事.](https://github.com/digoal/blog/blob/master/README.md "22709685feb7cab07d30f30387f0a9ae") ![digoal's wechat](../pic/digoal_weixin.jpg "f7ad92eeba24523fd47a6e1a0e691b59")
{ "pile_set_name": "Github" }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "qmljslexer_p.h" #include "qmljsengine_p.h" #include "qmljsmemorypool_p.h" #include "qmljskeywords_p.h" #include <QtCore/qcoreapplication.h> #include <QtCore/qvarlengtharray.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok); QT_END_NAMESPACE using namespace QmlJS; static inline int regExpFlagFromChar(const QChar &ch) { switch (ch.unicode()) { case 'g': return Lexer::RegExp_Global; case 'i': return Lexer::RegExp_IgnoreCase; case 'm': return Lexer::RegExp_Multiline; } return 0; } static inline unsigned char convertHex(ushort c) { if (c >= '0' && c <= '9') return (c - '0'); else if (c >= 'a' && c <= 'f') return (c - 'a' + 10); else return (c - 'A' + 10); } static inline QChar convertHex(QChar c1, QChar c2) { return QChar((convertHex(c1.unicode()) << 4) + convertHex(c2.unicode())); } static inline QChar convertUnicode(QChar c1, QChar c2, QChar c3, QChar c4) { return QChar((convertHex(c3.unicode()) << 4) + convertHex(c4.unicode()), (convertHex(c1.unicode()) << 4) + convertHex(c2.unicode())); } Lexer::Lexer(Engine *engine) : _engine(engine) , _codePtr(0) , _endPtr(0) , _lastLinePtr(0) , _tokenLinePtr(0) , _tokenStartPtr(0) , _char(QLatin1Char('\n')) , _errorCode(NoError) , _currentLineNumber(0) , _tokenValue(0) , _parenthesesState(IgnoreParentheses) , _parenthesesCount(0) , _stackToken(-1) , _patternFlags(0) , _tokenKind(0) , _tokenLength(0) , _tokenLine(0) , _validTokenText(false) , _prohibitAutomaticSemicolon(false) , _restrictedKeyword(false) , _terminator(false) , _followsClosingBrace(false) , _delimited(true) , _qmlMode(true) { if (engine) engine->setLexer(this); } bool Lexer::qmlMode() const { return _qmlMode; } QString Lexer::code() const { return _code; } void Lexer::setCode(const QString &code, int lineno, bool qmlMode) { if (_engine) _engine->setCode(code); _qmlMode = qmlMode; _code = code; _tokenText.clear(); _tokenText.reserve(1024); _errorMessage.clear(); _tokenSpell = QStringRef(); _codePtr = code.unicode(); _endPtr = _codePtr + code.length(); _lastLinePtr = _codePtr; _tokenLinePtr = _codePtr; _tokenStartPtr = _codePtr; _char = QLatin1Char('\n'); _errorCode = NoError; _currentLineNumber = lineno; _tokenValue = 0; // parentheses state _parenthesesState = IgnoreParentheses; _parenthesesCount = 0; _stackToken = -1; _patternFlags = 0; _tokenLength = 0; _tokenLine = lineno; _validTokenText = false; _prohibitAutomaticSemicolon = false; _restrictedKeyword = false; _terminator = false; _followsClosingBrace = false; _delimited = true; } void Lexer::scanChar() { unsigned sequenceLength = isLineTerminatorSequence(); _char = *_codePtr++; if (sequenceLength == 2) _char = *_codePtr++; if (unsigned sequenceLength = isLineTerminatorSequence()) { _lastLinePtr = _codePtr + sequenceLength - 1; // points to the first character after the newline ++_currentLineNumber; } } namespace { inline bool isBinop(int tok) { switch (tok) { case Lexer::T_AND: case Lexer::T_AND_AND: case Lexer::T_AND_EQ: case Lexer::T_DIVIDE_: case Lexer::T_DIVIDE_EQ: case Lexer::T_EQ: case Lexer::T_EQ_EQ: case Lexer::T_EQ_EQ_EQ: case Lexer::T_GE: case Lexer::T_GT: case Lexer::T_GT_GT: case Lexer::T_GT_GT_EQ: case Lexer::T_GT_GT_GT: case Lexer::T_GT_GT_GT_EQ: case Lexer::T_LE: case Lexer::T_LT: case Lexer::T_LT_LT: case Lexer::T_LT_LT_EQ: case Lexer::T_MINUS: case Lexer::T_MINUS_EQ: case Lexer::T_NOT_EQ: case Lexer::T_NOT_EQ_EQ: case Lexer::T_OR: case Lexer::T_OR_EQ: case Lexer::T_OR_OR: case Lexer::T_PLUS: case Lexer::T_PLUS_EQ: case Lexer::T_REMAINDER: case Lexer::T_REMAINDER_EQ: case Lexer::T_RETURN: case Lexer::T_STAR: case Lexer::T_STAR_EQ: case Lexer::T_XOR: case Lexer::T_XOR_EQ: return true; default: return false; } } } // anonymous namespace int Lexer::lex() { const int previousTokenKind = _tokenKind; _tokenSpell = QStringRef(); _tokenKind = scanToken(); _tokenLength = _codePtr - _tokenStartPtr - 1; _delimited = false; _restrictedKeyword = false; _followsClosingBrace = (previousTokenKind == T_RBRACE); // update the flags switch (_tokenKind) { case T_LBRACE: case T_SEMICOLON: case T_QUESTION: case T_COLON: case T_TILDE: _delimited = true; break; default: if (isBinop(_tokenKind)) _delimited = true; break; case T_IF: case T_FOR: case T_WHILE: case T_WITH: _parenthesesState = CountParentheses; _parenthesesCount = 0; break; case T_ELSE: case T_DO: _parenthesesState = BalancedParentheses; break; case T_CONTINUE: case T_BREAK: case T_RETURN: case T_THROW: _restrictedKeyword = true; break; } // switch // update the parentheses state switch (_parenthesesState) { case IgnoreParentheses: break; case CountParentheses: if (_tokenKind == T_RPAREN) { --_parenthesesCount; if (_parenthesesCount == 0) _parenthesesState = BalancedParentheses; } else if (_tokenKind == T_LPAREN) { ++_parenthesesCount; } break; case BalancedParentheses: if (_tokenKind != T_DO && _tokenKind != T_ELSE) _parenthesesState = IgnoreParentheses; break; } // switch return _tokenKind; } bool Lexer::isUnicodeEscapeSequence(const QChar *chars) { if (isHexDigit(chars[0]) && isHexDigit(chars[1]) && isHexDigit(chars[2]) && isHexDigit(chars[3])) return true; return false; } QChar Lexer::decodeUnicodeEscapeCharacter(bool *ok) { if (_char == QLatin1Char('u') && isUnicodeEscapeSequence(&_codePtr[0])) { scanChar(); // skip u const QChar c1 = _char; scanChar(); const QChar c2 = _char; scanChar(); const QChar c3 = _char; scanChar(); const QChar c4 = _char; scanChar(); if (ok) *ok = true; return convertUnicode(c1, c2, c3, c4); } *ok = false; return QChar(); } QChar Lexer::decodeHexEscapeCharacter(bool *ok) { if (isHexDigit(_codePtr[0]) && isHexDigit(_codePtr[1])) { scanChar(); const QChar c1 = _char; scanChar(); const QChar c2 = _char; scanChar(); if (ok) *ok = true; return convertHex(c1, c2); } *ok = false; return QChar(); } static inline bool isIdentifierStart(QChar ch) { // fast path for ascii if ((ch.unicode() >= 'a' && ch.unicode() <= 'z') || (ch.unicode() >= 'A' && ch.unicode() <= 'Z') || ch == '$' || ch == '_') return true; switch (ch.category()) { case QChar::Number_Letter: case QChar::Letter_Uppercase: case QChar::Letter_Lowercase: case QChar::Letter_Titlecase: case QChar::Letter_Modifier: case QChar::Letter_Other: return true; default: break; } return false; } static bool isIdentifierPart(QChar ch) { // fast path for ascii if ((ch.unicode() >= 'a' && ch.unicode() <= 'z') || (ch.unicode() >= 'A' && ch.unicode() <= 'Z') || (ch.unicode() >= '0' && ch.unicode() <= '9') || ch == '$' || ch == '_' || ch.unicode() == 0x200c /* ZWNJ */ || ch.unicode() == 0x200d /* ZWJ */) return true; switch (ch.category()) { case QChar::Mark_NonSpacing: case QChar::Mark_SpacingCombining: case QChar::Number_DecimalDigit: case QChar::Number_Letter: case QChar::Letter_Uppercase: case QChar::Letter_Lowercase: case QChar::Letter_Titlecase: case QChar::Letter_Modifier: case QChar::Letter_Other: case QChar::Punctuation_Connector: return true; default: break; } return false; } int Lexer::scanToken() { if (_stackToken != -1) { int tk = _stackToken; _stackToken = -1; return tk; } _terminator = false; again: _validTokenText = false; _tokenLinePtr = _lastLinePtr; while (_char.isSpace()) { if (unsigned sequenceLength = isLineTerminatorSequence()) { _tokenLinePtr = _codePtr + sequenceLength - 1; if (_restrictedKeyword) { // automatic semicolon insertion _tokenLine = _currentLineNumber; _tokenStartPtr = _codePtr - 1; return T_SEMICOLON; } else { _terminator = true; syncProhibitAutomaticSemicolon(); } } scanChar(); } _tokenStartPtr = _codePtr - 1; _tokenLine = _currentLineNumber; if (_codePtr > _endPtr) return EOF_SYMBOL; const QChar ch = _char; scanChar(); switch (ch.unicode()) { case '~': return T_TILDE; case '}': return T_RBRACE; case '|': if (_char == QLatin1Char('|')) { scanChar(); return T_OR_OR; } else if (_char == QLatin1Char('=')) { scanChar(); return T_OR_EQ; } return T_OR; case '{': return T_LBRACE; case '^': if (_char == QLatin1Char('=')) { scanChar(); return T_XOR_EQ; } return T_XOR; case ']': return T_RBRACKET; case '[': return T_LBRACKET; case '?': return T_QUESTION; case '>': if (_char == QLatin1Char('>')) { scanChar(); if (_char == QLatin1Char('>')) { scanChar(); if (_char == QLatin1Char('=')) { scanChar(); return T_GT_GT_GT_EQ; } return T_GT_GT_GT; } else if (_char == QLatin1Char('=')) { scanChar(); return T_GT_GT_EQ; } return T_GT_GT; } else if (_char == QLatin1Char('=')) { scanChar(); return T_GE; } return T_GT; case '=': if (_char == QLatin1Char('=')) { scanChar(); if (_char == QLatin1Char('=')) { scanChar(); return T_EQ_EQ_EQ; } return T_EQ_EQ; } return T_EQ; case '<': if (_char == QLatin1Char('=')) { scanChar(); return T_LE; } else if (_char == QLatin1Char('<')) { scanChar(); if (_char == QLatin1Char('=')) { scanChar(); return T_LT_LT_EQ; } return T_LT_LT; } return T_LT; case ';': return T_SEMICOLON; case ':': return T_COLON; case '/': if (_char == QLatin1Char('*')) { scanChar(); while (_codePtr <= _endPtr) { if (_char == QLatin1Char('*')) { scanChar(); if (_char == QLatin1Char('/')) { scanChar(); if (_engine) { _engine->addComment(tokenOffset() + 2, _codePtr - _tokenStartPtr - 1 - 4, tokenStartLine(), tokenStartColumn() + 2); } goto again; } } else { scanChar(); } } } else if (_char == QLatin1Char('/')) { while (_codePtr <= _endPtr && !isLineTerminator()) { scanChar(); } if (_engine) { _engine->addComment(tokenOffset() + 2, _codePtr - _tokenStartPtr - 1 - 2, tokenStartLine(), tokenStartColumn() + 2); } goto again; } if (_char == QLatin1Char('=')) { scanChar(); return T_DIVIDE_EQ; } return T_DIVIDE_; case '.': if (_char.isDigit()) { QVarLengthArray<char,32> chars; chars.append(ch.unicode()); // append the `.' while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); } if (_char == QLatin1Char('e') || _char == QLatin1Char('E')) { if (_codePtr[0].isDigit() || ((_codePtr[0] == QLatin1Char('+') || _codePtr[0] == QLatin1Char('-')) && _codePtr[1].isDigit())) { chars.append(_char.unicode()); scanChar(); // consume `e' if (_char == QLatin1Char('+') || _char == QLatin1Char('-')) { chars.append(_char.unicode()); scanChar(); // consume the sign } while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); } } } chars.append('\0'); const char *begin = chars.constData(); const char *end = 0; bool ok = false; _tokenValue = qstrtod(begin, &end, &ok); if (end - begin != chars.size() - 1) { _errorCode = IllegalExponentIndicator; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number"); return T_ERROR; } return T_NUMERIC_LITERAL; } return T_DOT; case '-': if (_char == QLatin1Char('=')) { scanChar(); return T_MINUS_EQ; } else if (_char == QLatin1Char('-')) { scanChar(); if (_terminator && !_delimited && !_prohibitAutomaticSemicolon) { _stackToken = T_MINUS_MINUS; return T_SEMICOLON; } return T_MINUS_MINUS; } return T_MINUS; case ',': return T_COMMA; case '+': if (_char == QLatin1Char('=')) { scanChar(); return T_PLUS_EQ; } else if (_char == QLatin1Char('+')) { scanChar(); if (_terminator && !_delimited && !_prohibitAutomaticSemicolon) { _stackToken = T_PLUS_PLUS; return T_SEMICOLON; } return T_PLUS_PLUS; } return T_PLUS; case '*': if (_char == QLatin1Char('=')) { scanChar(); return T_STAR_EQ; } return T_STAR; case ')': return T_RPAREN; case '(': return T_LPAREN; case '&': if (_char == QLatin1Char('=')) { scanChar(); return T_AND_EQ; } else if (_char == QLatin1Char('&')) { scanChar(); return T_AND_AND; } return T_AND; case '%': if (_char == QLatin1Char('=')) { scanChar(); return T_REMAINDER_EQ; } return T_REMAINDER; case '!': if (_char == QLatin1Char('=')) { scanChar(); if (_char == QLatin1Char('=')) { scanChar(); return T_NOT_EQ_EQ; } return T_NOT_EQ; } return T_NOT; case '\'': case '"': { const QChar quote = ch; bool multilineStringLiteral = false; const QChar *startCode = _codePtr; if (_engine) { while (_codePtr <= _endPtr) { if (isLineTerminator()) { if (qmlMode()) break; _errorCode = IllegalCharacter; _errorMessage = QCoreApplication::translate("QmlParser", "Stray newline in string literal"); return T_ERROR; } else if (_char == QLatin1Char('\\')) { break; } else if (_char == quote) { _tokenSpell = _engine->midRef(startCode - _code.unicode() - 1, _codePtr - startCode); scanChar(); return T_STRING_LITERAL; } scanChar(); } } _validTokenText = true; _tokenText.resize(0); startCode--; while (startCode != _codePtr - 1) _tokenText += *startCode++; while (_codePtr <= _endPtr) { if (unsigned sequenceLength = isLineTerminatorSequence()) { multilineStringLiteral = true; _tokenText += _char; if (sequenceLength == 2) _tokenText += *_codePtr; scanChar(); } else if (_char == quote) { scanChar(); if (_engine) _tokenSpell = _engine->newStringRef(_tokenText); return multilineStringLiteral ? T_MULTILINE_STRING_LITERAL : T_STRING_LITERAL; } else if (_char == QLatin1Char('\\')) { scanChar(); if (_codePtr > _endPtr) { _errorCode = IllegalEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "End of file reached at escape sequence"); return T_ERROR; } QChar u; switch (_char.unicode()) { // unicode escape sequence case 'u': { bool ok = false; u = decodeUnicodeEscapeCharacter(&ok); if (! ok) { _errorCode = IllegalUnicodeEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence"); return T_ERROR; } } break; // hex escape sequence case 'x': { bool ok = false; u = decodeHexEscapeCharacter(&ok); if (!ok) { _errorCode = IllegalHexadecimalEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal hexadecimal escape sequence"); return T_ERROR; } } break; // single character escape sequence case '\\': u = QLatin1Char('\\'); scanChar(); break; case '\'': u = QLatin1Char('\''); scanChar(); break; case '\"': u = QLatin1Char('\"'); scanChar(); break; case 'b': u = QLatin1Char('\b'); scanChar(); break; case 'f': u = QLatin1Char('\f'); scanChar(); break; case 'n': u = QLatin1Char('\n'); scanChar(); break; case 'r': u = QLatin1Char('\r'); scanChar(); break; case 't': u = QLatin1Char('\t'); scanChar(); break; case 'v': u = QLatin1Char('\v'); scanChar(); break; case '0': if (! _codePtr->isDigit()) { scanChar(); u = QLatin1Char('\0'); break; } // fall through case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': _errorCode = IllegalEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "Octal escape sequences are not allowed"); return T_ERROR; case '\r': case '\n': case 0x2028u: case 0x2029u: scanChar(); continue; default: // non escape character u = _char; scanChar(); } _tokenText += u; } else { _tokenText += _char; scanChar(); } } _errorCode = UnclosedStringLiteral; _errorMessage = QCoreApplication::translate("QmlParser", "Unclosed string at end of line"); return T_ERROR; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scanNumber(ch); default: { QChar c = ch; bool identifierWithEscapeChars = false; if (c == QLatin1Char('\\') && _char == QLatin1Char('u')) { identifierWithEscapeChars = true; bool ok = false; c = decodeUnicodeEscapeCharacter(&ok); if (! ok) { _errorCode = IllegalUnicodeEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence"); return T_ERROR; } } if (isIdentifierStart(c)) { if (identifierWithEscapeChars) { _tokenText.resize(0); _tokenText += c; _validTokenText = true; } while (true) { c = _char; if (_char == QLatin1Char('\\') && _codePtr[0] == QLatin1Char('u')) { if (! identifierWithEscapeChars) { identifierWithEscapeChars = true; _tokenText.resize(0); _tokenText.insert(0, _tokenStartPtr, _codePtr - _tokenStartPtr - 1); _validTokenText = true; } scanChar(); // skip '\\' bool ok = false; c = decodeUnicodeEscapeCharacter(&ok); if (! ok) { _errorCode = IllegalUnicodeEscapeSequence; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence"); return T_ERROR; } if (isIdentifierPart(c)) _tokenText += c; continue; } else if (isIdentifierPart(c)) { if (identifierWithEscapeChars) _tokenText += c; scanChar(); continue; } _tokenLength = _codePtr - _tokenStartPtr - 1; int kind = T_IDENTIFIER; if (! identifierWithEscapeChars) kind = classify(_tokenStartPtr, _tokenLength, _qmlMode); if (_engine) { if (kind == T_IDENTIFIER && identifierWithEscapeChars) _tokenSpell = _engine->newStringRef(_tokenText); else _tokenSpell = _engine->midRef(_tokenStartPtr - _code.unicode(), _tokenLength); } return kind; } } } break; } return T_ERROR; } int Lexer::scanNumber(QChar ch) { if (ch != QLatin1Char('0')) { QVarLengthArray<char, 64> buf; buf += ch.toLatin1(); QChar n = _char; const QChar *code = _codePtr; while (n.isDigit()) { buf += n.toLatin1(); n = *code++; } if (n != QLatin1Char('.') && n != QLatin1Char('e') && n != QLatin1Char('E')) { if (code != _codePtr) { _codePtr = code - 1; scanChar(); } buf.append('\0'); _tokenValue = strtod(buf.constData(), 0); return T_NUMERIC_LITERAL; } } else if (_char.isDigit() && !qmlMode()) { _errorCode = IllegalCharacter; _errorMessage = QCoreApplication::translate("QmlParser", "Decimal numbers can't start with '0'"); return T_ERROR; } QVarLengthArray<char,32> chars; chars.append(ch.unicode()); if (ch == QLatin1Char('0') && (_char == QLatin1Char('x') || _char == QLatin1Char('X'))) { ch = _char; // remember the x or X to use it in the error message below. // parse hex integer literal chars.append(_char.unicode()); scanChar(); // consume `x' while (isHexDigit(_char)) { chars.append(_char.unicode()); scanChar(); } if (chars.size() < 3) { _errorCode = IllegalHexNumber; _errorMessage = QCoreApplication::translate("QmlParser", "At least one hexadecimal digit is required after '0%1'").arg(ch); return T_ERROR; } _tokenValue = integerFromString(chars.constData(), chars.size(), 16); return T_NUMERIC_LITERAL; } // decimal integer literal while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); // consume the digit } if (_char == QLatin1Char('.')) { chars.append(_char.unicode()); scanChar(); // consume `.' while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); } if (_char == QLatin1Char('e') || _char == QLatin1Char('E')) { if (_codePtr[0].isDigit() || ((_codePtr[0] == QLatin1Char('+') || _codePtr[0] == QLatin1Char('-')) && _codePtr[1].isDigit())) { chars.append(_char.unicode()); scanChar(); // consume `e' if (_char == QLatin1Char('+') || _char == QLatin1Char('-')) { chars.append(_char.unicode()); scanChar(); // consume the sign } while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); } } } } else if (_char == QLatin1Char('e') || _char == QLatin1Char('E')) { if (_codePtr[0].isDigit() || ((_codePtr[0] == QLatin1Char('+') || _codePtr[0] == QLatin1Char('-')) && _codePtr[1].isDigit())) { chars.append(_char.unicode()); scanChar(); // consume `e' if (_char == QLatin1Char('+') || _char == QLatin1Char('-')) { chars.append(_char.unicode()); scanChar(); // consume the sign } while (_char.isDigit()) { chars.append(_char.unicode()); scanChar(); } } } if (chars.size() == 1) { // if we ended up with a single digit, then it was a '0' _tokenValue = 0; return T_NUMERIC_LITERAL; } chars.append('\0'); const char *begin = chars.constData(); const char *end = 0; bool ok = false; _tokenValue = qstrtod(begin, &end, &ok); if (end - begin != chars.size() - 1) { _errorCode = IllegalExponentIndicator; _errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number"); return T_ERROR; } return T_NUMERIC_LITERAL; } bool Lexer::scanRegExp(RegExpBodyPrefix prefix) { _tokenText.resize(0); _validTokenText = true; _patternFlags = 0; if (prefix == EqualPrefix) _tokenText += QLatin1Char('='); while (true) { switch (_char.unicode()) { case '/': scanChar(); // scan the flags _patternFlags = 0; while (isIdentLetter(_char)) { int flag = regExpFlagFromChar(_char); if (flag == 0 || _patternFlags & flag) { _errorMessage = QCoreApplication::translate("QmlParser", "Invalid regular expression flag '%0'") .arg(QChar(_char)); return false; } _patternFlags |= flag; scanChar(); } _tokenLength = _codePtr - _tokenStartPtr - 1; return true; case '\\': // regular expression backslash sequence _tokenText += _char; scanChar(); if (_codePtr > _endPtr || isLineTerminator()) { _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence"); return false; } _tokenText += _char; scanChar(); break; case '[': // regular expression class _tokenText += _char; scanChar(); while (_codePtr <= _endPtr && ! isLineTerminator()) { if (_char == QLatin1Char(']')) break; else if (_char == QLatin1Char('\\')) { // regular expression backslash sequence _tokenText += _char; scanChar(); if (_codePtr > _endPtr || isLineTerminator()) { _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence"); return false; } _tokenText += _char; scanChar(); } else { _tokenText += _char; scanChar(); } } if (_char != QLatin1Char(']')) { _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression class"); return false; } _tokenText += _char; scanChar(); // skip ] break; default: if (_codePtr > _endPtr || isLineTerminator()) { _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal"); return false; } else { _tokenText += _char; scanChar(); } } // switch } // while return false; } bool Lexer::isLineTerminator() const { const ushort unicode = _char.unicode(); return unicode == 0x000Au || unicode == 0x000Du || unicode == 0x2028u || unicode == 0x2029u; } unsigned Lexer::isLineTerminatorSequence() const { switch (_char.unicode()) { case 0x000Au: case 0x2028u: case 0x2029u: return 1; case 0x000Du: if (_codePtr->unicode() == 0x000Au) return 2; else return 1; default: return 0; } } bool Lexer::isIdentLetter(QChar ch) { // ASCII-biased, since all reserved words are ASCII, aand hence the // bulk of content to be parsed. if ((ch >= QLatin1Char('a') && ch <= QLatin1Char('z')) || (ch >= QLatin1Char('A') && ch <= QLatin1Char('Z')) || ch == QLatin1Char('$') || ch == QLatin1Char('_')) return true; if (ch.unicode() < 128) return false; return ch.isLetterOrNumber(); } bool Lexer::isDecimalDigit(ushort c) { return (c >= '0' && c <= '9'); } bool Lexer::isHexDigit(QChar c) { return ((c >= QLatin1Char('0') && c <= QLatin1Char('9')) || (c >= QLatin1Char('a') && c <= QLatin1Char('f')) || (c >= QLatin1Char('A') && c <= QLatin1Char('F'))); } bool Lexer::isOctalDigit(ushort c) { return (c >= '0' && c <= '7'); } int Lexer::tokenEndLine() const { return _currentLineNumber; } int Lexer::tokenEndColumn() const { return _codePtr - _lastLinePtr; } QString Lexer::tokenText() const { if (_validTokenText) return _tokenText; if (_tokenKind == T_STRING_LITERAL) return QString(_tokenStartPtr + 1, _tokenLength - 2); return QString(_tokenStartPtr, _tokenLength); } Lexer::Error Lexer::errorCode() const { return _errorCode; } QString Lexer::errorMessage() const { return _errorMessage; } void Lexer::syncProhibitAutomaticSemicolon() { if (_parenthesesState == BalancedParentheses) { // we have seen something like "if (foo)", which means we should // never insert an automatic semicolon at this point, since it would // then be expanded into an empty statement (ECMA-262 7.9.1) _prohibitAutomaticSemicolon = true; _parenthesesState = IgnoreParentheses; } else { _prohibitAutomaticSemicolon = false; } } bool Lexer::prevTerminator() const { return _terminator; } bool Lexer::followsClosingBrace() const { return _followsClosingBrace; } bool Lexer::canInsertAutomaticSemicolon(int token) const { return token == T_RBRACE || token == EOF_SYMBOL || _terminator || _followsClosingBrace; } static const int uriTokens[] = { QmlJSGrammar::T_IDENTIFIER, QmlJSGrammar::T_PROPERTY, QmlJSGrammar::T_SIGNAL, QmlJSGrammar::T_READONLY, QmlJSGrammar::T_ON, QmlJSGrammar::T_BREAK, QmlJSGrammar::T_CASE, QmlJSGrammar::T_CATCH, QmlJSGrammar::T_CONTINUE, QmlJSGrammar::T_DEFAULT, QmlJSGrammar::T_DELETE, QmlJSGrammar::T_DO, QmlJSGrammar::T_ELSE, QmlJSGrammar::T_FALSE, QmlJSGrammar::T_FINALLY, QmlJSGrammar::T_FOR, QmlJSGrammar::T_FUNCTION, QmlJSGrammar::T_IF, QmlJSGrammar::T_IN, QmlJSGrammar::T_INSTANCEOF, QmlJSGrammar::T_NEW, QmlJSGrammar::T_NULL, QmlJSGrammar::T_RETURN, QmlJSGrammar::T_SWITCH, QmlJSGrammar::T_THIS, QmlJSGrammar::T_THROW, QmlJSGrammar::T_TRUE, QmlJSGrammar::T_TRY, QmlJSGrammar::T_TYPEOF, QmlJSGrammar::T_VAR, QmlJSGrammar::T_VOID, QmlJSGrammar::T_WHILE, QmlJSGrammar::T_CONST, QmlJSGrammar::T_DEBUGGER, QmlJSGrammar::T_RESERVED_WORD, QmlJSGrammar::T_WITH, QmlJSGrammar::EOF_SYMBOL }; static inline bool isUriToken(int token) { const int *current = uriTokens; while (*current != QmlJSGrammar::EOF_SYMBOL) { if (*current == token) return true; ++current; } return false; } bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error) { Q_ASSERT(!_qmlMode); lex(); // fetch the first token if (_tokenKind != T_DOT) return true; do { const int lineNumber = tokenStartLine(); const int column = tokenStartColumn(); lex(); // skip T_DOT if (! (_tokenKind == T_IDENTIFIER || _tokenKind == T_RESERVED_WORD)) return true; // expected a valid QML/JS directive const QString directiveName = tokenText(); if (! (directiveName == QLatin1String("pragma") || directiveName == QLatin1String("import"))) { error->message = QCoreApplication::translate("QmlParser", "Syntax error"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; // not a valid directive name } // it must be a pragma or an import directive. if (directiveName == QLatin1String("pragma")) { // .pragma library if (! (lex() == T_IDENTIFIER && tokenText() == QLatin1String("library"))) { error->message = QCoreApplication::translate("QmlParser", "Syntax error"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; // expected `library } // we found a .pragma library directive directives->pragmaLibrary(lineNumber, column); } else { Q_ASSERT(directiveName == QLatin1String("import")); lex(); // skip .import QString pathOrUri; QString version; bool fileImport = false; // file or uri import if (_tokenKind == T_STRING_LITERAL) { // .import T_STRING_LITERAL as T_IDENTIFIER fileImport = true; pathOrUri = tokenText(); if (!pathOrUri.endsWith(QLatin1String("js"))) { error->message = QCoreApplication::translate("QmlParser","Imported file must be a script"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; } } else if (_tokenKind == T_IDENTIFIER) { // .import T_IDENTIFIER (. T_IDENTIFIER)* T_NUMERIC_LITERAL as T_IDENTIFIER while (true) { if (!isUriToken(_tokenKind)) { error->message = QCoreApplication::translate("QmlParser","Invalid module URI"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; } pathOrUri.append(tokenText()); lex(); if (tokenStartLine() != lineNumber) { error->message = QCoreApplication::translate("QmlParser","Invalid module URI"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; } if (_tokenKind != QmlJSGrammar::T_DOT) break; pathOrUri.append(QLatin1Char('.')); lex(); if (tokenStartLine() != lineNumber) { error->message = QCoreApplication::translate("QmlParser","Invalid module URI"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; } } if (_tokenKind != T_NUMERIC_LITERAL) { error->message = QCoreApplication::translate("QmlParser","Module import requires a version"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; // expected the module version number } version = tokenText(); } // // recognize the mandatory `as' followed by the module name // if (! (lex() == T_IDENTIFIER && tokenText() == QLatin1String("as") && tokenStartLine() == lineNumber)) { if (fileImport) error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier"); else error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier"); if (tokenStartLine() != lineNumber) { error->loc.startLine = lineNumber; error->loc.startColumn = column; } else { error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); } return false; // expected `as' } if (lex() != T_IDENTIFIER || tokenStartLine() != lineNumber) { if (fileImport) error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier"); else error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; // expected module name } const QString module = tokenText(); if (!module.at(0).isUpper()) { error->message = QCoreApplication::translate("QmlParser","Invalid import qualifier"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; } if (fileImport) directives->importFile(pathOrUri, module, lineNumber, column); else directives->importModule(pathOrUri, version, module, lineNumber, column); } if (tokenStartLine() != lineNumber) { error->message = QCoreApplication::translate("QmlParser", "Syntax error"); error->loc.startLine = tokenStartLine(); error->loc.startColumn = tokenStartColumn(); return false; // the directives cannot span over multiple lines } // fetch the first token after the .pragma/.import directive lex(); } while (_tokenKind == T_DOT); return true; }
{ "pile_set_name": "Github" }
@import './_config'; body { font-family: 'Roboto', Helvetica, Arial, 'Lucida Grande', sans-serif; font-weight: 300; line-height: 1.5em; font-display: swap; } h1, h2, h3 { margin: 0 0 12px 0; padding: 0; font-weight: 300; line-height: 1.2em; } @media (min-width: $nav-break) { h1 { font-size: 2.5em; } } h1 { margin: 0 0 24px 0; } p { margin: 0 0 24px 0; } a { color: $color-type; &.invert { text-decoration: none; &:hover { text-decoration: underline; } } } hr { height: 1px; border: 0; margin: 0; border-top: 1px solid $color-border-light; }
{ "pile_set_name": "Github" }
@import '~antd/lib/style/themes/default.less'; // For 2.x reset compatibility // import 'antd/style/v2-compatible-reset'; // or // @import '~antd/style/v2-compatible-reset.css'; // unify the setting of elements's margin and padding for browsers body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section { margin: 0; padding: 0; } ul, ol { list-style: none; } html, body { height: 100%; } body { font-family: @font-family; line-height: 1.5; color: #314659; font-size: 14Px; background: #fff; transition: background 1s cubic-bezier(0.075, 0.82, 0.165, 1); overflow-x: hidden; -webkit-user-select: initial !important; user-select: initial !important; } a { transition: color .3s ease; &:focus { text-decoration: underline; text-decoration-skip: ink; } } .main-wrapper { background: #fff; padding: 40px 0 0; position: relative; } .main-container { padding: 0 170px 144px 64px; margin-left: -1Px; background: #fff; min-height: 500Px; overflow: hidden; border-left: 1Px solid #e9e9e9; position: relative; } .aside-container { padding-bottom: 50Px; font-family: Lato, @font-family; &.ant-menu-inline .ant-menu-submenu-title h4, &.ant-menu-inline > .ant-menu-item, &.ant-menu-inline .ant-menu-item a { font-size: 14Px; text-overflow: ellipsis; overflow: hidden; } &.ant-menu-inline .ant-menu-item-group-title { padding-left: 56px; } a[disabled] { color: #ccc; } } .aside-container .chinese { font-size: 12Px; margin-left: 6Px; font-weight: normal; opacity: .67; } .outside-link { display: inline-block; } .outside-link:after { content: '\e691'; font-family: 'anticon'; margin-left: 5Px; font-size: 12Px; color: #aaa; } .outside-link.internal { display: none; } #react-content { -webkit-user-select: initial; user-select: initial; }
{ "pile_set_name": "Github" }
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved. // Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information. // See ThirdPartyNotices.txt for references to third party code used inside Helios. using System; using Helios.Serialization; namespace Helios.Codecs { /// <summary> /// Exception thrown by a <see cref="IMessageDecoder" /> when encountering corrupt data /// </summary> public class DecoderException : HeliosException { public DecoderException(string message) : base(message) { } public DecoderException(Exception inner) : base("Exception occurred while decoding.", inner) { } } /// <summary> /// Exception thrown by a <see cref="IMessageEncoder" /> /// </summary> public class EncoderException : HeliosException { public EncoderException(Exception inner) : base("Exception occurred while encoding.", inner) { } public EncoderException(string message) : base(message) { } } /// <summary> /// Exception class that is thrown by a <see cref="IMessageDecoder" /> when it encounters a frame that is longer than /// can be processed /// </summary> public class TooLongFrameException : DecoderException { public TooLongFrameException(string message) : base(message) { } } /// <summary> /// Thrown when a frame of negative length is detected by a <see cref="IMessageDecoder" /> /// </summary> public class CorruptedFrameException : HeliosException { public CorruptedFrameException(string message) : base(message) { } } }
{ "pile_set_name": "Github" }
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package socket /* #include <sys/socket.h> #include <netinet/in.h> */ import "C" const ( sysAF_UNSPEC = C.AF_UNSPEC sysAF_INET = C.AF_INET sysAF_INET6 = C.AF_INET6 sysSOCK_RAW = C.SOCK_RAW ) type iovec C.struct_iovec type msghdr C.struct_msghdr type cmsghdr C.struct_cmsghdr type sockaddrInet C.struct_sockaddr_in type sockaddrInet6 C.struct_sockaddr_in6 const ( sizeofIovec = C.sizeof_struct_iovec sizeofMsghdr = C.sizeof_struct_msghdr sizeofCmsghdr = C.sizeof_struct_cmsghdr sizeofSockaddrInet = C.sizeof_struct_sockaddr_in sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 )
{ "pile_set_name": "Github" }
// Copyright (C) 2006-2009 Dmitry Bufistov and Andrey Parfenov // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <cassert> #include <ctime> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_real.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/random.hpp> #include <boost/graph/howard_cycle_ratio.hpp> /** * @author Dmitry Bufistov * @author Andrey Parfenov */ using namespace boost; typedef adjacency_list< listS, listS, directedS, property< vertex_index_t, int >, property< edge_weight_t, double, property< edge_weight2_t, double > > > grap_real_t; template < typename TG > void gen_rand_graph(TG& g, size_t nV, size_t nE) { g.clear(); mt19937 rng; rng.seed(0 /*uint32_t(time(0))*/); // Reproducable seed. boost::generate_random_graph(g, nV, nE, rng, true, true); boost::uniform_real<> ur(-1, 10); boost::variate_generator< boost::mt19937&, boost::uniform_real<> > ew1rg( rng, ur); randomize_property< edge_weight_t >(g, ew1rg); boost::uniform_int< size_t > uint(1, 5); boost::variate_generator< boost::mt19937&, boost::uniform_int< size_t > > ew2rg(rng, uint); randomize_property< edge_weight2_t >(g, ew2rg); } int main(int argc, char* argv[]) { using std::cout; using std::endl; const double epsilon = 0.0000001; double min_cr, max_cr; /// Minimum and maximum cycle ratio typedef std::vector< graph_traits< grap_real_t >::edge_descriptor > ccReal_t; ccReal_t cc; /// critical cycle grap_real_t tgr; property_map< grap_real_t, vertex_index_t >::type vim = get(vertex_index, tgr); property_map< grap_real_t, edge_weight_t >::type ew1 = get(edge_weight, tgr); property_map< grap_real_t, edge_weight2_t >::type ew2 = get(edge_weight2, tgr); gen_rand_graph(tgr, 1000, 30000); cout << "Vertices number: " << num_vertices(tgr) << endl; cout << "Edges number: " << num_edges(tgr) << endl; int i = 0; graph_traits< grap_real_t >::vertex_iterator vi, vi_end; for (boost::tie(vi, vi_end) = vertices(tgr); vi != vi_end; vi++) { vim[*vi] = i++; /// Initialize vertex index property } max_cr = maximum_cycle_ratio(tgr, vim, ew1, ew2); cout << "Maximum cycle ratio is " << max_cr << endl; min_cr = minimum_cycle_ratio(tgr, vim, ew1, ew2, &cc); cout << "Minimum cycle ratio is " << min_cr << endl; std::pair< double, double > cr(.0, .0); cout << "Critical cycle:\n"; for (ccReal_t::iterator itr = cc.begin(); itr != cc.end(); ++itr) { cr.first += ew1[*itr]; cr.second += ew2[*itr]; std::cout << "(" << vim[source(*itr, tgr)] << "," << vim[target(*itr, tgr)] << ") "; } cout << endl; assert(std::abs(cr.first / cr.second - min_cr) < epsilon * 2); return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
;;; pgg-gpg.el --- GnuPG support for PGG. ;; Copyright (C) 1999-2000, 2002-2017 Free Software Foundation, Inc. ;; Author: Daiki Ueno <ueno@unixuser.org> ;; Symmetric encryption and gpg-agent support added by: ;; Sascha Wilde <wilde@sha-bang.de> ;; Created: 1999/10/28 ;; Keywords: PGP, OpenPGP, GnuPG ;; Package: pgg ;; Obsolete-since: 24.1 ;; This file is part of GNU Emacs. ;; GNU Emacs is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. ;;; Code: (eval-when-compile (require 'cl)) (require 'pgg) (defgroup pgg-gpg () "GnuPG interface." :group 'pgg) (defcustom pgg-gpg-program "gpg" "The GnuPG executable." :group 'pgg-gpg :type 'string) (defcustom pgg-gpg-extra-args nil "Extra arguments for every GnuPG invocation." :group 'pgg-gpg :type '(repeat (string :tag "Argument"))) (defcustom pgg-gpg-recipient-argument "--recipient" "GnuPG option to specify recipient." :group 'pgg-gpg :type '(choice (const :tag "New `--recipient' option" "--recipient") (const :tag "Old `--remote-user' option" "--remote-user"))) (defcustom pgg-gpg-use-agent t "Whether to use gnupg agent for key caching." :group 'pgg-gpg :type 'boolean) (defvar pgg-gpg-user-id nil "GnuPG ID of your default identity.") (defun pgg-gpg-process-region (start end passphrase program args) (let* ((use-agent (and (null passphrase) (pgg-gpg-use-agent-p))) (output-file-name (pgg-make-temp-file "pgg-output")) (args `("--status-fd" "2" ,@(if use-agent '("--use-agent") (if passphrase '("--passphrase-fd" "0"))) "--yes" ; overwrite "--output" ,output-file-name ,@pgg-gpg-extra-args ,@args)) (output-buffer pgg-output-buffer) (errors-buffer pgg-errors-buffer) (orig-mode (default-file-modes)) (process-connection-type nil) (inhibit-redisplay t) process status exit-status passphrase-with-newline encoded-passphrase-with-new-line) (with-current-buffer (get-buffer-create errors-buffer) (buffer-disable-undo) (erase-buffer)) (unwind-protect (progn (set-default-file-modes 448) (let ((coding-system-for-write 'binary)) (setq process (apply #'start-process "*GnuPG*" errors-buffer program args))) (set-process-sentinel process #'ignore) (when passphrase (setq passphrase-with-newline (concat passphrase "\n")) (if pgg-passphrase-coding-system (progn (setq encoded-passphrase-with-new-line (encode-coding-string passphrase-with-newline (coding-system-change-eol-conversion pgg-passphrase-coding-system 'unix))) (pgg-clear-string passphrase-with-newline)) (setq encoded-passphrase-with-new-line passphrase-with-newline passphrase-with-newline nil)) (process-send-string process encoded-passphrase-with-new-line)) (process-send-region process start end) (process-send-eof process) (while (eq 'run (process-status process)) (accept-process-output process 5)) ;; Accept any remaining pending output coming after the ;; status change. (accept-process-output process 5) (setq status (process-status process) exit-status (process-exit-status process)) (delete-process process) (with-current-buffer (get-buffer-create output-buffer) (buffer-disable-undo) (erase-buffer) (if (file-exists-p output-file-name) (let ((coding-system-for-read (if pgg-text-mode 'raw-text 'binary))) (insert-file-contents output-file-name))) (set-buffer errors-buffer) (if (memq status '(stop signal)) (error "%s exited abnormally: `%s'" program exit-status)) (if (= 127 exit-status) (error "%s could not be found" program)))) (if passphrase-with-newline (pgg-clear-string passphrase-with-newline)) (if encoded-passphrase-with-new-line (pgg-clear-string encoded-passphrase-with-new-line)) (if (and process (eq 'run (process-status process))) (interrupt-process process)) (if (file-exists-p output-file-name) (delete-file output-file-name)) (set-default-file-modes orig-mode)))) (defun pgg-gpg-possibly-cache-passphrase (passphrase &optional key notruncate) (if (and passphrase pgg-cache-passphrase (progn (goto-char (point-min)) (re-search-forward "^\\[GNUPG:] \\(GOOD_PASSPHRASE\\>\\)\\|\\(SIG_CREATED\\)" nil t))) (pgg-add-passphrase-to-cache (or key (progn (goto-char (point-min)) (if (re-search-forward "^\\[GNUPG:] NEED_PASSPHRASE\\(_PIN\\)? \\w+ ?\\w*" nil t) (substring (match-string 0) -8)))) passphrase notruncate))) (defvar pgg-gpg-all-secret-keys 'unknown) (defun pgg-gpg-lookup-all-secret-keys () "Return all secret keys present in secret key ring." (when (eq pgg-gpg-all-secret-keys 'unknown) (setq pgg-gpg-all-secret-keys '()) (let ((args (list "--with-colons" "--no-greeting" "--batch" "--list-secret-keys"))) (with-temp-buffer (apply #'call-process pgg-gpg-program nil t nil args) (goto-char (point-min)) (while (re-search-forward "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)" nil t) (push (substring (match-string 2) 8) pgg-gpg-all-secret-keys))))) pgg-gpg-all-secret-keys) (defun pgg-gpg-lookup-key (string &optional type) "Search keys associated with STRING." (let ((args (list "--with-colons" "--no-greeting" "--batch" (if type "--list-secret-keys" "--list-keys") string))) (with-temp-buffer (apply #'call-process pgg-gpg-program nil t nil args) (goto-char (point-min)) (if (re-search-forward "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)" nil t) (substring (match-string 2) 8))))) (defun pgg-gpg-lookup-key-owner (string &optional all) "Search keys associated with STRING and return owner of identified key. The value may be just the bare key id, or it may be a combination of the user name associated with the key and the key id, with the key id enclosed in \"<...>\" angle brackets. Optional ALL non-nil means search all keys, including secret keys." (let ((args (list "--with-colons" "--no-greeting" "--batch" (if all "--list-secret-keys" "--list-keys") string)) (key-regexp (concat "^\\(sec\\|pub\\|uid\\)" ":[^:]*:[^:]*:[^:]*:\\([^:]*\\):[^:]*" ":[^:]*:[^:]*:[^:]*:\\([^:]+\\):"))) (with-temp-buffer (apply #'call-process pgg-gpg-program nil t nil args) (goto-char (point-min)) (if (re-search-forward key-regexp nil t) (match-string 3))))) (defun pgg-gpg-key-id-from-key-owner (key-owner) (cond ((not key-owner) nil) ;; Extract bare key id from outermost paired angle brackets, if any: ((string-match "[^<]*<\\(.+\\)>[^>]*" key-owner) (substring key-owner (match-beginning 1)(match-end 1))) (key-owner))) (defun pgg-gpg-encrypt-region (start end recipients &optional sign passphrase) "Encrypt the current region between START and END. If optional argument SIGN is non-nil, do a combined sign and encrypt. If optional PASSPHRASE is not specified, it will be obtained from the passphrase cache or user." (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id)) (passphrase (or passphrase (when (and sign (not (pgg-gpg-use-agent-p))) (pgg-read-passphrase (format "GnuPG passphrase for %s: " pgg-gpg-user-id) pgg-gpg-user-id)))) (args (append (list "--batch" "--armor" "--always-trust" "--encrypt") (if pgg-text-mode (list "--textmode")) (if sign (list "--sign" "--local-user" pgg-gpg-user-id)) (if (or recipients pgg-encrypt-for-me) (apply #'nconc (mapcar (lambda (rcpt) (list pgg-gpg-recipient-argument rcpt)) (append recipients (if pgg-encrypt-for-me (list pgg-gpg-user-id))))))))) (pgg-gpg-process-region start end passphrase pgg-gpg-program args) (when sign (with-current-buffer pgg-errors-buffer ;; Possibly cache passphrase under, e.g. "jas", for future sign. (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id) ;; Possibly cache passphrase under, e.g. B565716F, for future decrypt. (pgg-gpg-possibly-cache-passphrase passphrase))) (pgg-process-when-success))) (defun pgg-gpg-encrypt-symmetric-region (start end &optional passphrase) "Encrypt the current region between START and END with symmetric cipher. If optional PASSPHRASE is not specified, it will be obtained from the passphrase cache or user." (let* ((passphrase (or passphrase (when (not (pgg-gpg-use-agent-p)) (pgg-read-passphrase "GnuPG passphrase for symmetric encryption: ")))) (args (append (list "--batch" "--armor" "--symmetric" ) (if pgg-text-mode (list "--textmode"))))) (pgg-gpg-process-region start end passphrase pgg-gpg-program args) (pgg-process-when-success))) (defun pgg-gpg-decrypt-region (start end &optional passphrase) "Decrypt the current region between START and END. If optional PASSPHRASE is not specified, it will be obtained from the passphrase cache or user." (let* ((current-buffer (current-buffer)) (message-keys (with-temp-buffer (insert-buffer-substring current-buffer) (pgg-decode-armor-region (point-min) (point-max)))) (secret-keys (pgg-gpg-lookup-all-secret-keys)) ;; XXX the user is stuck if they need to use the passphrase for ;; any but the first secret key for which the message is ;; encrypted. ideally, we would incrementally give them a ;; chance with subsequent keys each time they fail with one. (key (pgg-gpg-select-matching-key message-keys secret-keys)) (key-owner (and key (pgg-gpg-lookup-key-owner key t))) (key-id (pgg-gpg-key-id-from-key-owner key-owner)) (pgg-gpg-user-id (or key-id key pgg-gpg-user-id pgg-default-user-id)) (passphrase (or passphrase (when (not (pgg-gpg-use-agent-p)) (pgg-read-passphrase (format (if (pgg-gpg-symmetric-key-p message-keys) "Passphrase for symmetric decryption: " "GnuPG passphrase for %s: ") (or key-owner "??")) pgg-gpg-user-id)))) (args '("--batch" "--decrypt"))) (pgg-gpg-process-region start end passphrase pgg-gpg-program args) (with-current-buffer pgg-errors-buffer (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id) (goto-char (point-min)) (re-search-forward "^\\[GNUPG:] DECRYPTION_OKAY\\>" nil t)))) ;;;###autoload (defun pgg-gpg-symmetric-key-p (message-keys) "True if decoded armor MESSAGE-KEYS has symmetric encryption indicator." (let (result) (dolist (key message-keys result) (when (and (eq (car key) 3) (member '(symmetric-key-algorithm) key)) (setq result key))))) (defun pgg-gpg-select-matching-key (message-keys secret-keys) "Choose a key from MESSAGE-KEYS that matches one of the keys in SECRET-KEYS." (loop for message-key in message-keys for message-key-id = (and (equal (car message-key) 1) (cdr (assq 'key-identifier (cdr message-key)))) for key = (and message-key-id (pgg-lookup-key message-key-id 'encrypt)) when (and key (member key secret-keys)) return key)) (defun pgg-gpg-sign-region (start end &optional cleartext passphrase) "Make detached signature from text between START and END." (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id)) (passphrase (or passphrase (when (not (pgg-gpg-use-agent-p)) (pgg-read-passphrase (format "GnuPG passphrase for %s: " pgg-gpg-user-id) pgg-gpg-user-id)))) (args (append (list (if cleartext "--clearsign" "--detach-sign") "--armor" "--batch" "--verbose" "--local-user" pgg-gpg-user-id) (if pgg-text-mode (list "--textmode")))) (inhibit-read-only t) buffer-read-only) (pgg-gpg-process-region start end passphrase pgg-gpg-program args) (with-current-buffer pgg-errors-buffer ;; Possibly cache passphrase under, e.g. "jas", for future sign. (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id) ;; Possibly cache passphrase under, e.g. B565716F, for future decrypt. (pgg-gpg-possibly-cache-passphrase passphrase)) (pgg-process-when-success))) (defun pgg-gpg-verify-region (start end &optional signature) "Verify region between START and END as the detached signature SIGNATURE." (let ((args '("--batch" "--verify"))) (when (stringp signature) (setq args (append args (list signature)))) (setq args (append args '("-"))) (pgg-gpg-process-region start end nil pgg-gpg-program args) (with-current-buffer pgg-errors-buffer (goto-char (point-min)) (while (re-search-forward "^gpg: \\(.*\\)\n" nil t) (with-current-buffer pgg-output-buffer (insert-buffer-substring pgg-errors-buffer (match-beginning 1) (match-end 0))) (delete-region (match-beginning 0) (match-end 0))) (goto-char (point-min)) (re-search-forward "^\\[GNUPG:] GOODSIG\\>" nil t)))) (defun pgg-gpg-insert-key () "Insert public key at point." (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id)) (args (list "--batch" "--export" "--armor" pgg-gpg-user-id))) (pgg-gpg-process-region (point)(point) nil pgg-gpg-program args) (insert-buffer-substring pgg-output-buffer))) (defun pgg-gpg-snarf-keys-region (start end) "Add all public keys in region between START and END to the keyring." (let ((args '("--import" "--batch" "-")) status) (pgg-gpg-process-region start end nil pgg-gpg-program args) (set-buffer pgg-errors-buffer) (goto-char (point-min)) (when (re-search-forward "^\\[GNUPG:] IMPORT_RES\\>" nil t) (setq status (buffer-substring (match-end 0) (progn (end-of-line)(point))) status (vconcat (mapcar #'string-to-number (split-string status)))) (erase-buffer) (insert (format "Imported %d key(s). \tArmor contains %d key(s) [%d bad, %d old].\n" (+ (aref status 2) (aref status 10)) (aref status 0) (aref status 1) (+ (aref status 4) (aref status 11))) (if (zerop (aref status 9)) "" "\tSecret keys are imported.\n"))) (append-to-buffer pgg-output-buffer (point-min)(point-max)) (pgg-process-when-success))) (defun pgg-gpg-update-agent () "Try to connect to gpg-agent and send UPDATESTARTUPTTY." (if (fboundp 'make-network-process) (let* ((agent-info (getenv "GPG_AGENT_INFO")) (socket (and agent-info (string-match "^\\([^:]*\\)" agent-info) (match-string 1 agent-info))) (conn (and socket (make-network-process :name "gpg-agent-process" :host 'local :family 'local :service socket)))) (when (and conn (eq (process-status conn) 'open)) (process-send-string conn "UPDATESTARTUPTTY\n") (delete-process conn) t)) ;; We can't check, so assume gpg-agent is up. t)) (defun pgg-gpg-use-agent-p () "Return t if `pgg-gpg-use-agent' is t and gpg-agent is available." (and pgg-gpg-use-agent (pgg-gpg-update-agent))) (provide 'pgg-gpg) ;;; pgg-gpg.el ends here
{ "pile_set_name": "Github" }
<div class="modal fade" tabindex="-1" role="dialog" aria-modal="true" aria-labelledby="folderAddEditTitle"> <div class="modal-dialog modal-sm" role="document"> <form class="modal-content" #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate> <div class="modal-header"> <h2 class="modal-title" id="folderAddEditTitle">{{title}}</h2> <button type="button" class="close" data-dismiss="modal" appA11yTitle="{{'close' | i18n}}"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <label for="name">{{'name' | i18n}}</label> <input id="name" class="form-control" type="text" name="Name" [(ngModel)]="folder.name" required> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading"> <i class="fa fa-spinner fa-spin" title="{{'loading' | i18n}}" aria-hidden="true"></i> <span>{{'save' | i18n}}</span> </button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">{{'cancel' | i18n}}</button> <div class="ml-auto"> <button #deleteBtn type="button" (click)="delete()" class="btn btn-outline-danger" appA11yTitle="{{'delete' | i18n}}" *ngIf="editMode" [disabled]="deleteBtn.loading" [appApiAction]="deletePromise"> <i class="fa fa-trash-o fa-lg fa-fw" [hidden]="deleteBtn.loading" aria-hidden="true"></i> <i class="fa fa-spinner fa-spin fa-lg fa-fw" [hidden]="!deleteBtn.loading" title="{{'loading' | i18n}}" aria-hidden="true"></i> </button> </div> </div> </form> </div> </div>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2009 Andrejs Jermakovics. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andrejs Jermakovics - initial implementation */ package it.unibz.instasearch.indexing.querying; import it.unibz.instasearch.indexing.Field; import java.util.HashMap; import org.apache.lucene.index.Term; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.WildcardQuery; /** * Converts field aliases to actual field names */ public class FieldAliasConverter extends QueryVisitor { private static HashMap<String, Field> aliases = new HashMap<String, Field>(); static { aliases.put("project", Field.PROJ); aliases.put("filetype", Field.EXT); aliases.put("type", Field.EXT); aliases.put("workingset", Field.WS); aliases.put("age", Field.MODIFIED); aliases.put("folder", Field.DIR); } /** * */ public FieldAliasConverter() { } @Override public Query visit(TermQuery termQuery, Field termField) { Term t = termQuery.getTerm(); if( termField == null && aliases.containsKey(t.field()) ) { Field field = aliases.get(t.field()); Term newTerm = field.createTerm(t.text()); TermQuery newTermQuery = new TermQuery(newTerm); return newTermQuery; } return super.visit(termQuery, termField); } @Override public Query visit(PrefixQuery prefixQuery, Field termField) { Term t = prefixQuery.getPrefix(); if( termField == null && aliases.containsKey(t.field()) ) { Field field = aliases.get(t.field()); Term newTerm = field.createTerm(t.text()); PrefixQuery newTermQuery = new PrefixQuery(newTerm); return newTermQuery; } return super.visit(prefixQuery, termField); } @Override public Query visit(WildcardQuery wildcardQuery, Field termField) { Term t = wildcardQuery.getTerm(); if( termField == null && aliases.containsKey(t.field()) ) { Field field = aliases.get(t.field()); Term newTerm = field.createTerm(t.text()); WildcardQuery newTermQuery = new WildcardQuery(newTerm); return newTermQuery; } return super.visit(wildcardQuery, termField); } }
{ "pile_set_name": "Github" }
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.apiv1.artifactstoreconfig.representers; import com.thoughtworks.go.api.base.OutputWriter; import com.thoughtworks.go.api.representers.ConfigurationPropertyRepresenter; import com.thoughtworks.go.api.representers.ErrorGetter; import com.thoughtworks.go.api.representers.JsonReader; import com.thoughtworks.go.config.ArtifactStore; import com.thoughtworks.go.spark.Routes; import java.util.Collections; import java.util.Map; public class ArtifactStoreRepresenter { public static void toJSON(OutputWriter outputWriter, ArtifactStore store) { outputWriter .addLinks(linksWriter -> linksWriter .addLink("self", Routes.ArtifactStoreConfig.id(store.getId())) .addAbsoluteLink("doc", Routes.ArtifactStoreConfig.DOC) .addLink("find", Routes.ArtifactStoreConfig.find())) .add("id", store.getId()) .add("plugin_id", store.getPluginId()) .addChildList("properties", listWriter -> store.forEach(property -> listWriter.addChild(propertyWriter -> ConfigurationPropertyRepresenter.toJSON(propertyWriter, property)))); if (store.hasErrors()) { Map<String, String> fieldMapping = Collections.singletonMap("pluginId", "plugin_id"); outputWriter.addChild("errors", errorWriter -> new ErrorGetter(fieldMapping).toJSON(errorWriter, store)); } } public static ArtifactStore fromJSON(JsonReader jsonReader) { ArtifactStore artifactStore = new ArtifactStore( jsonReader.getString("id"), jsonReader.getString("plugin_id")); artifactStore.addConfigurations(ConfigurationPropertyRepresenter.fromJSONArray(jsonReader, "properties")); return artifactStore; } }
{ "pile_set_name": "Github" }
{ "name": "lowercase tags", "options": {}, "html": "<!DOCTYPE html><HTML><TITLE>The Title</title><BODY>Hello world</body></html>", "expected": [ { "name": "!doctype", "data": "!DOCTYPE html", "type": "directive" }, { "type": "tag", "name": "html", "attribs": {}, "children": [ { "type": "tag", "name": "title", "attribs": {}, "children": [ { "data": "The Title", "type": "text" } ] }, { "type": "tag", "name": "body", "attribs": {}, "children": [ { "data": "Hello world", "type": "text" } ] } ] } ] }
{ "pile_set_name": "Github" }
# locally computed using sha256sum sha256 142127b7953fbd829b1057fb64a78d3340c2b771484230a7347e94530a0d9039 memtest86+-5.01.tar.gz sha256 2e15e2174b86640d7fbfcb62b51d9182062d9db71d66a46e5b01d736c68150ea README
{ "pile_set_name": "Github" }
##Package: StdCtrls ##Status: Partial ---------------------------------------------------------------------------------------------------- @@JvDatePickerEdit.pas Summary Contains the TJvDatePickerEdit component. Author Oliver Giesen ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.OnCancel Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.CreateWithAppearance Summary Write here a summary (1 line) Description Write here a description Parameters AOwner - Description for this parameter AAppearance - Description for this parameter See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar Summary Write here a summary (1 line) Description Write here a description ---------------------------------------------------------------------------------------------------- @@TJvDatePickerEdit <TITLEIMG TJvDatePickerEdit> #JVCLInfo <GROUP JVCL.DateTime.EditsCombos,JVCL.EditsMemosAndCombos.Edits,JVCL.SelectAndChoose> <FLAG Component> Summary A replacement for TDateTimePicker that maintains its look but fixes its deficiencies concerning keyboard entry. Description Write here a description ---------------------------------------------------------------------------------------------------- @@TJvDateFigureInfo.Length Description for Length ---------------------------------------------------------------------------------------------------- @@TJvDateFigureInfo.Index Description for Index ---------------------------------------------------------------------------------------------------- @@TJvDateFigures <TITLE TJvDateFigures type> Summary Write here a summary (1 line) Description You don't have to document already described items such as sets, pointers to records etc. (Value = array [0..2] of TJvDateFigureInfo; - for reference) ---------------------------------------------------------------------------------------------------- @@TJvDateFigureInfo.Figure Description for Figure ---------------------------------------------------------------------------------------------------- @@TJvDateFigureInfo.Start Description for Start ---------------------------------------------------------------------------------------------------- @@TJvDateFigure.dfMonth Description for dfMonth ---------------------------------------------------------------------------------------------------- @@TJvDateFigure.dfDay Description for dfDay ---------------------------------------------------------------------------------------------------- @@TJvDateFigureInfo <TITLE TJvDateFigureInfo type> Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDateFigure.dfYear Description for dfYear ---------------------------------------------------------------------------------------------------- @@TJvDateFigure.dfNone Description for dfNone ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.Text Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDateFigure <TITLE TJvDateFigure type> Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.StoreDateFormat Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.StoreDate Summary Specifies whether the date set or displayed at design time will be restored at runtime Description Write here a description See Also TJvCustomDatePickerEdit.Date ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.OnGetValidDateString Summary Write here a summary (1 line) Description Write here a description Parameters Sender - Description for this parameter DateText - Description for this parameter See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.NoDateText Summary Specifies the text that will be displayed at runtime when the control holds no date Description Write here a description See Also TJvCustomDatePickerEdit.ShowCheckbox ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.NoDateShortcut Summary Specifies the keyboard shortcut that will trigger the clearing of the control Description Write here a description See Also TJvCustomDatePickerEdit.ShowCheckbox ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.IsEmpty Summary Indicates at runtime whether the control is currently empty, i.e. holds no date Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.HasValidDate Summary Write here a summary (1 line) Description Write here a description Return value Describe here what the function returns See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.EditMask Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.EnableValidation Summary Enables "As-you-type" validation of entries Description If True, ranges on day and month figures will be enforced while typing, i.e. given a date format of "dd-MM-yyyy" an entry of "00-00-0000" would automatically be corrected to "01-01-0000" (enforcing of year ranges is not implemented yet because of the added complexity of handling two-digit years) and an entry of "99-99-9999" would automatically be corrected to "31-12-9999". The algorithm does not validate wh ther a given day is valid for the given month though, i.e. it does not yet catch an entry of "30-02-2005". See Also TJvCustomDatePickerEdit.DateFormat ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.Dropped Summary Indicates at runtime whether the drop-down calendar is currently visible Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.DateSeparator Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.DateFormat Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.Date Summary Returns the value of the control as TDateTime Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.Clear Summary Write here a summary (1 line) Description This is an overridden method, you don't have to describe these if it does the same as the inherited method See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.CalendarAppearance Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.AlwaysReturnEditDate Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit Summary Write here a summary (1 line) Description Write here a description ---------------------------------------------------------------------------------------------------- @@TJvCustomDatePickerEdit.AllowNoDate Summary Specifies whether the control allows clearing the value altogether. Description Write here a description See Also TJvCustomDatePickerEdit.ShowCheckbox ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.OnChange Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.OnSelect Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.SelDate Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.SetFocus Summary Write here a summary (1 line) Description This is an overridden method, you don't have to describe these if it does the same as the inherited method See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvDropCalendar.WithBeep Summary Write here a summary (1 line) Description Write here a description See Also List here other properties, methods (comma seperated) Remove the 'See Also' section if there are no references ---------------------------------------------------------------------------------------------------- @@TJvGetValidDateStringEvent <TITLE TJvGetValidDateStringEvent type> <COMBINE TJvCustomDatePickerEdit.OnGetValidDateString>
{ "pile_set_name": "Github" }
import { UserInventory } from '../../../model/user/inventory/user-inventory'; import { InventoryItem } from '../../../model/user/inventory/inventory-item'; import { InjectionToken } from '@angular/core'; import { ListRow } from '../../../modules/list/model/list-row'; import { ContainerType } from '../../../model/user/inventory/container-type'; export const INVENTORY_OPTIMIZER: InjectionToken<InventoryOptimizer> = new InjectionToken('InventoryOptimizer'); export abstract class InventoryOptimizer { protected static IGNORED_CONTAINERS = [ ContainerType.TradeInventory, ContainerType.FreeCompanyBag0, ContainerType.FreeCompanyBag1, ContainerType.FreeCompanyBag2, ContainerType.FreeCompanyBag3, ContainerType.FreeCompanyBag4, ContainerType.FreeCompanyBag5, ContainerType.FreeCompanyBag6, ContainerType.FreeCompanyBag7, ContainerType.FreeCompanyBag8, ContainerType.FreeCompanyBag9, ContainerType.FreeCompanyBag10, ContainerType.RetainerMarket, ContainerType.RetainerEquippedGear, ContainerType.Crystal, ContainerType.RetainerCrystal, ContainerType.HandIn, ContainerType.RetainerGil, ContainerType.FreeCompanyGil, ContainerType.GearSet0, ContainerType.GearSet1, ContainerType.Mail, ContainerType.UNKNOWN_1 ]; /// Compare two InventoryItem objects to determine whether they consume the same slot in the same /// container. protected static inSameSlot(source: InventoryItem, target: InventoryItem): boolean { return source.slot === target.slot && source.containerId === target.containerId; } public getOptimization(item: InventoryItem, inventory: UserInventory, extracts: ListRow[]): { [p: string]: number | string } | null { if (InventoryOptimizer.IGNORED_CONTAINERS.indexOf(item.containerId) > -1) { return null; } const data = extracts.find(i => i.id === item.itemId); return this._getOptimization(item, inventory, data); } protected abstract _getOptimization(item: InventoryItem, inventory: UserInventory, data: ListRow): { [p: string]: number | string } | null; public abstract getId(): string; }
{ "pile_set_name": "Github" }
Warning: VTypeProbes are deprecated. Use fcd-output devices (assigned to the vType) instead.
{ "pile_set_name": "Github" }
/* jqPlot @VERSION | (c) 2009-2015 Chris Leonello | jqplot.com jsDate | (c) 2010-2015 Chris Leonello */
{ "pile_set_name": "Github" }
#-*- coding:utf-8 -*- import warnings import logging from miasm.ir.ir import IntermediateRepresentation, AssignBlock from miasm.expression.expression import ExprOp, ExprAssign log = logging.getLogger("analysis") console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter("[%(levelname)-8s]: %(message)s")) log.addHandler(console_handler) log.setLevel(logging.WARNING) class ira(IntermediateRepresentation): """IR Analysis This class provides higher level manipulations on IR, such as dead instruction removals. This class can be used as a common parent with `miasm.ir.ir::IntermediateRepresentation` class. For instance: class ira_x86_16(ir_x86_16, ira) """ ret_reg = None def call_effects(self, addr, instr): """Default modelisation of a function call to @addr. This may be used to: * insert dependencies to arguments (stack base, registers, ...) * add some side effects (stack clean, return value, ...) Return a couple: * list of assignments to add to the current irblock * list of additional irblocks @addr: (Expr) address of the called function @instr: native instruction which is responsible of the call """ call_assignblk = AssignBlock( [ ExprAssign(self.ret_reg, ExprOp('call_func_ret', addr, self.sp)), ExprAssign(self.sp, ExprOp('call_func_stack', addr, self.sp)) ], instr ) return [call_assignblk], [] def add_instr_to_current_state(self, instr, block, assignments, ir_blocks_all, gen_pc_updt): """ Add the IR effects of an instruction to the current state. If the instruction is a function call, replace the original IR by a model of the sub function Returns a bool: * True if the current assignments list must be split * False in other cases. @instr: native instruction @block: native block source @assignments: current irbloc @ir_blocks_all: list of additional effects @gen_pc_updt: insert PC update effects between instructions """ if instr.is_subcall(): call_assignblks, extra_irblocks = self.call_effects( instr.args[0], instr ) assignments += call_assignblks ir_blocks_all += extra_irblocks return True if gen_pc_updt is not False: self.gen_pc_update(assignments, instr) assignblk, ir_blocks_extra = self.instr2ir(instr) assignments.append(assignblk) ir_blocks_all += ir_blocks_extra if ir_blocks_extra: return True return False def sizeof_char(self): "Return the size of a char in bits" raise NotImplementedError("Abstract method") def sizeof_short(self): "Return the size of a short in bits" raise NotImplementedError("Abstract method") def sizeof_int(self): "Return the size of an int in bits" raise NotImplementedError("Abstract method") def sizeof_long(self): "Return the size of a long in bits" raise NotImplementedError("Abstract method") def sizeof_pointer(self): "Return the size of a void* in bits" raise NotImplementedError("Abstract method")
{ "pile_set_name": "Github" }
namespace Ceras.Resolvers { using System; using Formatters; /// <summary> /// A formatter resolver is something that can create instances of <see cref="IFormatter{T}"/> for a given <see cref="Type"/> (or null if the resolver can not handle the given type) /// </summary> public interface IFormatterResolver { IFormatter GetFormatter(Type type); } }
{ "pile_set_name": "Github" }
package sfBugs; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Bug2791706 { public void clear() { Lock l = new ReentrantLock(); l.lock(); try { // do nothing } finally { l.unlock(); } } }
{ "pile_set_name": "Github" }
/* * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package sun.security.ssl; import java.security.*; /** * The "KeyManager" for ephemeral RSA keys. Ephemeral DH and ECDH keys * are handled by the DHCrypt and ECDHCrypt classes, respectively. * * @author Andreas Sterbenz */ final class EphemeralKeyManager { // indices for the keys array below private final static int INDEX_RSA512 = 0; private final static int INDEX_RSA1024 = 1; /* * Current cached RSA KeyPairs. Elements are never null. * Indexed via the the constants above. */ private final EphemeralKeyPair[] keys = new EphemeralKeyPair[] { new EphemeralKeyPair(null), new EphemeralKeyPair(null), }; EphemeralKeyManager() { // empty } /* * Get a temporary RSA KeyPair. */ KeyPair getRSAKeyPair(boolean export, SecureRandom random) { int length, index; if (export) { length = 512; index = INDEX_RSA512; } else { length = 1024; index = INDEX_RSA1024; } synchronized (keys) { KeyPair kp = keys[index].getKeyPair(); if (kp == null) { try { KeyPairGenerator kgen = JsseJce.getKeyPairGenerator("RSA"); kgen.initialize(length, random); keys[index] = new EphemeralKeyPair(kgen.genKeyPair()); kp = keys[index].getKeyPair(); } catch (Exception e) { // ignore } } return kp; } } /** * Inner class to handle storage of ephemeral KeyPairs. */ private static class EphemeralKeyPair { // maximum number of times a KeyPair is used private final static int MAX_USE = 200; // maximum time interval in which the keypair is used (1 hour in ms) private final static long USE_INTERVAL = 3600*1000; private KeyPair keyPair; private int uses; private long expirationTime; private EphemeralKeyPair(KeyPair keyPair) { this.keyPair = keyPair; expirationTime = System.currentTimeMillis() + USE_INTERVAL; } /* * Check if the KeyPair can still be used. */ private boolean isValid() { return (keyPair != null) && (uses < MAX_USE) && (System.currentTimeMillis() < expirationTime); } /* * Return the KeyPair or null if it is invalid. */ private KeyPair getKeyPair() { if (isValid() == false) { keyPair = null; return null; } uses++; return keyPair; } } }
{ "pile_set_name": "Github" }
package com.susion.boring.read.view; import android.app.Activity; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.PopupWindow; import com.susion.boring.base.SAppApplication; /** * Created by susion on 11/7/16. */ public class FixedPopupWindow extends PopupWindow { public FixedPopupWindow(Context context) { super(context); } public FixedPopupWindow(Context context, AttributeSet attrs) { super(context, attrs); } public FixedPopupWindow(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public FixedPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public FixedPopupWindow(View contentView) { super(contentView); } public FixedPopupWindow() { super(); } public FixedPopupWindow(int width, int height) { super(width, height); } public FixedPopupWindow(View contentView, int width, int height, boolean focusable) { super(contentView, width, height, focusable); } public FixedPopupWindow(View contentView, int width, int height) { super(contentView, width, height); } @Override public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) { if (isShowing() || getContentView() == null) { return; } if (Build.VERSION.SDK_INT >= 24) { int[] a = new int[2]; anchor.getLocationInWindow(a); Context context = SAppApplication.getAppContext(); if (context instanceof Activity) { showAtLocation(((Activity) context).getWindow().getDecorView(), Gravity.NO_GRAVITY, xoff, yoff + a[1] + anchor.getHeight()); } else { super.showAsDropDown(anchor, xoff, yoff, gravity); } } else { super.showAsDropDown(anchor, xoff, yoff, gravity); } } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Ghostscript problem report form</title> <!-- $Id: Bug-form.htm,v 1.49 2005/10/20 19:46:23 ray Exp $ --> <!-- Originally: bug-form.txt --> <link rel="stylesheet" type="text/css" href="gs.css" title="Ghostscript Style"> </head> <body> <!-- [1.0 begin visible header] ============================================ --> <!-- [1.1 begin headline] ================================================== --> <h1>Ghostscript problem report form</h1> <!-- [1.1 end headline] ==================================================== --> <!-- [1.0 end visible header] ============================================== --> <!-- [2.0 begin contents] ================================================== --> <p> Before using this form, please read the <a href="Bug-info.htm">instructions</a> for reporting problems. If you are running a developer or beta version of Ghostscript, and you are an experienced tester (for example, if you have been testing Ghostscript for more than a year, or you have already submitted at least two problem reports that we accepted for investigation), you can send an informal report to the place indicated below. Otherwise, please fill out this form completely. Fill out <strong>all</strong> applicable items in this form. <p> Most importantly, you <strong>must</strong> include all data (PostScript files, PDF files, batch/script files, and/or fonts) required to reproduce the problem, either by giving a URL from which we can download the data, or by including the data with the report itself. If you don't include this information, we can't investigate the problem. Please note that the bug reports are publicly archived, so the information you provide will be generally available. If the test data absolutely must remain confidential, please so indicate on the form below and provide an address we may contact privately for the file. <p> Once you have prepared the report, go to <a href="http://bugs.ghostscript.com" class="offsite">http://bugs.ghostscript.com</a>. and follow the instructions there. Data files can be attached to the bug report after the bug is submitted. Use the completed problem reporting form as the body of the Bugzilla submission. If by some reason the Bugzilla doesn't work for you, bugs can be submitted as follows: <ul> <li>If you are running MS-DOS, MS Windows, or OS/2, and you are reasonably sure that the problem is specific to your platform, mail to <a href="mailto:bug-gswin@ghostscript.com">bug-gswin@ghostscript.com</a>. <li>If you are running MacOS, and you are reasonably sure that the problem is specific to the Mac, mail to <a href="mailto:mac-gs@ghostscript.com">mac-gs@ghostscript.com</a>. <li>Otherwise, mail to <a href="mailto:bug-gs@ghostscript.com">bug-gs@ghostscript.com</a>. </ul> <p> Fully completed problem reports help us improve Ghostscript. Thanks in advance. <pre> ------------------------------------------------------------------------ Symptoms: ------------------------------------------------------------------------ Ghostscript version (or include output from "gs -h"): ------------------------------------------------------------------------ Where you got Ghostscript: ------------------------------------------------------------------------ Hardware system you are using (including printer model if the problem involves printing): ------------------------------------------------------------------------ Operating system you are using: ------------------------------------------------------------------------ If you are using X Windows, and your problem involved output to the screen, the output from running xdpyinfo and xwininfo: ------------------------------------------------------------------------ C compiler you are using, including its version, if you compiled Ghostscript yourself: ------------------------------------------------------------------------ If you compiled Ghostscript yourself, changes you made to the makefiles: ------------------------------------------------------------------------ Environment variables: GS_DEVICE GS_FONTPATH GS_LIB GS_OPTIONS ------------------------------------------------------------------------ Command line: ------------------------------------------------------------------------ URL or FTP location of test files (include the data at the end of this form if 500K or less): ------------------------------------------------------------------------ Suggested fix, if any: ------------------------------------------------------------------------ Other comments: </pre> <!-- [2.0 end contents] ==================================================== --> <!-- [3.0 begin visible trailer] =========================================== --> <hr> <p> <small>Copyright &copy; 1996, 2001 artofcode LLC. All rights reserved.</small> <p> <small>This file is part of AFPL Ghostscript. See the <a href="Public.htm">Aladdin Free Public License</a> (the "License") for full details of the terms of using, copying, modifying, and redistributing AFPL Ghostscript.</small> <p> <small>Ghostscript version 8.53, 20 October 2005 <!-- [3.0 end visible trailer] ============================================= --> </body> </html>
{ "pile_set_name": "Github" }
#ifndef BOOST_MPL_PRIOR_HPP_INCLUDED #define BOOST_MPL_PRIOR_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/next_prior.hpp> #endif // BOOST_MPL_PRIOR_HPP_INCLUDED
{ "pile_set_name": "Github" }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Api; using namespace Client; using namespace Common; using namespace Reliability; using namespace ServiceModel; using namespace Transport; IpcHealthReportingClient::IpcHealthReportingClientTransport::IpcHealthReportingClientTransport( Common::ComponentRoot const & root, IpcHealthReportingClient & owner ) : HealthReportingTransport(root) , owner_(owner) { } AsyncOperationSPtr IpcHealthReportingClient::IpcHealthReportingClientTransport::BeginReport( Transport::MessageUPtr && message, Common::TimeSpan timeout, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) { message->Headers.Replace(ActorHeader(owner_.actor_)); return owner_.ipcClient_.BeginRequest( move(message), timeout, callback, parent); } ErrorCode IpcHealthReportingClient::IpcHealthReportingClientTransport::EndReport( AsyncOperationSPtr const & operation, __out Transport::MessageUPtr & reply) { return owner_.ipcClient_.EndRequest(operation, reply); } IpcHealthReportingClient::IpcHealthReportingClient( Common::ComponentRoot const & root, Transport::IpcClient & ipcClient, bool enableMaxNumberOfReportThrottle, std::wstring const & traceContext, Transport::Actor::Enum actor, bool isEnabled) : Common::FabricComponent() , Common::RootedObject(root) , ipcClient_(ipcClient) , healthClient_(nullptr) , enableMaxNumberOfReportThrottle(enableMaxNumberOfReportThrottle) , traceContext_(traceContext) , actor_(actor) , isEnabled_(isEnabled) { } IpcHealthReportingClient::~IpcHealthReportingClient() { } Common::ErrorCode IpcHealthReportingClient::OnOpen() { healthClientTransport_ = make_unique<IpcHealthReportingClientTransport>(get_Root(), *this); healthClient_ = make_shared<HealthReportingComponent>(*healthClientTransport_,traceContext_,enableMaxNumberOfReportThrottle); return healthClient_->Open(); } Common::ErrorCode IpcHealthReportingClient::OnClose() { if (healthClient_) { return healthClient_->Close(); } return ErrorCodeValue::Success; } void IpcHealthReportingClient::OnAbort() { auto result = OnClose(); } Common::ErrorCode IpcHealthReportingClient::AddReport( HealthReport && healthReport, HealthReportSendOptionsUPtr && sendOptions) { ErrorCode error; if (isEnabled_) { if (IsOpened()) { return healthClient_->AddHealthReport(move(healthReport), move(sendOptions)); } return ErrorCodeValue::InvalidState; } return error; } Common::ErrorCode IpcHealthReportingClient::AddReports( std::vector<ServiceModel::HealthReport> && healthReports, HealthReportSendOptionsUPtr && sendOptions) { ErrorCode error; if (isEnabled_) { if (IsOpened()) { return healthClient_->AddHealthReports(move(healthReports), move(sendOptions)); } return ErrorCodeValue::InvalidState; } return error; }
{ "pile_set_name": "Github" }
#source: main1.s #source: a.s #ld: -m mmo -e a #error: bad symbol definition: `Main' set to
{ "pile_set_name": "Github" }
#region Copyright Syncfusion Inc. 2001-2020. // Copyright Syncfusion Inc. 2001-2020. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SampleBrowser.SfStepProgressBar.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Syncfusion Inc.")] [assembly: AssemblyProduct("SampleBrowser.SfStepProgressBar.iOS")] [assembly: AssemblyCopyright("Copyright © 2001-2020 Syncfusion Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "pile_set_name": "Github" }
/// @ref gtc_reciprocal /// @file glm/gtc/reciprocal.inl #include "../trigonometric.hpp" #include <limits> namespace glm { // sec template<typename genType> GLM_FUNC_QUALIFIER genType sec(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'sec' only accept floating-point values"); return genType(1) / glm::cos(angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> sec(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'sec' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(sec, x); } // csc template<typename genType> GLM_FUNC_QUALIFIER genType csc(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'csc' only accept floating-point values"); return genType(1) / glm::sin(angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> csc(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'csc' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(csc, x); } // cot template<typename genType> GLM_FUNC_QUALIFIER genType cot(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'cot' only accept floating-point values"); genType const pi_over_2 = genType(3.1415926535897932384626433832795 / 2.0); return glm::tan(pi_over_2 - angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> cot(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'cot' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(cot, x); } // asec template<typename genType> GLM_FUNC_QUALIFIER genType asec(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'asec' only accept floating-point values"); return acos(genType(1) / x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> asec(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'asec' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(asec, x); } // acsc template<typename genType> GLM_FUNC_QUALIFIER genType acsc(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'acsc' only accept floating-point values"); return asin(genType(1) / x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> acsc(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'acsc' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(acsc, x); } // acot template<typename genType> GLM_FUNC_QUALIFIER genType acot(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'acot' only accept floating-point values"); genType const pi_over_2 = genType(3.1415926535897932384626433832795 / 2.0); return pi_over_2 - atan(x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> acot(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'acot' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(acot, x); } // sech template<typename genType> GLM_FUNC_QUALIFIER genType sech(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'sech' only accept floating-point values"); return genType(1) / glm::cosh(angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> sech(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'sech' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(sech, x); } // csch template<typename genType> GLM_FUNC_QUALIFIER genType csch(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'csch' only accept floating-point values"); return genType(1) / glm::sinh(angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> csch(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'csch' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(csch, x); } // coth template<typename genType> GLM_FUNC_QUALIFIER genType coth(genType angle) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'coth' only accept floating-point values"); return glm::cosh(angle) / glm::sinh(angle); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> coth(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'coth' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(coth, x); } // asech template<typename genType> GLM_FUNC_QUALIFIER genType asech(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'asech' only accept floating-point values"); return acosh(genType(1) / x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> asech(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'asech' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(asech, x); } // acsch template<typename genType> GLM_FUNC_QUALIFIER genType acsch(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'acsch' only accept floating-point values"); return acsch(genType(1) / x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> acsch(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'acsch' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(acsch, x); } // acoth template<typename genType> GLM_FUNC_QUALIFIER genType acoth(genType x) { GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'acoth' only accept floating-point values"); return atanh(genType(1) / x); } template<length_t L, typename T, precision P, template<length_t, typename, precision> class vecType> GLM_FUNC_QUALIFIER vecType<L, T, P> acoth(vecType<L, T, P> const & x) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'acoth' only accept floating-point inputs"); return detail::functor1<L, T, T, P>::call(acoth, x); } }//namespace glm
{ "pile_set_name": "Github" }
exports.fetch = (store, actionData) -> store.set 'accounts', actionData exports.unbind = (store, actionData) -> store.update 'accounts', (accounts) -> accounts.filterNot (account) -> account.get('login') is actionData.get('refer') exports.unbindEmail = (store, actionData) -> store.update 'accounts', (accounts) -> accounts.filterNot (account) -> account.get('login') is 'email' exports.bind = (store, newBinding) -> targetBinding = store.get('accounts').find (binding) -> binding.get('refer') is newBinding.get('refer') store.update 'accounts', (cursor) -> if targetBinding? cursor.map (binding) -> if binding.get('refer') is newBinding.get('refer') binding.merge newBinding else binding else cursor.push newBinding
{ "pile_set_name": "Github" }
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file file.hpp * \author Andrey Semashev * \date 16.05.2008 * * The header contains implementation of convenience functions for enabling logging to a file. */ #ifndef BOOST_LOG_UTILITY_SETUP_FILE_HPP_INCLUDED_ #define BOOST_LOG_UTILITY_SETUP_FILE_HPP_INCLUDED_ #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/parameter/parameters.hpp> // for is_named_argument #include <boost/preprocessor/comparison/greater.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_params.hpp> #include <boost/preprocessor/repetition/repeat_from_to.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/detail/sink_init_helpers.hpp> #include <boost/log/detail/parameter_tools.hpp> #include <boost/log/core/core.hpp> #ifndef BOOST_LOG_NO_THREADS #include <boost/log/sinks/sync_frontend.hpp> #else #include <boost/log/sinks/unlocked_frontend.hpp> #endif #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/keywords/scan_method.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #ifndef BOOST_LOG_DOXYGEN_PASS #ifndef BOOST_LOG_NO_THREADS #define BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL sinks::synchronous_sink #else #define BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL sinks::unlocked_sink #endif #endif // BOOST_LOG_DOXYGEN_PASS namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { //! The function creates a file collector according to the specified arguments template< typename ArgsT > inline shared_ptr< sinks::file::collector > setup_file_collector(ArgsT const&, mpl::true_ const&) { return shared_ptr< sinks::file::collector >(); } template< typename ArgsT > inline shared_ptr< sinks::file::collector > setup_file_collector(ArgsT const& args, mpl::false_ const&) { return sinks::file::make_collector(args); } //! The function constructs the sink and adds it to the core template< typename ArgsT > shared_ptr< BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL< sinks::text_file_backend > > add_file_log(ArgsT const& args) { typedef sinks::text_file_backend backend_t; shared_ptr< backend_t > pBackend = boost::make_shared< backend_t >(args); shared_ptr< sinks::file::collector > pCollector = aux::setup_file_collector(args, typename is_void< typename parameter::binding< ArgsT, keywords::tag::target, void >::type >::type()); if (pCollector) { pBackend->set_file_collector(pCollector); pBackend->scan_for_files(args[keywords::scan_method | sinks::file::scan_matching]); } shared_ptr< BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL< backend_t > > pSink = boost::make_shared< BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL< backend_t > >(pBackend); aux::setup_filter(*pSink, args, typename is_void< typename parameter::binding< ArgsT, keywords::tag::filter, void >::type >::type()); aux::setup_formatter(*pSink, args, typename is_void< typename parameter::binding< ArgsT, keywords::tag::format, void >::type >::type()); core::get()->add_sink(pSink); return pSink; } //! The function wraps the argument into a file_name named argument, if needed template< typename T > inline T const& wrap_file_name(T const& arg, mpl::true_) { return arg; } template< typename T > inline typename parameter::aux::tag< keywords::tag::file_name, T const >::type wrap_file_name(T const& arg, mpl::false_) { return keywords::file_name = arg; } } // namespace aux #ifndef BOOST_LOG_DOXYGEN_PASS #define BOOST_LOG_INIT_LOG_TO_FILE_INTERNAL(z, n, data)\ template< BOOST_PP_ENUM_PARAMS(n, typename T) >\ inline shared_ptr< BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL< sinks::text_file_backend > > add_file_log(BOOST_PP_ENUM_BINARY_PARAMS(n, T, const& arg))\ {\ return aux::add_file_log((\ aux::wrap_file_name(arg0, typename parameter::aux::is_named_argument< T0 >::type())\ BOOST_PP_COMMA_IF(BOOST_PP_GREATER(n, 1))\ BOOST_PP_ENUM_SHIFTED_PARAMS(n, arg)\ ));\ } BOOST_PP_REPEAT_FROM_TO(1, BOOST_LOG_MAX_PARAMETER_ARGS, BOOST_LOG_INIT_LOG_TO_FILE_INTERNAL, ~) #undef BOOST_LOG_INIT_LOG_TO_FILE_INTERNAL #else // BOOST_LOG_DOXYGEN_PASS /*! * The function initializes the logging library to write logs to a file stream. * * \param args A number of named arguments. The following parameters are supported: * \li \c file_name The file name or its pattern. This parameter is mandatory. * \li \c open_mode The mask that describes the open mode for the file. See <tt>std::ios_base::openmode</tt>. * \li \c rotation_size The size of the file at which rotation should occur. See <tt>basic_text_file_backend</tt>. * \li \c time_based_rotation The predicate for time-based file rotations. See <tt>basic_text_file_backend</tt>. * \li \c auto_flush A boolean flag that shows whether the sink should automatically flush the file * after each written record. * \li \c target The target directory to store rotated files in. See <tt>sinks::file::make_collector</tt>. * \li \c max_size The maximum total size of rotated files in the target directory. See <tt>sinks::file::make_collector</tt>. * \li \c min_free_space Minimum free space in the target directory. See <tt>sinks::file::make_collector</tt>. * \li \c max_files The maximum total number of rotated files in the target directory. See <tt>sinks::file::make_collector</tt>. * \li \c scan_method The method of scanning the target directory for log files. See <tt>sinks::file::scan_method</tt>. * \li \c filter Specifies a filter to install into the sink. May be a string that represents a filter, * or a filter lambda expression. * \li \c format Specifies a formatter to install into the sink. May be a string that represents a formatter, * or a formatter lambda expression (either streaming or Boost.Format-like notation). * \return Pointer to the constructed sink. */ template< typename... ArgsT > shared_ptr< BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL< sinks::text_file_backend > > add_file_log(ArgsT... const& args); #endif // BOOST_LOG_DOXYGEN_PASS BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #undef BOOST_LOG_FILE_SINK_FRONTEND_INTERNAL #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_UTILITY_SETUP_FILE_HPP_INCLUDED_
{ "pile_set_name": "Github" }
## DESCRIPTION ## ## ENDDESCRIPTION ## DBsubject(Algebra) ## DBchapter(Transformations of functions and graphs) ## DBsection(Symmetry: even, odd, neither) ## Date(06/02/2017) ## Institution(Red Rocks Community College, Colorado Community College System) ## Author(Brenda Forland) ## MO(1) ## KEYWORDS('algebra') ########################### # Initialization DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "parserPopUp.pl", "AnswerFormatHelp.pl", "PGML.pl", "PGcourse.pl", ); TEXT(beginproblem()); $showPartialCorrectAnswers = 1; ########################### # Setup Context("Numeric"); $a = non_zero_random(2,6,2); $b = non_zero_random(-10,10,1); $f = Formula("$b*x^$a")->reduce; $ans1 = $f; $ans2 = Formula("-$b*x^$a")->reduce; $popup = PopUp( ["?","odd","even","neither"], "even", ); ########################### # Main text BEGIN_PGML Let [``f(x) = [$f]``]. Find [``f(-x)``] and [``-f(x)``]. Use them to determine whether or not [``f(x)``] is even, odd, or neither. [` f(-x) = `] [_______________]{$ans1} [@ AnswerFormatHelp("formulas") @]* [` -f(x) = `] [_______________]{$ans2} [@ AnswerFormatHelp("formulas") @]* Is [``f(x)``] odd, even, or neither? [@ $popup->menu() @]* END_PGML ############################ # Answer evaluation install_problem_grader(~~&std_problem_grader); $showPartialCorrectAnswers = 0; ANS( $popup->cmp() ); ############################ # Solution #BEGIN_PGML_SOLUTION #Solution explanation goes here. #END_PGML_SOLUTION COMMENT('MathObject version. Uses PGML.'); ENDDOCUMENT();
{ "pile_set_name": "Github" }
.container { background: linear-gradient(200deg, #42275a, #734b6d); height: 100%; display: flex; flex-direction: column; } .table { text-align: left; min-width: 600px; } .table th:nth-child(1) { width: 80%; } .table th:nth-child(2) { width: 20%; } .table td { padding: 10px; padding-left: 0; } .table td:last-child { padding-right: 0; } .peerId { vertical-align: bottom; width: 100%; max-width: 400px; border-color: rgba(255, 255, 255, 0.3); } .discovery { margin-top: 2rem; max-width: 600px; } .header { composes: h2 from '~styles/typography.css'; margin-bottom: 1rem; } .discovery img { display: block; margin-top: 1rem; filter: invert(1); height: 2rem; }
{ "pile_set_name": "Github" }
#import "GPUImageTwoInputFilter.h" @interface GPUImageHardLightBlendFilter : GPUImageTwoInputFilter { } @end
{ "pile_set_name": "Github" }
--- title: Property Page Callback Function description: Property Page Callback Function ms.assetid: 3f4d7247-2a12-4889-9fc0-a28f58046c7b keywords: - device property pages WDK device installations , callback functions - property pages WDK device installations , callback functions - custom property pages WDK device installations , callback functions - callback functions WDK property page - PSPCB_CREATE - PSPCB_RELEASE ms.date: 04/20/2017 ms.localizationpriority: medium --- # Property Page Callback Function When a provider creates a property page for its device or device class, it supplies a pointer to a callback function. The callback function is called one time when the property page is created and again when it is about to be destroyed. The callback is a **PropSheetPageProc** function that is described in the Windows SDK documentation. This function must be able to handle the PSPCB_CREATE and PSPCB_RELEASE actions. The callback is called with a PSPCB_CREATE message when a property page is being created. In response to this message, the callback can allocate memory for data that is associated with the page. The function should return **TRUE** to continue to create the page or **FALSE** if the page should not be created. Property pages for a device are destroyed when the user clicks **OK** or **Cancel** on the page's dialog box or clicks **Uninstall** on the **Drivers** tab. When a property page is destroyed, the callback is called with a PSPCB_RELEASE message. The function should free any data that was allocated when the property page was created. Typically, this involves freeing the data referenced by the **lParam** member of the PROPSHEETPAGE structure. The return value is ignored when the page is being destroyed.
{ "pile_set_name": "Github" }
/** This file is part of sgm. (https://github.com/dhernandez0/sgm). Copyright (c) 2016 Daniel Hernandez Juarez. sgm is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. sgm is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with sgm. If not, see <http://www.gnu.org/licenses/>. **/ #include "median_filter.h" __global__ void MedianFilter3x3(const uint8_t* __restrict__ d_input, uint8_t* __restrict__ d_out, const uint32_t rows, const uint32_t cols) { MedianFilter<3>(d_input, d_out, rows, cols); }
{ "pile_set_name": "Github" }
name: deploy on: push: branches: - master jobs: deploy: name: docs.vapor.codes runs-on: ubuntu-latest steps: - name: Deploy docs uses: appleboy/ssh-action@master with: host: vapor.codes username: vapor key: ${{ secrets.VAPOR_CODES_SSH_KEY }} script: ./github-actions/deploy-docs.sh
{ "pile_set_name": "Github" }
# These are supported funding model platforms custom: ['https://space.bilibili.com/433584098']
{ "pile_set_name": "Github" }
package com.foxinmy.weixin4j.type; /** * 消息加密类型 * * @className EncryptType * @author jinyu(foxinmy@gmail.com) * @date 2014年11月23日 * @since JDK 1.6 * @see */ public enum EncryptType { /** * 明文模式 */ RAW, /** * 密文模式 */ AES; }
{ "pile_set_name": "Github" }
LEVEL = ../../../../make SWIFT_SOURCES := main.swift SWIFT_OBJC_INTEROP := 1 include $(LEVEL)/Makefile.rules
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_MINIMAL #define BOOST_SPIRIT_INCLUDE_CLASSIC_MINIMAL #include <boost/spirit/home/classic/debug/minimal.hpp> #endif
{ "pile_set_name": "Github" }
#include "su.h" #include "segy.h" /*********************** self documentation *****************************/ string sdoc = " \n" " MUTEPICK - Segy-data Mute (Top/Bottom) PICK on X-Window \n" " \n" " mutepick <stdin [optional parameters] \n" " \n" "X Functionality: \n" "Button 1 Zoom with rubberband box \n" "Button 2 Show mouse (x1,x2) location while pressed \n" "Button 3 The same as a or A (depends on previous key) \n" "Q key Quit (can also use Motif Action button) \n" "a key Append current mouse location to end of \n" " the top-zone mute picks \n" "i key Insert current mouse location in middle of \n" " the top-zone mute picks \n" "d key Delete current mouse location from \n" " the top-zone mute picks \n" "A key Append current mouse location to end of \n" " the bottom-zone mute picks \n" "I key Insert current mouse location in middle of \n" " the bottom-zone mute picks \n" "D key Delete current mouse location from \n" " the bottom-zone mute picks \n" "p key Display picks \n" "s key Append saved MUTE picks to pick file \n" "\n" "Optional parameters: \n" "mpicks=stderr file to save MUTE picks (picks will be appended to \n" " end of the file. (default: screen output) \n" "d1= sampling interval \n" "f1= first sampling time/depth \n" "d2= trace interval \n" "f2= first trace position \n" "All the above four parameter default from trace headers) \n" "panel=1 panel to pick \n" "ntpp=fold or ntrpr number of traces per panel (=fold for cdp input \n" " =ntrpr for other input --- number of traces per \n" " record) \n" "dtype=0 display type (0=variable density; 1=variable area) \n" "itoff=0 output offset-time when itoff=0; output time-offset when \n" " itoff=1 \n" "perc=100.0 percentile used to determine clip\n" "clip=(perc percentile) clip used to determine bclip and wclip\n" "bperc=perc percentile for determining black clip value\n" "wperc=100.0-perc percentile for determining white clip value\n" "bclip=clip data values outside of [bclip,wclip] are clipped\n" "wclip=-clip data values outside of [bclip,wclip] are clipped\n" "cmap=gray gray, hue, or default colormaps may be specified\n" "verbose=1 =1 for info printed on stderr (0 for no info)\n" "xbox=50 x in pixels of upper left corner of window\n" "ybox=50 y in pixels of upper left corner of window\n" "wbox=550 width in pixels of window\n" "hbox=700 height in pixels of window\n" "x1beg=x1min value at which axis 1 begins\n" "x1end=x1max value at which axis 1 ends\n" "d1num=0.0 numbered tic interval on axis 1 (0.0 for automatic)\n" "f1num=x1min first numbered tic on axis 1 (used if d1num not 0.0)\n" "n1tic=1 number of tics per numbered tic on axis 1\n" "grid1=none grid lines on axis 1 - none, dot, dash, or solid\n" "label1=time (or depth) label on axis 1\n" "x2beg=x2min value at which axis 2 begins\n" "x2end=x2max value at which axis 2 ends\n" "d2num=0.0 numbered tic interval on axis 2 (0.0 for automatic)\n" "f2num=x2min first numbered tic on axis 2 (used if d2num not 0.0)\n" "n2tic=1 number of tics per numbered tic on axis 2\n" "grid2=none grid lines on axis 2 - none, dot, dash, or solid\n" "label2=offset (or cdp) label on axis 2\n" "labelfont=Erg14 font name for axes labels\n" "title=Mute Picking title of plot\n" "titlefont=Rom22 font name for title\n" "labelcolor=blue color for axes labels\n" "titlecolor=red color for title\n" "gridcolor=blue color for grid lines\n" "topmutecolor=blue color for top-zone mute picks \n" "bottommutecolor=red color for bottom-zone mute picks \n" "style=seismic normal (axis 1 horizontal, axis 2 vertical) or\n" "labelfont=Erg14 font name for axes labels\n" " seismic (axis 1 vertical, axis 2 horizontal)\n" "Following four parameters are for dtype=1 \n" "xcur=1.0 wiggle excursion in traces corresponding to clip\n" "wt=1 =0 for no wiggle-trace; =1 for wiggle-trace\n" "va=1 =0 for no variable-area; =1 for variable-area fill\n" "nbpi=72 number of bits per inch at which to rasterize\n" "\n" "NOTE: \n" "Mute Picks Output Card Format: \n" "1---5---10---15----21----27----33----39----45----51----57----63----69----75\n" "MUTE ppos px1 tp1 bt1 px2 tp2 bp2 px3 tp3 bt3 \n" "\n" "where ppos indicates mute pick panel position (cdp or offset) \n" " pxi, i=1,2,..., are mute time x position (offset or cdp) \n" " tpi, i=1,2,..., are mute time at top-mute zone \n" " bti, i=1,2,..., are mute time at bottom-mute zone \n" "\n" " author: Zhiming Li 9/12/91 \n" ; /**************** end self doc *******************************************/ segytrace tr; segybhdr bh; segychdr ch; main(int argc, char **argv) { char plotcmd[BUFSIZ]; /* build ximage command for popen */ float *trbuf; /* trace buffer */ FILE *datafp; /* fp for trace data file */ FILE *plotfp; /* fp for plot data */ int nt; /* number of samples on trace */ int ntr; /* number of traces */ float d1; /* time/depth sample rate */ float d2; /* trace/dx sample rate */ float f1; /* tmin/zmin */ float f2; /* tracemin/xmin */ bool seismic; /* is this seismic data? */ int panel; /* panel to pick */ int dtype; /* type of display */ int ppos; /* position of the panel */ FILE *infp=stdin; int n3,n2,n1; long long lpos; /* Initialize */ initargs(argc, argv); askdoc(1); /* Get info from headers and first trace */ file2g(infp); fgethdr(infp,&ch,&bh); n1 = bh.hns; if(!getparint("ntpp",&n2)) { if (bh.tsort==2) { n2 = bh.fold; } else { n2 = bh.ntrpr; } } if (!fgettr(infp,&tr)) err("can't get first trace"); nt = tr.ns; if ( n1!=nt ) warn("samples/trace in bhdr and trhdr different; trhdr used! \n"); n1 = nt; lpos = 0; fseek64(infp,lpos,2); n3=(ftell(infp)-EBCBYTES-BNYBYTES)/(n1*sizeof(float)+HDRBYTES)/n2; if(n3==0) { n3=1; n2=(ftell(infp)-EBCBYTES-BNYBYTES)/(n1*sizeof(float)+HDRBYTES); warn("less traces were found in input! \n"); } fseek64(infp,lpos,0); seismic = (tr.trid == 0 || tr.trid == TREAL); if (!getparint("panel", &panel)) panel=1; if (!getparint("dtype", &dtype)) dtype=0; if (!getparfloat("d1", &d1)) { if (seismic) { /* sampling interval in ms or in m (ft) */ if ( tr.dz!=0. ) { d1 = tr.dz; } else if (tr.dt) { d1 = (float) tr.dt / 1000.0; if (tr.dt<1000) d1 = tr.dt; } else { d1 = 0.004 * 1000.; warn("tr.dt not set, assuming dt=4"); } } else { /* non-seismic data */ if (tr.d1) { d1 = tr.d1; } else { d1 = 1.0; warn("tr.d1 not set, assuming d1=1.0"); } } } if (!getparfloat("d2", &d2)) { if(bh.tsort==2) { d2 = tr.offset; } else { d2 = tr.cdp; } } if (!getparfloat("f1", &f1)) { if (seismic) { f1 = (tr.delrt) ? (float) tr.delrt/1000.0 : 0.0; if(tr.delrt<1000) f1=tr.delrt; if(tr.dz!=0.) f1=tr.fz; } else { f1 = (tr.f1) ? tr.f1 : 0.0; } } if (!getparfloat("f2", &f2)) { if (bh.tsort==2) { f2 = tr.offset; } else { f2 = tr.cdp; } } /* Allocate trace buffer */ trbuf = ealloc1float(nt); /* Create temporary "file" to hold data */ datafp = etempfile(NULL); /* Loop over input traces & put them into the data file */ ntr = 0; lpos = (panel-1)*n2; lpos = lpos*(n1*sizeof(float)+HDRBYTES); lpos = lpos + EBCBYTES+BNYBYTES; fseek64(infp,lpos,0); for(ntr=0;ntr<n2;ntr++) { if(!fgettr(infp,&tr)) err("get trace error \n"); efwrite(tr.data, FSIZE, nt, datafp); if(ntr==1) { if (bh.tsort==2) { if(!getparfloat("d2",&d2)) d2 = tr.offset-d2; if (!getparint("ppos", &ppos)) ppos = tr.cdp; } else { if(!getparfloat("d2",&d2)) d2 = tr.cdp-d2; if (!getparint("ppos", &ppos)) ppos = tr.offset; } } } /* Set up xipick or xwpick command line */ if ( dtype == 0 ) { sprintf(plotcmd, "mipick n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f ppos=%d", n1, n2, d1, d2, f1, f2, ppos); } else { sprintf(plotcmd, "mwpick n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f ppos=%d", n1, n2, d1, d2, f1, f2, ppos); } for (--argc, ++argv; argc; --argc, ++argv) { if (strncmp(*argv, "d1=", 3) && /* skip those already set */ strncmp(*argv, "d2=", 3) && strncmp(*argv, "f1=", 3) && strncmp(*argv, "f2=", 3)) { strcat(plotcmd, " "); /* put a space between args */ strcat(plotcmd, "\""); /* user quotes are stripped */ strcat(plotcmd, *argv); /* add the arg */ strcat(plotcmd, "\""); /* user quotes are stripped */ } } /* Open pipe; read data to buf; write buf to plot program */ plotfp = epopen(plotcmd, "w"); rewind(datafp); { register int itr; for (itr = 0; itr < ntr; ++itr) { efread (trbuf, FSIZE, nt, datafp); efwrite(trbuf, FSIZE, nt, plotfp); } } /* Clean up */ epclose(plotfp); efclose(datafp); return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
import { component } from 'picoapp' import { addVariant } from '@/lib/cart.js' export default component((node, ctx) => { const json = JSON.parse(node.querySelector('.js-product-json').innerHTML) const form = node.querySelector('form') const { selectedOrFirstAvailableVariant, product } = json let currentVariant = product.variants.filter(v => v.id === selectedOrFirstAvailableVariant)[0] form.addEventListener('submit', e => { e.preventDefault() currentVariant = product.variants.filter(v => v.id === parseInt(form.elements.id.value))[0] addVariant(currentVariant, form.elements.quantity.value) console.log(json) }) })
{ "pile_set_name": "Github" }
declare namespace jdk { namespace nashorn { namespace internal { namespace runtime { namespace regexp { namespace joni { namespace ast { abstract class StateNode extends jdk.nashorn.internal.runtime.regexp.joni.ast.Node implements jdk.nashorn.internal.runtime.regexp.joni.constants.NodeStatus { protected state: int public constructor() public toString(arg0: int): string public stateToString(): string public isMinFixed(): boolean public setMinFixed(): void public isMaxFixed(): boolean public setMaxFixed(): void public isCLenFixed(): boolean public setCLenFixed(): void public isMark1(): boolean public setMark1(): void public isMark2(): boolean public setMark2(): void public clearMark2(): void public isMemBackrefed(): boolean public setMemBackrefed(): void public isStopBtSimpleRepeat(): boolean public setStopBtSimpleRepeat(): void public isRecursion(): boolean public setRecursion(): void public isCalled(): boolean public setCalled(): void public isAddrFixed(): boolean public setAddrFixed(): void public isInRepeat(): boolean public setInRepeat(): void public isNestLevel(): boolean public setNestLevel(): void public isByNumber(): boolean public setByNumber(): void public static class: java.lang.Class<any> } } } } } } } }
{ "pile_set_name": "Github" }
--- description: "Current (MDX)" title: "Current (MDX) | Microsoft Docs" ms.date: 06/04/2018 ms.prod: sql ms.technology: analysis-services ms.custom: mdx ms.topic: reference ms.author: owend ms.reviewer: owend author: minewiskan --- # Current (MDX) Returns the current tuple from a set during iteration. ## Syntax ``` Set_Expression.Current ``` ## Arguments *Set_Expression* A valid Multidimensional Expressions (MDX) expression that returns a set. ## Remarks At each step during an iteration, the tuple being operated upon is the current tuple. The **Current** function returns that tuple. This function is only valid during an iteration over a set. MDX functions that iterate through a set include the [Generate](../mdx/generate-mdx.md) function. > [!NOTE] > This function only works with sets that are named, either using a set alias or by defining a named set. ## Examples The following example shows how to use the **Current** function inside **Generate**: `WITH` `//Creates a set of tuples consisting of all Calendar Years crossjoined with` `//all Product Categories` `SET MyTuples AS CROSSJOIN(` `[Date].[Calendar Year].[Calendar Year].MEMBERS,` `[Product].[Category].[Category].MEMBERS)` `//Iterates through each tuple in the set and returns the name of the Calendar` `//Year in each tuple` `MEMBER MEASURES.CURRENTDEMO AS` `GENERATE(MyTuples, MyTuples.CURRENT.ITEM(0).NAME, ", ")` `SELECT MEASURES.CURRENTDEMO ON 0` `FROM [Adventure Works]` ## See Also [MDX Function Reference &#40;MDX&#41;](../mdx/mdx-function-reference-mdx.md)
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='UTF-8'?> <!-- Schema file written by PDE --> <schema targetNamespace="org.python.pydev"> <annotation> <appInfo> <meta.schema plugin="org.python.pydev" id="pydev_preferences_provider" name="org.python.pydev.pydev_preferences_provider"/> </appInfo> <documentation> [Enter description of this extension point.] </documentation> </annotation> <element name="extension"> <complexType> <sequence> <element ref="preferences_provider_participant" minOccurs="0" maxOccurs="unbounded"/> </sequence> <attribute name="point" type="string" use="required"> <annotation> <documentation> a fully qualified identifier of the target extension point </documentation> </annotation> </attribute> <attribute name="id" type="string"> <annotation> <documentation> an optional identifier of the extension instance </documentation> </annotation> </attribute> <attribute name="name" type="string"> <annotation> <documentation> an optional name of the extension instance </documentation> <appInfo> <meta.attribute translatable="true"/> </appInfo> </annotation> </attribute> </complexType> </element> <element name="preferences_provider_participant"> <complexType> <sequence> </sequence> <attribute name="class" type="string" use="required"> <annotation> <documentation> </documentation> <appInfo> <meta.attribute translatable="true"/> </appInfo> </annotation> </attribute> </complexType> </element> <annotation> <appInfo> <meta.section type="since"/> </appInfo> <documentation> [Enter the first release in which this extension point appears.] </documentation> </annotation> <annotation> <appInfo> <meta.section type="examples"/> </appInfo> <documentation> [Enter extension point usage example here.] </documentation> </annotation> <annotation> <appInfo> <meta.section type="apiInfo"/> </appInfo> <documentation> [Enter API information here.] </documentation> </annotation> <annotation> <appInfo> <meta.section type="implementation"/> </appInfo> <documentation> [Enter information about supplied implementation of this extension point.] </documentation> </annotation> <annotation> <appInfo> <meta.section type="copyright"/> </appInfo> <documentation> </documentation> </annotation> </schema>
{ "pile_set_name": "Github" }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import streamAdapters from './io/adapters'; import { Builder } from './builder/index'; import { RecordBatchReader } from './ipc/reader'; import { RecordBatchWriter } from './ipc/writer'; import { toDOMStream } from './io/whatwg/iterable'; import { builderThroughDOMStream } from './io/whatwg/builder'; import { recordBatchReaderThroughDOMStream } from './io/whatwg/reader'; import { recordBatchWriterThroughDOMStream } from './io/whatwg/writer'; streamAdapters.toDOMStream = toDOMStream; Builder['throughDOM'] = builderThroughDOMStream; RecordBatchReader['throughDOM'] = recordBatchReaderThroughDOMStream; RecordBatchWriter['throughDOM'] = recordBatchWriterThroughDOMStream; export { ArrowType, DateUnit, IntervalUnit, MessageHeader, MetadataVersion, Precision, TimeUnit, Type, UnionMode, BufferType, Data, DataType, Null, Bool, Int, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, Float, Float16, Float32, Float64, Utf8, Binary, FixedSizeBinary, Date_, DateDay, DateMillisecond, Timestamp, TimestampSecond, TimestampMillisecond, TimestampMicrosecond, TimestampNanosecond, Time, TimeSecond, TimeMillisecond, TimeMicrosecond, TimeNanosecond, Decimal, List, Struct, Union, DenseUnion, SparseUnion, Dictionary, Interval, IntervalDayTime, IntervalYearMonth, FixedSizeList, Map_, Table, Column, Schema, Field, Visitor, Vector, BaseVector, BinaryVector, BoolVector, Chunked, DateVector, DateDayVector, DateMillisecondVector, DecimalVector, DictionaryVector, FixedSizeBinaryVector, FixedSizeListVector, FloatVector, Float16Vector, Float32Vector, Float64Vector, IntervalVector, IntervalDayTimeVector, IntervalYearMonthVector, IntVector, Int8Vector, Int16Vector, Int32Vector, Int64Vector, Uint8Vector, Uint16Vector, Uint32Vector, Uint64Vector, ListVector, MapVector, NullVector, StructVector, TimestampVector, TimestampSecondVector, TimestampMillisecondVector, TimestampMicrosecondVector, TimestampNanosecondVector, TimeVector, TimeSecondVector, TimeMillisecondVector, TimeMicrosecondVector, TimeNanosecondVector, UnionVector, DenseUnionVector, SparseUnionVector, Utf8Vector, ByteStream, AsyncByteStream, AsyncByteQueue, ReadableSource, WritableSink, RecordBatchReader, RecordBatchFileReader, RecordBatchStreamReader, AsyncRecordBatchFileReader, AsyncRecordBatchStreamReader, RecordBatchWriter, RecordBatchFileWriter, RecordBatchStreamWriter, RecordBatchJSONWriter, MessageReader, AsyncMessageReader, JSONMessageReader, Message, RecordBatch, ArrowJSONLike, FileHandle, Readable, Writable, ReadableWritable, ReadableDOMStreamOptions, DataFrame, FilteredDataFrame, CountByResult, BindFunc, NextFunc, predicate, util, Builder, BinaryBuilder, BoolBuilder, DateBuilder, DateDayBuilder, DateMillisecondBuilder, DecimalBuilder, DictionaryBuilder, FixedSizeBinaryBuilder, FixedSizeListBuilder, FloatBuilder, Float16Builder, Float32Builder, Float64Builder, IntervalBuilder, IntervalDayTimeBuilder, IntervalYearMonthBuilder, IntBuilder, Int8Builder, Int16Builder, Int32Builder, Int64Builder, Uint8Builder, Uint16Builder, Uint32Builder, Uint64Builder, ListBuilder, MapBuilder, NullBuilder, StructBuilder, TimestampBuilder, TimestampSecondBuilder, TimestampMillisecondBuilder, TimestampMicrosecondBuilder, TimestampNanosecondBuilder, TimeBuilder, TimeSecondBuilder, TimeMillisecondBuilder, TimeMicrosecondBuilder, TimeNanosecondBuilder, UnionBuilder, DenseUnionBuilder, SparseUnionBuilder, Utf8Builder, } from './Arrow';
{ "pile_set_name": "Github" }
// Copyright Oliver Kowalke 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_OBJECT_H #define BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_OBJECT_H #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/cstdint.hpp> #include <boost/exception_ptr.hpp> #include <boost/move/move.hpp> #include <boost/coroutine/detail/config.hpp> #include <boost/coroutine/detail/coroutine_context.hpp> #include <boost/coroutine/detail/flags.hpp> #include <boost/coroutine/detail/preallocated.hpp> #include <boost/coroutine/detail/push_coroutine_impl.hpp> #include <boost/coroutine/detail/trampoline_push.hpp> #include <boost/coroutine/exceptions.hpp> #include <boost/coroutine/flags.hpp> #include <boost/coroutine/stack_context.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #if defined(BOOST_MSVC) # pragma warning(push) # pragma warning(disable:4355) #endif namespace boost { namespace coroutines { namespace detail { struct push_coroutine_context { coroutine_context caller; coroutine_context callee; template< typename Coro > push_coroutine_context( preallocated const& palloc, Coro *) : caller(), callee( trampoline_push< Coro >, palloc) {} }; struct push_coroutine_context_void { coroutine_context caller; coroutine_context callee; template< typename Coro > push_coroutine_context_void( preallocated const& palloc, Coro *) : caller(), callee( trampoline_push_void< Coro >, palloc) {} }; template< typename PullCoro, typename R, typename Fn, typename StackAllocator > class push_coroutine_object : private push_coroutine_context, public push_coroutine_impl< R > { private: typedef push_coroutine_context ctx_t; typedef push_coroutine_impl< R > base_t; typedef push_coroutine_object< PullCoro, R, Fn, StackAllocator > obj_t; Fn fn_; stack_context stack_ctx_; StackAllocator stack_alloc_; static void deallocate_( obj_t * obj) { stack_context stack_ctx( obj->stack_ctx_); StackAllocator stack_alloc( obj->stack_alloc_); obj->unwind_stack(); obj->~obj_t(); stack_alloc.deallocate( stack_ctx); } public: #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES push_coroutine_object( Fn fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), fn_( fn), stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} #endif push_coroutine_object( BOOST_RV_REF( Fn) fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES fn_( fn), #else fn_( boost::forward< Fn >( fn) ), #endif stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} void run( R * result) { BOOST_ASSERT( ! base_t::unwind_requested() ); base_t::flags_ |= flag_started; base_t::flags_ |= flag_running; // create push_coroutine typename PullCoro::synth_type b( & this->callee, & this->caller, false, result); PullCoro pull_coro( synthesized_t::syntesized, b); try { fn_( pull_coro); } catch ( forced_unwind const&) {} catch (...) { base_t::except_ = current_exception(); } base_t::flags_ |= flag_complete; base_t::flags_ &= ~flag_running; typename base_t::param_type to; this->callee.jump( this->caller, & to); BOOST_ASSERT_MSG( false, "pull_coroutine is complete"); } void destroy() { deallocate_( this); } }; template< typename PullCoro, typename R, typename Fn, typename StackAllocator > class push_coroutine_object< PullCoro, R &, Fn, StackAllocator > : private push_coroutine_context, public push_coroutine_impl< R & > { private: typedef push_coroutine_context ctx_t; typedef push_coroutine_impl< R & > base_t; typedef push_coroutine_object< PullCoro, R &, Fn, StackAllocator > obj_t; Fn fn_; stack_context stack_ctx_; StackAllocator stack_alloc_; static void deallocate_( obj_t * obj) { stack_context stack_ctx( obj->stack_ctx_); StackAllocator stack_alloc( obj->stack_alloc_); obj->unwind_stack(); obj->~obj_t(); stack_alloc.deallocate( stack_ctx); } public: #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES push_coroutine_object( Fn fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), fn_( fn), stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} #endif push_coroutine_object( BOOST_RV_REF( Fn) fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES fn_( fn), #else fn_( boost::forward< Fn >( fn) ), #endif stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} void run( R * result) { BOOST_ASSERT( ! base_t::unwind_requested() ); base_t::flags_ |= flag_started; base_t::flags_ |= flag_running; // create push_coroutine typename PullCoro::synth_type b( & this->callee, & this->caller, false, result); PullCoro push_coro( synthesized_t::syntesized, b); try { fn_( push_coro); } catch ( forced_unwind const&) {} catch (...) { base_t::except_ = current_exception(); } base_t::flags_ |= flag_complete; base_t::flags_ &= ~flag_running; typename base_t::param_type to; this->callee.jump( this->caller, & to); BOOST_ASSERT_MSG( false, "pull_coroutine is complete"); } void destroy() { deallocate_( this); } }; template< typename PullCoro, typename Fn, typename StackAllocator > class push_coroutine_object< PullCoro, void, Fn, StackAllocator > : private push_coroutine_context_void, public push_coroutine_impl< void > { private: typedef push_coroutine_context_void ctx_t; typedef push_coroutine_impl< void > base_t; typedef push_coroutine_object< PullCoro, void, Fn, StackAllocator > obj_t; Fn fn_; stack_context stack_ctx_; StackAllocator stack_alloc_; static void deallocate_( obj_t * obj) { stack_context stack_ctx( obj->stack_ctx_); StackAllocator stack_alloc( obj->stack_alloc_); obj->unwind_stack(); obj->~obj_t(); stack_alloc.deallocate( stack_ctx); } public: #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES push_coroutine_object( Fn fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), fn_( fn), stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} #endif push_coroutine_object( BOOST_RV_REF( Fn) fn, attributes const& attrs, preallocated const& palloc, StackAllocator const& stack_alloc) BOOST_NOEXCEPT : ctx_t( palloc, this), base_t( & this->caller, & this->callee, stack_unwind == attrs.do_unwind), #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES fn_( fn), #else fn_( boost::forward< Fn >( fn) ), #endif stack_ctx_( palloc.sctx), stack_alloc_( stack_alloc) {} void run() { BOOST_ASSERT( ! base_t::unwind_requested() ); base_t::flags_ |= flag_started; base_t::flags_ |= flag_running; // create push_coroutine typename PullCoro::synth_type b( & this->callee, & this->caller, false); PullCoro push_coro( synthesized_t::syntesized, b); try { fn_( push_coro); } catch ( forced_unwind const&) {} catch (...) { base_t::except_ = current_exception(); } base_t::flags_ |= flag_complete; base_t::flags_ &= ~flag_running; typename base_t::param_type to; this->callee.jump( this->caller, & to); BOOST_ASSERT_MSG( false, "pull_coroutine is complete"); } void destroy() { deallocate_( this); } }; }}} #if defined(BOOST_MSVC) # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_OBJECT_H
{ "pile_set_name": "Github" }
# Copyright 2012 Red Hat, Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Functional test cases for glance-manage""" import os import sys from oslo_config import cfg from oslo_db import options as db_options from glance.common import utils from glance.db import migration as db_migration from glance.db.sqlalchemy import alembic_migrations from glance.db.sqlalchemy.alembic_migrations import data_migrations from glance.db.sqlalchemy import api as db_api from glance.tests import functional from glance.tests.utils import depends_on_exe from glance.tests.utils import execute from glance.tests.utils import skip_if_disabled CONF = cfg.CONF class TestGlanceManage(functional.FunctionalTest): """Functional tests for glance-manage""" def setUp(self): super(TestGlanceManage, self).setUp() conf_dir = os.path.join(self.test_dir, 'etc') utils.safe_mkdirs(conf_dir) self.conf_filepath = os.path.join(conf_dir, 'glance-manage.conf') self.db_filepath = os.path.join(self.test_dir, 'tests.sqlite') self.connection = ('sql_connection = sqlite:///%s' % self.db_filepath) db_options.set_defaults(CONF, connection='sqlite:///%s' % self.db_filepath) def _db_command(self, db_method): with open(self.conf_filepath, 'w') as conf_file: conf_file.write('[DEFAULT]\n') conf_file.write(self.connection) conf_file.flush() cmd = ('%s -m glance.cmd.manage --config-file %s db %s' % (sys.executable, self.conf_filepath, db_method)) return execute(cmd, raise_error=True) def _check_db(self, expected_exitcode): with open(self.conf_filepath, 'w') as conf_file: conf_file.write('[DEFAULT]\n') conf_file.write(self.connection) conf_file.flush() cmd = ('%s -m glance.cmd.manage --config-file %s db check' % (sys.executable, self.conf_filepath)) exitcode, out, err = execute(cmd, raise_error=True, expected_exitcode=expected_exitcode) return exitcode, out def _assert_table_exists(self, db_table): cmd = ("sqlite3 {0} \"SELECT name FROM sqlite_master WHERE " "type='table' AND name='{1}'\"").format(self.db_filepath, db_table) exitcode, out, err = execute(cmd, raise_error=True) msg = "Expected table {0} was not found in the schema".format(db_table) self.assertEqual(out.rstrip().decode("utf-8"), db_table, msg) @depends_on_exe('sqlite3') @skip_if_disabled def test_db_creation(self): """Test schema creation by db_sync on a fresh DB""" self._db_command(db_method='sync') for table in ['images', 'image_tags', 'image_locations', 'image_members', 'image_properties']: self._assert_table_exists(table) @depends_on_exe('sqlite3') @skip_if_disabled def test_sync(self): """Test DB sync which internally calls EMC""" self._db_command(db_method='sync') contract_head = alembic_migrations.get_alembic_branch_head( db_migration.CONTRACT_BRANCH) cmd = ("sqlite3 {0} \"SELECT version_num FROM alembic_version\"" ).format(self.db_filepath) exitcode, out, err = execute(cmd, raise_error=True) self.assertEqual(contract_head, out.rstrip().decode("utf-8")) @depends_on_exe('sqlite3') @skip_if_disabled def test_check(self): exitcode, out = self._check_db(3) self.assertEqual(3, exitcode) self._db_command(db_method='expand') if data_migrations.has_pending_migrations(db_api.get_engine()): exitcode, out = self._check_db(4) self.assertEqual(4, exitcode) self._db_command(db_method='migrate') exitcode, out = self._check_db(5) self.assertEqual(5, exitcode) self._db_command(db_method='contract') exitcode, out = self._check_db(0) self.assertEqual(0, exitcode) @depends_on_exe('sqlite3') @skip_if_disabled def test_expand(self): """Test DB expand""" self._db_command(db_method='expand') expand_head = alembic_migrations.get_alembic_branch_head( db_migration.EXPAND_BRANCH) cmd = ("sqlite3 {0} \"SELECT version_num FROM alembic_version\"" ).format(self.db_filepath) exitcode, out, err = execute(cmd, raise_error=True) self.assertEqual(expand_head, out.rstrip().decode("utf-8")) exitcode, out, err = self._db_command(db_method='expand') self.assertIn('Database expansion is up to date. ' 'No expansion needed.', str(out)) @depends_on_exe('sqlite3') @skip_if_disabled def test_migrate(self): """Test DB migrate""" self._db_command(db_method='expand') if data_migrations.has_pending_migrations(db_api.get_engine()): self._db_command(db_method='migrate') expand_head = alembic_migrations.get_alembic_branch_head( db_migration.EXPAND_BRANCH) cmd = ("sqlite3 {0} \"SELECT version_num FROM alembic_version\"" ).format(self.db_filepath) exitcode, out, err = execute(cmd, raise_error=True) self.assertEqual(expand_head, out.rstrip().decode("utf-8")) self.assertEqual(False, data_migrations.has_pending_migrations( db_api.get_engine())) if data_migrations.has_pending_migrations(db_api.get_engine()): exitcode, out, err = self._db_command(db_method='migrate') self.assertIn('Database migration is up to date. No migration ' 'needed.', str(out)) @depends_on_exe('sqlite3') @skip_if_disabled def test_contract(self): """Test DB contract""" self._db_command(db_method='expand') if data_migrations.has_pending_migrations(db_api.get_engine()): self._db_command(db_method='migrate') self._db_command(db_method='contract') contract_head = alembic_migrations.get_alembic_branch_head( db_migration.CONTRACT_BRANCH) cmd = ("sqlite3 {0} \"SELECT version_num FROM alembic_version\"" ).format(self.db_filepath) exitcode, out, err = execute(cmd, raise_error=True) self.assertEqual(contract_head, out.rstrip().decode("utf-8")) exitcode, out, err = self._db_command(db_method='contract') self.assertIn('Database is up to date. No migrations needed.', str(out))
{ "pile_set_name": "Github" }
# 64 Audio N8 M15 RMA See [usage instructions](https://github.com/jaakkopasanen/AutoEq#usage) for more options and info. ### Parametric EQs In case of using parametric equalizer, apply preamp of **-7.4dB** and build filters manually with these parameters. The first 5 filters can be used independently. When using independent subset of filters, apply preamp of **-7.4dB**. | Type | Fc | Q | Gain | |:--------|:---------|:-----|:---------| | Peaking | 40 Hz | 0.26 | -1.5 dB | | Peaking | 119 Hz | 0.61 | -4.0 dB | | Peaking | 271 Hz | 0.99 | -3.3 dB | | Peaking | 3403 Hz | 1.98 | 4.7 dB | | Peaking | 7982 Hz | 0.99 | 6.6 dB | | Peaking | 959 Hz | 2.25 | 2.0 dB | | Peaking | 1645 Hz | 1.18 | -1.9 dB | | Peaking | 2493 Hz | 1.44 | 1.1 dB | | Peaking | 12056 Hz | 1.63 | 4.7 dB | | Peaking | 19732 Hz | 0.51 | -15.0 dB | ### Fixed Band EQs In case of using fixed band (also called graphic) equalizer, apply preamp of **-8.4dB** (if available) and set gains manually with these parameters. | Type | Fc | Q | Gain | |:--------|:---------|:-----|:--------| | Peaking | 31 Hz | 1.41 | -1.7 dB | | Peaking | 62 Hz | 1.41 | -3.0 dB | | Peaking | 125 Hz | 1.41 | -4.8 dB | | Peaking | 250 Hz | 1.41 | -4.9 dB | | Peaking | 500 Hz | 1.41 | -1.4 dB | | Peaking | 1000 Hz | 1.41 | 0.9 dB | | Peaking | 2000 Hz | 1.41 | -0.6 dB | | Peaking | 4000 Hz | 1.41 | 4.8 dB | | Peaking | 8000 Hz | 1.41 | 7.5 dB | | Peaking | 16000 Hz | 1.41 | -6.0 dB | ### Graphs ![](./64%20Audio%20N8%20M15%20RMA.png)
{ "pile_set_name": "Github" }
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2020 Ruhr University Bochum, Paderborn University, * and Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.core.protocol.parser; import de.rub.nds.modifiablevariable.util.ArrayConverter; import de.rub.nds.tlsattacker.core.config.Config; import de.rub.nds.tlsattacker.core.constants.HandshakeByteLength; import de.rub.nds.tlsattacker.core.constants.HandshakeMessageType; import de.rub.nds.tlsattacker.core.constants.KeyExchangeAlgorithm; import de.rub.nds.tlsattacker.core.constants.ProtocolVersion; import de.rub.nds.tlsattacker.core.protocol.message.DHEServerKeyExchangeMessage; import java.util.Arrays; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class DHEServerKeyExchangeParser<T extends DHEServerKeyExchangeMessage> extends ServerKeyExchangeParser<T> { private static final Logger LOGGER = LogManager.getLogger(); private final ProtocolVersion version; private final KeyExchangeAlgorithm keyExchangeAlgorithm; /** * Constructor for the Parser class * * @param pointer * Position in the array where the ServerKeyExchangeParser is * supposed to start parsing * @param array * The byte[] which the ServerKeyExchangeParser is supposed to * parse * @param version * Version of the Protocol * @param keyExchangeAlgorithm * The selected key exchange algorithm (affects which fields are * present). * @param config * A Config used in the current context */ public DHEServerKeyExchangeParser(int pointer, byte[] array, ProtocolVersion version, KeyExchangeAlgorithm keyExchangeAlgorithm, Config config) { super(pointer, array, HandshakeMessageType.SERVER_KEY_EXCHANGE, version, config); this.version = version; this.keyExchangeAlgorithm = keyExchangeAlgorithm; } public DHEServerKeyExchangeParser(int pointer, byte[] array, ProtocolVersion version, Config config) { // TODO: Delete when done this(pointer, array, version, null, config); } @Override protected void parseHandshakeMessageContent(DHEServerKeyExchangeMessage msg) { LOGGER.debug("Parsing DHEServerKeyExchangeMessage"); parsepLength(msg); parseP(msg); parsegLength(msg); parseG(msg); parseSerializedPublicKeyLength(msg); parseSerializedPublicKey(msg); // TODO: this.keyExchangeAlgorithm can currently be null, only for test // code that needs to be reworked. if (this.keyExchangeAlgorithm == null || !this.keyExchangeAlgorithm.isAnon()) { if (isTLS12() || isDTLS12()) { parseSignatureAndHashAlgorithm(msg); } parseSignatureLength(msg); parseSignature(msg); } } protected void parseDheParams(T msg) { parsepLength(msg); parseP(msg); parsegLength(msg); parseG(msg); parseSerializedPublicKeyLength(msg); parseSerializedPublicKey(msg); } @Override protected T createHandshakeMessage() { return (T) new DHEServerKeyExchangeMessage(); } /** * Reads the next bytes as the pLength and writes them in the message * * @param msg * Message to write in */ private void parsepLength(DHEServerKeyExchangeMessage msg) { msg.setModulusLength(parseIntField(HandshakeByteLength.DH_MODULUS_LENGTH)); LOGGER.debug("pLength: " + msg.getModulusLength().getValue()); } /** * Reads the next bytes as P and writes them in the message * * @param msg * Message to write in */ private void parseP(DHEServerKeyExchangeMessage msg) { msg.setModulus(parseByteArrayField(msg.getModulusLength().getValue())); LOGGER.debug("P: " + Arrays.toString(msg.getModulus().getValue())); } /** * Reads the next bytes as the gLength and writes them in the message * * @param msg * Message to write in */ private void parsegLength(DHEServerKeyExchangeMessage msg) { msg.setGeneratorLength(parseIntField(HandshakeByteLength.DH_GENERATOR_LENGTH)); LOGGER.debug("gLength: " + msg.getGeneratorLength().getValue()); } /** * Reads the next bytes as G and writes them in the message * * @param msg * Message to write in */ private void parseG(DHEServerKeyExchangeMessage msg) { msg.setGenerator(parseByteArrayField(msg.getGeneratorLength().getValue())); LOGGER.debug("G: " + Arrays.toString(msg.getGenerator().getValue())); } /** * Reads the next bytes as the SerializedPublicKeyLength and writes them in * the message * * @param msg * Message to write in */ private void parseSerializedPublicKeyLength(DHEServerKeyExchangeMessage msg) { msg.setPublicKeyLength(parseIntField(HandshakeByteLength.DH_PUBLICKEY_LENGTH)); LOGGER.debug("SerializedPublicKeyLength: " + msg.getPublicKeyLength().getValue()); } /** * Reads the next bytes as the SerializedPublicKey and writes them in the * message * * @param msg * Message to write in */ private void parseSerializedPublicKey(DHEServerKeyExchangeMessage msg) { msg.setPublicKey(parseByteArrayField(msg.getPublicKeyLength().getValue())); LOGGER.debug("SerializedPublicKey: " + ArrayConverter.bytesToHexString(msg.getPublicKey().getValue())); } /** * Checks if the version is TLS12 * * @return True if the used version is TLS12 */ private boolean isTLS12() { return version == ProtocolVersion.TLS12; } /** * Checks if the version is DTLS12 * * @return True if the used version is DTLS12 */ private boolean isDTLS12() { return version == ProtocolVersion.DTLS12; } /** * Reads the next bytes as the SignatureAndHashAlgorithm and writes them in * the message * * @param msg * Message to write in */ private void parseSignatureAndHashAlgorithm(DHEServerKeyExchangeMessage msg) { msg.setSignatureAndHashAlgorithm(parseByteArrayField(HandshakeByteLength.SIGNATURE_HASH_ALGORITHM)); LOGGER.debug("SignatureAndHashAlgorithm: " + ArrayConverter.bytesToHexString(msg.getSignatureAndHashAlgorithm().getValue())); } /** * Reads the next bytes as the SignatureLength and writes them in the * message * * @param msg * Message to write in */ private void parseSignatureLength(DHEServerKeyExchangeMessage msg) { msg.setSignatureLength(parseIntField(HandshakeByteLength.SIGNATURE_LENGTH)); LOGGER.debug("SignatureLength: " + msg.getSignatureLength().getValue()); } /** * Reads the next bytes as the Signature and writes them in the message * * @param msg * Message to write in */ private void parseSignature(DHEServerKeyExchangeMessage msg) { msg.setSignature(parseByteArrayField(msg.getSignatureLength().getValue())); LOGGER.debug("Signature: " + ArrayConverter.bytesToHexString(msg.getSignature().getValue())); } }
{ "pile_set_name": "Github" }
KISSY.add('brix/gallery/charts/js/e/line3/main',function(S,Base,Global,SVGElement,Widget,DataParse,ConfigParse){ function Main(){ var self = this /* arguments: o:{ parent :'' //SVGElement w :100 //chart 宽 h :100 //chart 高 config :'' //图表配置 data :'' //图表数据 } */ Main.superclass.constructor.apply(self,arguments); self.init() } Main.ATTRS = { _main:{ value:null }, _config:{ //图表配置 经过ConfigParse.parse value:{} }, _DataSource:{ value:{} //图表数据源 经过DataParse.parse } } S.extend(Main,Base,{ init:function(){ var self = this self.set('_DataSource', new DataParse().parse(self.get('data'))) self.set('_config', new ConfigParse().parse(self.get('config'))) self._widget() }, _widget:function(){ var self = this self.set('_main',new SVGElement('g')) self.get('_main').attr({'class':'main'}); self.get('parent').appendChild(self.get('_main').element) self.get('_main').transformXY(Global.N05, Global.N05) var o = {} o.parent = self.get('_main') //SVGElement o.w = self.get('w') //chart 宽 o.h = self.get('h') //chart 高 o.DataSource = self.get('_DataSource') //图表数据源 o.config = self.get('_config') //图表配置 new Widget(o) } }); return Main; }, { requires:['base','../../pub/utils/global','../../pub/utils/svgelement','./view/widget','../../pub/controls/line3/dataparse','../../pub/controls/line3/configparse'] } );
{ "pile_set_name": "Github" }
var once = require('once'); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onclose = function() { if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', callback); stream.on('close', onclose); return function() { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', callback); stream.removeListener('close', onclose); }; }; module.exports = eos;
{ "pile_set_name": "Github" }
.mp, body#manpage { background:#080706; color:#888; } .mp, .mp code, .mp pre, .mp pre code, .mp tt, .mp kbd, .mp samp { color:#aaa } .mp h1, .mp h2, .mp h3, .mp h4 { color:#fff } .man-decor, .man-decor ol li { color:#666 } .mp code, .mp strong, .mp b { color:#fff } .mp em, .mp var, .mp u { color:#ddd } .mp pre code { color:#ddd } .mp a, .mp a:link, .mp a:hover, .mp a code, .mp a pre, .mp a tt, .mp a kbd, .mp a samp { color:#fff }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ReSharper disable InconsistentNaming namespace DotNetty.Codecs.Http.WebSockets { using System.Collections.Generic; using DotNetty.Buffers; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public class WebSocket00FrameEncoder : MessageToMessageEncoder<WebSocketFrame>, IWebSocketFrameEncoder { static readonly IByteBuffer _0X00 = Unpooled.UnreleasableBuffer( Unpooled.DirectBuffer(1, 1).WriteByte(0x00)); static readonly IByteBuffer _0XFF = Unpooled.UnreleasableBuffer( Unpooled.DirectBuffer(1, 1).WriteByte(0xFF)); static readonly IByteBuffer _0XFF_0X00 = Unpooled.UnreleasableBuffer( Unpooled.DirectBuffer(2, 2).WriteByte(0xFF).WriteByte(0x00)); public override bool IsSharable => true; protected override void Encode(IChannelHandlerContext context, WebSocketFrame message, List<object> output) { if (message is TextWebSocketFrame) { // Text frame IByteBuffer data = message.Content; output.Add(_0X00.Duplicate()); output.Add(data.Retain()); output.Add(_0XFF.Duplicate()); } else if (message is CloseWebSocketFrame) { // Close frame, needs to call duplicate to allow multiple writes. // See https://github.com/netty/netty/issues/2768 output.Add(_0XFF_0X00.Duplicate()); } else { // Binary frame IByteBuffer data = message.Content; int dataLen = data.ReadableBytes; IByteBuffer buf = context.Allocator.Buffer(5); bool release = true; try { // Encode type. buf.WriteByte(0x80); // Encode length. int b1 = dataLen.RightUShift(28) & 0x7F; int b2 = dataLen.RightUShift(14) & 0x7F; int b3 = dataLen.RightUShift(7) & 0x7F; int b4 = dataLen & 0x7F; if (b1 == 0) { if (b2 == 0) { if (b3 == 0) { buf.WriteByte(b4); } else { buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } } else { buf.WriteByte(b2 | 0x80); buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } } else { buf.WriteByte(b1 | 0x80); buf.WriteByte(b2 | 0x80); buf.WriteByte(b3 | 0x80); buf.WriteByte(b4); } // Encode binary data. output.Add(buf); output.Add(data.Retain()); release = false; } finally { if (release) { buf.Release(); } } } } } }
{ "pile_set_name": "Github" }
import { userFetchStartedType as USER_FETCH_STARTED, userReceivedType as USER_RECEIVED, } from '../actions/actionCreators/userActions'; const initialState = { isLoading: false, data: {}, }; export default function user(state = initialState, action) { switch (action.type) { case USER_FETCH_STARTED: return { ...state, isLoading: true, }; case USER_RECEIVED: // TODO: When does this happen? Should this happen, or should // an error be thrown instead? if (!action.user) { return false; } return { isLoading: false, data: { ...action.user, }, }; default: return state; } }
{ "pile_set_name": "Github" }
{% load django_tables2 %} {% load i18n %} <div class="btn-toolbar"> <div class="btn-group"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="true"> {% trans "Actions" %} <span class="caret"></span> </button> <ul class="dropdown-menu pull-right"> <li> <a href="{% url 'dashboard:catalogue-product' pk=record.id %}{% querystring %}">{% trans "Edit" %}</a> </li> <li> <a href="{{ record.get_absolute_url }}"> {% trans "View on site" %}</a> </li> <li> <a href="{% url 'dashboard:catalogue-product-delete' pk=record.id %}">{% trans "Delete" %}</a> </li> </ul> </div> </div>
{ "pile_set_name": "Github" }
// // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.// // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" #include "AL/usdmaya/utils/AttributeType.h" #include "AL/usdmaya/utils/Utils.h" #include "maya/MFileIO.h" #include "maya/MViewport2Renderer.h" #include "maya/MFnTransform.h" PXR_NAMESPACE_USING_DIRECTIVE namespace AL { namespace usdmaya { namespace nodes { using AL::usdmaya::utils::UsdDataType; //---------------------------------------------------------------------------------------------------------------------- const MTypeId TransformationMatrix::kTypeId(AL_USDMAYA_TRANSFORMATION_MATRIX); //---------------------------------------------------------------------------------------------------------------------- MPxTransformationMatrix* TransformationMatrix::creator() { return new TransformationMatrix; } //---------------------------------------------------------------------------------------------------------------------- TransformationMatrix::TransformationMatrix() : MPxTransformationMatrix(), m_prim(), m_xform(), m_time(UsdTimeCode::Default()), m_scaleTweak(0, 0, 0), m_rotationTweak(0, 0, 0), m_translationTweak(0, 0, 0), m_shearTweak(0, 0, 0), m_scalePivotTweak(0, 0, 0), m_scalePivotTranslationTweak(0, 0, 0), m_rotatePivotTweak(0, 0, 0), m_rotatePivotTranslationTweak(0, 0, 0), m_rotateOrientationTweak(0, 0, 0, 1.0), m_scaleFromUsd(1.1, 1.1, 1.1), m_rotationFromUsd(0, 0, 0), m_translationFromUsd(0.1, 0.2, 0.3), m_shearFromUsd(0, 0, 0), m_scalePivotFromUsd(0, 0, 0), m_scalePivotTranslationFromUsd(0, 0, 0), m_rotatePivotFromUsd(0, 0, 0), m_rotatePivotTranslationFromUsd(0, 0, 0), m_rotateOrientationFromUsd(0, 0, 0, 1.0), m_localTranslateOffset(0, 0, 0), m_flags(0) { TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformationMatrix::TransformationMatrix\n"); initialiseToPrim(); } //---------------------------------------------------------------------------------------------------------------------- TransformationMatrix::TransformationMatrix(const UsdPrim& prim) : MPxTransformationMatrix(), m_prim(prim), m_xform(prim), m_time(UsdTimeCode::Default()), m_scaleTweak(0, 0, 0), m_rotationTweak(0, 0, 0), m_translationTweak(0, 0, 0), m_shearTweak(0, 0, 0), m_scalePivotTweak(0, 0, 0), m_scalePivotTranslationTweak(0, 0, 0), m_rotatePivotTweak(0, 0, 0), m_rotatePivotTranslationTweak(0, 0, 0), m_rotateOrientationTweak(0, 0, 0, 1.0), m_scaleFromUsd(1.0, 1.0, 1.0), m_rotationFromUsd(0, 0, 0), m_translationFromUsd(0, 0, 0), m_shearFromUsd(0, 0, 0), m_scalePivotFromUsd(0, 0, 0), m_scalePivotTranslationFromUsd(0, 0, 0), m_rotatePivotFromUsd(0, 0, 0), m_rotatePivotTranslationFromUsd(0, 0, 0), m_rotateOrientationFromUsd(0, 0, 0, 1.0), m_localTranslateOffset(0, 0, 0), m_flags(0) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::TransformationMatrix\n"); initialiseToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::setPrim(const UsdPrim& prim, Transform* transformNode) { if(prim.IsValid()) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setPrim %s\n", prim.GetName().GetText()); m_prim = prim; UsdGeomXform xform(prim); m_xform = xform; } else { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setPrim null\n"); m_prim = UsdPrim(); m_xform = UsdGeomXform(); } // Most of these flags are calculated based on reading the usd prim; however, a few are driven // "externally" (ie, from attributes on the controlling transform node), and should NOT be reset // when we're re-initializing m_flags &= kPreservationMask; m_scaleTweak = MVector(0, 0, 0); m_rotationTweak = MEulerRotation(0, 0, 0); m_translationTweak = MVector(0, 0, 0); m_shearTweak = MVector(0, 0, 0); m_scalePivotTweak = MPoint(0, 0, 0); m_scalePivotTranslationTweak = MVector(0, 0, 0); m_rotatePivotTweak = MPoint(0, 0, 0); m_rotatePivotTranslationTweak = MVector(0, 0, 0); m_rotateOrientationTweak = MQuaternion(0, 0, 0, 1.0); m_localTranslateOffset = MVector(0, 0, 0); if(m_prim.IsValid()) { m_scaleFromUsd = MVector(1.0, 1.0, 1.0); m_rotationFromUsd = MEulerRotation(0, 0, 0); m_translationFromUsd = MVector(0, 0, 0); m_shearFromUsd = MVector(0, 0, 0); m_scalePivotFromUsd = MPoint(0, 0, 0); m_scalePivotTranslationFromUsd = MVector(0, 0, 0); m_rotatePivotFromUsd = MPoint(0, 0, 0); m_rotatePivotTranslationFromUsd = MVector(0, 0, 0); m_rotateOrientationFromUsd = MQuaternion(0, 0, 0, 1.0); initialiseToPrim(!MFileIO::isReadingFile(), transformNode); MPxTransformationMatrix::scaleValue = m_scaleFromUsd; MPxTransformationMatrix::rotationValue = m_rotationFromUsd; MPxTransformationMatrix::translationValue = m_translationFromUsd; MPxTransformationMatrix::shearValue = m_shearFromUsd; MPxTransformationMatrix::scalePivotValue = m_scalePivotFromUsd; MPxTransformationMatrix::scalePivotTranslationValue = m_scalePivotTranslationFromUsd; MPxTransformationMatrix::rotatePivotValue = m_rotatePivotFromUsd; MPxTransformationMatrix::rotatePivotTranslationValue = m_rotatePivotTranslationFromUsd; MPxTransformationMatrix::rotateOrientationValue = m_rotateOrientationFromUsd; } } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readVector(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readVector\n"); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kVec3d: { GfVec3d value; const bool retValue = op.GetAs<GfVec3d>(&value, timeCode); if (!retValue) { return false; } result.x = value[0]; result.y = value[1]; result.z = value[2]; } break; case UsdDataType::kVec3f: { GfVec3f value; const bool retValue = op.GetAs<GfVec3f>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; case UsdDataType::kVec3h: { GfVec3h value; const bool retValue = op.GetAs<GfVec3h>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; case UsdDataType::kVec3i: { GfVec3i value; const bool retValue = op.GetAs<GfVec3i>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; default: return false; } TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readVector %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushVector(const MVector& result, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushVector %f %f %f [@%f]\n%s\n", result.x, result.y, result.z, timeCode.GetValue(), op.GetOpName().GetText()); auto attr = op.GetAttr(); if(!attr) { return false; } TfToken typeName; attr.GetMetadata(SdfFieldKeys->TypeName, &typeName); SdfValueTypeName vtn = SdfSchema::GetInstance().FindType(typeName); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kVec3d: { GfVec3d value(result.x, result.y, result.z); GfVec3d oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) { op.Set(value, timeCode); } } break; case UsdDataType::kVec3f: { GfVec3f value(result.x, result.y, result.z); GfVec3f oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) { op.Set(value, timeCode); } } break; case UsdDataType::kVec3h: { GfVec3h value(result.x, result.y, result.z); GfVec3h oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) { op.Set(value, timeCode); } } break; case UsdDataType::kVec3i: { GfVec3i value(result.x, result.y, result.z); GfVec3i oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) { op.Set(value, timeCode); } } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushShear(const MVector& result, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushShear %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kMatrix4d: { GfMatrix4d m( 1.0, 0.0, 0.0, 0.0, result.x, 1.0, 0.0, 0.0, result.y, result.z, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); GfMatrix4d oldValue; op.Get(&oldValue, timeCode); if(m != oldValue) op.Set(m, timeCode); } break; default: return false; } return false; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readShear(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readShear\n"); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kMatrix4d: { GfMatrix4d value; const bool retValue = op.GetAs<GfMatrix4d>(&value, timeCode); if (!retValue) { return false; } result.x = value[1][0]; result.y = value[2][0]; result.z = value[2][1]; } break; default: return false; } TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readShear %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readPoint(MPoint& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readPoint\n"); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kVec3d: { GfVec3d value; const bool retValue = op.GetAs<GfVec3d>(&value, timeCode); if (!retValue) { return false; } result.x = value[0]; result.y = value[1]; result.z = value[2]; } break; case UsdDataType::kVec3f: { GfVec3f value; const bool retValue = op.GetAs<GfVec3f>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; case UsdDataType::kVec3h: { GfVec3h value; const bool retValue = op.GetAs<GfVec3h>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; case UsdDataType::kVec3i: { GfVec3i value; const bool retValue = op.GetAs<GfVec3i>(&value, timeCode); if (!retValue) { return false; } result.x = double(value[0]); result.y = double(value[1]); result.z = double(value[2]); } break; default: return false; } TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readPoint %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readMatrix(MMatrix& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readMatrix\n"); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kMatrix4d: { GfMatrix4d value; const bool retValue = op.GetAs<GfMatrix4d>(&value, timeCode); if (!retValue) { return false; } auto vtemp = (const void*)&value; auto mtemp = (const MMatrix*)vtemp; result = *mtemp; } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushMatrix(const MMatrix& result, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushMatrix\n"); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kMatrix4d: { const GfMatrix4d& value = *(const GfMatrix4d*)(&result); GfMatrix4d oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) { const bool retValue = op.Set<GfMatrix4d>(value, timeCode); if (!retValue) { return false; } } } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::setFromMatrix(MObject thisNode, const MMatrix& m) { double S[3]; MEulerRotation R; double T[3]; utils::matrixToSRT(*(const GfMatrix4d*)&m, S, R, T); m_scaleFromUsd.x = S[0]; m_scaleFromUsd.y = S[1]; m_scaleFromUsd.z = S[2]; m_rotationFromUsd.x = R.x; m_rotationFromUsd.y = R.y; m_rotationFromUsd.z = R.z; m_translationFromUsd.x = T[0]; m_translationFromUsd.y = T[1]; m_translationFromUsd.z = T[2]; MPlug(thisNode, MPxTransform::scaleX).setValue(m_scaleFromUsd.x); MPlug(thisNode, MPxTransform::scaleY).setValue(m_scaleFromUsd.y); MPlug(thisNode, MPxTransform::scaleZ).setValue(m_scaleFromUsd.z); MPlug(thisNode, MPxTransform::rotateX).setValue(m_rotationFromUsd.x); MPlug(thisNode, MPxTransform::rotateY).setValue(m_rotationFromUsd.y); MPlug(thisNode, MPxTransform::rotateZ).setValue(m_rotationFromUsd.z); MPlug(thisNode, MPxTransform::translateX).setValue(m_translationFromUsd.x); MPlug(thisNode, MPxTransform::translateY).setValue(m_translationFromUsd.y); MPlug(thisNode, MPxTransform::translateZ).setValue(m_translationFromUsd.z); } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushPoint(const MPoint& result, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushPoint %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); const SdfValueTypeName vtn = op.GetTypeName(); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); switch(attr_type) { case UsdDataType::kVec3d: { GfVec3d value(result.x, result.y, result.z); GfVec3d oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) op.Set(value, timeCode); } break; case UsdDataType::kVec3f: { GfVec3f value(result.x, result.y, result.z); GfVec3f oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) op.Set(value, timeCode); } break; case UsdDataType::kVec3h: { GfVec3h value(result.x, result.y, result.z); GfVec3h oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) op.Set(value, timeCode); } break; case UsdDataType::kVec3i: { GfVec3i value(result.x, result.y, result.z); GfVec3i oldValue; op.Get(&oldValue, timeCode); if(value != oldValue) op.Set(value, timeCode); } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- double TransformationMatrix::readDouble(const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readDouble\n"); double result = 0; UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); switch(attr_type) { case UsdDataType::kHalf: { GfHalf value; const bool retValue = op.Get<GfHalf>(&value, timeCode); if (retValue) { result = float(value); } } break; case UsdDataType::kFloat: { float value; const bool retValue = op.Get<float>(&value, timeCode); if (retValue) { result = double(value); } } break; case UsdDataType::kDouble: { double value; const bool retValue = op.Get<double>(&value, timeCode); if (retValue) { result = value; } } break; case UsdDataType::kInt: { int32_t value; const bool retValue = op.Get<int32_t>(&value, timeCode); if (retValue) { result = double(value); } } break; default: break; } TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformationMatrix::readDouble %f\n%s\n", result, op.GetOpName().GetText()); return result; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushDouble(const double value, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushDouble %f\n%s\n", value, op.GetOpName().GetText()); UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); switch(attr_type) { case UsdDataType::kHalf: { GfHalf oldValue; op.Get(&oldValue); if(oldValue != GfHalf(value)) op.Set(GfHalf(value), timeCode); } break; case UsdDataType::kFloat: { float oldValue; op.Get(&oldValue); if(oldValue != float(value)) op.Set(float(value), timeCode); } break; case UsdDataType::kDouble: { double oldValue; op.Get(&oldValue); if(oldValue != double(value)) op.Set(double(value), timeCode); } break; case UsdDataType::kInt: { int32_t oldValue; op.Get(&oldValue); if(oldValue != int32_t(value)) op.Set(int32_t(value), timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readRotation(MEulerRotation& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readRotation %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); const double degToRad = 3.141592654 / 180.0; switch(op.GetOpType()) { case UsdGeomXformOp::TypeRotateX: { result.x = readDouble(op, timeCode) * degToRad; result.y = 0.0; result.z = 0.0; result.order = MEulerRotation::kXYZ; } break; case UsdGeomXformOp::TypeRotateY: { result.x = 0.0; result.y = readDouble(op, timeCode) * degToRad; result.z = 0.0; result.order = MEulerRotation::kXYZ; } break; case UsdGeomXformOp::TypeRotateZ: { result.x = 0.0; result.y = 0.0; result.z = readDouble(op, timeCode) * degToRad; result.order = MEulerRotation::kXYZ; } break; case UsdGeomXformOp::TypeRotateXYZ: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kXYZ; } else return false; } break; case UsdGeomXformOp::TypeRotateXZY: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kXZY; } else return false; } break; case UsdGeomXformOp::TypeRotateYXZ: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kYXZ; } else return false; } break; case UsdGeomXformOp::TypeRotateYZX: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kYZX; } else return false; } break; case UsdGeomXformOp::TypeRotateZXY: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kZXY; } else return false; } break; case UsdGeomXformOp::TypeRotateZYX: { MVector v; if(readVector(v, op, timeCode)) { result.x = v.x * degToRad; result.y = v.y * degToRad; result.z = v.z * degToRad; result.order = MEulerRotation::kZYX; } else return false; } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushRotation(const MEulerRotation& value, UsdGeomXformOp& op, UsdTimeCode timeCode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotation %f %f %f\n%s\n", value.x, value.y, value.z, op.GetOpName().GetText()); const double radToDeg = 180.0 / 3.141592654; switch(op.GetOpType()) { case UsdGeomXformOp::TypeRotateX: { pushDouble(value.x * radToDeg, op, timeCode); } break; case UsdGeomXformOp::TypeRotateY: { pushDouble(value.y * radToDeg, op, timeCode); } break; case UsdGeomXformOp::TypeRotateZ: { pushDouble(value.z * radToDeg, op, timeCode); } break; case UsdGeomXformOp::TypeRotateXYZ: case UsdGeomXformOp::TypeRotateXZY: case UsdGeomXformOp::TypeRotateYXZ: case UsdGeomXformOp::TypeRotateYZX: case UsdGeomXformOp::TypeRotateZYX: case UsdGeomXformOp::TypeRotateZXY: { MVector v(value.x, value.y, value.z); v *= radToDeg; return pushVector(v, op, timeCode); } break; default: return false; } return true; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::initialiseToPrim(bool readFromPrim, Transform* transformNode) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::initialiseToPrim\n"); // if not yet initialized, do not execute this code! (It will crash!). if(!m_prim) return; bool resetsXformStack = false; m_xformops = m_xform.GetOrderedXformOps(&resetsXformStack); m_orderedOps.resize(m_xformops.size()); if(!resetsXformStack) m_flags |= kInheritsTransform; if(matchesMayaProfile(m_xformops.begin(), m_xformops.end(), m_orderedOps.begin())) { m_flags |= kFromMayaSchema; } else { } auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::const_iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { const UsdGeomXformOp& op = *it; switch(*opIt) { case kTranslate: { m_flags |= kPrimHasTranslation; if(op.GetNumTimeSamples() > 1) { m_flags |= kAnimatedTranslation; } if(readFromPrim) { internal_readVector(m_translationFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::translateX).setValue(m_translationFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::translateY).setValue(m_translationFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::translateZ).setValue(m_translationFromUsd.z); } } } break; case kPivot: { m_flags |= kPrimHasPivot; if(readFromPrim) { internal_readPoint(m_scalePivotFromUsd, op); m_rotatePivotFromUsd = m_scalePivotFromUsd; if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX).setValue(m_rotatePivotFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY).setValue(m_rotatePivotFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ).setValue(m_rotatePivotFromUsd.z); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX).setValue(m_scalePivotFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY).setValue(m_scalePivotFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ).setValue(m_scalePivotFromUsd.z); } } } break; case kRotatePivotTranslate: { m_flags |= kPrimHasRotatePivotTranslate; if(readFromPrim) { internal_readVector(m_rotatePivotTranslationFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateX).setValue(m_rotatePivotTranslationFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateY).setValue(m_rotatePivotTranslationFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateZ).setValue(m_rotatePivotTranslationFromUsd.z); } } } break; case kRotatePivot: { m_flags |= kPrimHasRotatePivot; if(readFromPrim) { internal_readPoint(m_rotatePivotFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX).setValue(m_rotatePivotFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY).setValue(m_rotatePivotFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ).setValue(m_rotatePivotFromUsd.z); } } } break; case kRotate: { m_flags |= kPrimHasRotation; if(op.GetNumTimeSamples() > 1) { m_flags |= kAnimatedRotation; } if(readFromPrim) { internal_readRotation(m_rotationFromUsd, op); if(transformNode) { m_rotationTweak[0] = m_rotationTweak[1] = m_rotationTweak[2] = 0; // attempting to set the rotation via the attributes can end up failing when using zxy rotation orders. // The only reliable way to set this value would appeear to be via MFnTransform :( MFnTransform fn(m_transformNode.object()); fn.setRotation(m_rotationFromUsd); } } } break; case kRotateAxis: { m_flags |= kPrimHasRotateAxes; if(readFromPrim) { MEulerRotation eulers; internal_readRotation(eulers, op); m_rotateOrientationFromUsd = eulers.asQuaternion(); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisX).setValue(eulers.x); MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisY).setValue(eulers.y); MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisZ).setValue(eulers.z); } } } break; case kRotatePivotInv: { } break; case kScalePivotTranslate: { m_flags |= kPrimHasScalePivotTranslate; if(readFromPrim) { internal_readVector(m_scalePivotTranslationFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateX).setValue(m_scalePivotTranslationFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateY).setValue(m_scalePivotTranslationFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateZ).setValue(m_scalePivotTranslationFromUsd.z); } } } break; case kScalePivot: { m_flags |= kPrimHasScalePivot; if(readFromPrim) { internal_readPoint(m_scalePivotFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX).setValue(m_scalePivotFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY).setValue(m_scalePivotFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ).setValue(m_scalePivotFromUsd.z); } } } break; case kShear: { m_flags |= kPrimHasShear; if(op.GetNumTimeSamples() > 1) { m_flags |= kAnimatedShear; } if(readFromPrim) { internal_readShear(m_shearFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::shearXY).setValue(m_shearFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::shearXZ).setValue(m_shearFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::shearYZ).setValue(m_shearFromUsd.z); } } } break; case kScale: { m_flags |= kPrimHasScale; if(op.GetNumTimeSamples() > 1) { m_flags |= kAnimatedScale; } if(readFromPrim) { internal_readVector(m_scaleFromUsd, op); if(transformNode) { MPlug(transformNode->thisMObject(), MPxTransform::scaleX).setValue(m_scaleFromUsd.x); MPlug(transformNode->thisMObject(), MPxTransform::scaleY).setValue(m_scaleFromUsd.y); MPlug(transformNode->thisMObject(), MPxTransform::scaleZ).setValue(m_scaleFromUsd.z); } } } break; case kScalePivotInv: { } break; case kPivotInv: { } break; case kTransform: { m_flags |= kPrimHasTransform; m_flags |= kFromMatrix; m_flags |= kPushPrimToMatrix; if(op.GetNumTimeSamples() > 1) { m_flags |= kAnimatedMatrix; } if(readFromPrim) { MMatrix m; internal_readMatrix(m, op); setFromMatrix(transformNode->thisMObject(), m); } } break; case kUnknownOp: { } break; } } // if some animation keys are found on the transform ops, assume we have a read only viewer of the transform data. if(m_flags & kAnimationMask) { m_flags &= ~kPushToPrimEnabled; m_flags |= kReadAnimatedValues; } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::updateToTime(const UsdTimeCode& time) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::updateToTime %f\n", time.GetValue()); // if not yet initialized, do not execute this code! (It will crash!). if(!m_prim) { return; } if(m_time != time) { m_time = time; { auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::const_iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { const UsdGeomXformOp& op = *it; switch(*opIt) { case kTranslate: { if(op.GetNumTimeSamples() >= 1) { m_flags |= kAnimatedTranslation; internal_readVector(m_translationFromUsd, op); MPxTransformationMatrix::translationValue = m_translationFromUsd + m_translationTweak; } } break; case kRotate: { if(op.GetNumTimeSamples() >= 1) { m_flags |= kAnimatedRotation; internal_readRotation(m_rotationFromUsd, op); MPxTransformationMatrix::rotationValue = m_rotationFromUsd; MPxTransformationMatrix::rotationValue.x += m_rotationTweak.x; MPxTransformationMatrix::rotationValue.y += m_rotationTweak.y; MPxTransformationMatrix::rotationValue.z += m_rotationTweak.z; } } break; case kScale: { if(op.GetNumTimeSamples() >= 1) { m_flags |= kAnimatedScale; internal_readVector(m_scaleFromUsd, op); MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; } } break; case kShear: { if(op.GetNumTimeSamples() >= 1) { m_flags |= kAnimatedShear; internal_readShear(m_shearFromUsd, op); MPxTransformationMatrix::shearValue = m_shearFromUsd + m_shearTweak; } } break; case kTransform: { if(op.GetNumTimeSamples() >= 1) { m_flags |= kAnimatedMatrix; GfMatrix4d matrix; op.Get<GfMatrix4d>(&matrix, getTimeCode()); double T[3], S[3]; AL::usdmaya::utils::matrixToSRT(matrix, S, m_rotationFromUsd, T); m_scaleFromUsd.x = S[0]; m_scaleFromUsd.y = S[1]; m_scaleFromUsd.z = S[2]; m_translationFromUsd.x = T[0]; m_translationFromUsd.y = T[1]; m_translationFromUsd.z = T[2]; MPxTransformationMatrix::rotationValue.x = m_rotationFromUsd.x + m_rotationTweak.x; MPxTransformationMatrix::rotationValue.y = m_rotationFromUsd.y + m_rotationTweak.y; MPxTransformationMatrix::rotationValue.z = m_rotationFromUsd.z + m_rotationTweak.z; MPxTransformationMatrix::translationValue = m_translationFromUsd + m_translationTweak; MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; } } break; default: break; } } } } } //---------------------------------------------------------------------------------------------------------------------- // Translation //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertTranslateOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertTranslateOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("translate")); m_xformops.insert(m_xformops.begin(), op); m_orderedOps.insert(m_orderedOps.begin(), kTranslate); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasTranslation; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::translateTo(const MVector& vector, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::translateTo %f %f %f\n", vector.x, vector.y, vector.z); if(isTranslateLocked()) return MPxTransformationMatrix::translateTo(vector, space); MStatus status = MPxTransformationMatrix::translateTo(vector, space); if(status) { m_translationTweak = MPxTransformationMatrix::translationValue - m_translationFromUsd; } if(pushToPrimAvailable()) { // if the prim does not contain a translation, make sure we insert a transform op for that. if(primHasTranslation()) { // helping the branch predictor } else if(!pushPrimToMatrix() && vector != MVector(0.0, 0.0, 0.0)) { insertTranslateOp(); } pushTranslateToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- // Scale //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScaleOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScaleOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddScaleOp(UsdGeomXformOp::PrecisionFloat, TfToken("scale")); auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScale); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kScale); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasScale; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::scaleTo(const MVector& scale, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::scaleTo %f %f %f\n", scale.x, scale.y, scale.z); if(isScaleLocked()) return MPxTransformationMatrix::scaleTo(scale, space); MStatus status = MPxTransformationMatrix::scaleTo(scale, space); if(status) { m_scaleTweak = MPxTransformationMatrix::scaleValue - m_scaleFromUsd; } if(pushToPrimAvailable()) { if(primHasScale()) { // helping the branch predictor } else if(!pushPrimToMatrix() && scale != MVector(1.0, 1.0, 1.0)) { // rare case: add a new scale op into the prim insertScaleOp(); } pushScaleToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- // Shear //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertShearOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertShearOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("shear")); auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kShear); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kShear); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasShear; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::shearTo(const MVector& shear, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::shearTo %f %f %f\n", shear.x, shear.y, shear.z); if(isShearLocked()) return MPxTransformationMatrix::shearTo(shear, space); MStatus status = MPxTransformationMatrix::shearTo(shear, space); if(status) { m_shearTweak = MPxTransformationMatrix::shearValue - m_shearFromUsd; } if(pushToPrimAvailable()) { if(primHasShear()) { // helping the branch predictor } else if(!pushPrimToMatrix() && shear != MVector(0.0, 0.0, 0.0)) { // rare case: add a new scale op into the prim insertShearOp(); } pushShearToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScalePivotOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScalePivotOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot")); UsdGeomXformOp opinv = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot"), true); { auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivot); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kScalePivot); } { auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotInv); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, opinv); m_orderedOps.insert(posInOps, kScalePivotInv); } m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasScalePivot; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setScalePivot(const MPoint& sp, MSpace::Space space, bool balance) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setScalePivot %f %f %f\n", sp.x, sp.y, sp.z); MStatus status = MPxTransformationMatrix::setScalePivot(sp, space, balance); if(status) { m_scalePivotTweak = MPxTransformationMatrix::scalePivotValue - m_scalePivotFromUsd; } if(pushToPrimAvailable()) { // Do not insert a scale pivot op if the input prim has a generic pivot. if(primHasScalePivot() || primHasPivot()) { } else if(!pushPrimToMatrix() && sp != MPoint(0.0, 0.0, 0.0, 1.0)) { insertScalePivotOp(); } pushScalePivotToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScalePivotTranslationOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScalePivotTranslationOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivotTranslate")); auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotTranslate); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kScalePivotTranslate); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasScalePivotTranslate; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setScalePivotTranslation(const MVector& sp, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setScalePivotTranslation %f %f %f\n", sp.x, sp.y, sp.z); MStatus status = MPxTransformationMatrix::setScalePivotTranslation(sp, space); if(status) { m_scalePivotTranslationTweak = MPxTransformationMatrix::scalePivotTranslationValue - m_scalePivotTranslationFromUsd; } if(pushToPrimAvailable()) { if(primHasScalePivotTranslate()) { } else if(!pushPrimToMatrix() && sp != MVector(0.0, 0.0, 0.0)) { insertScalePivotTranslationOp(); } pushScalePivotTranslateToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotatePivotOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotatePivotOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot")); UsdGeomXformOp opinv = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot"), true); { auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivot); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kRotatePivot); } { auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotInv); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, opinv); m_orderedOps.insert(posInOps, kRotatePivotInv); } m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasRotatePivot; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotatePivot(const MPoint& pivot, MSpace::Space space, bool balance) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotatePivot %f %f %f\n", pivot.x, pivot.y, pivot.z); MStatus status = MPxTransformationMatrix::setRotatePivot(pivot, space, balance); if(status) { m_rotatePivotTweak = MPxTransformationMatrix::rotatePivotValue - m_rotatePivotFromUsd; } if(pushToPrimAvailable()) { // Do not insert a rotate pivot op if the input prim has a generic pivot. if(primHasRotatePivot() || primHasPivot()) { } else if(!pushPrimToMatrix() && pivot != MPoint(0.0, 0.0, 0.0, 1.0)) { insertRotatePivotOp(); } pushRotatePivotToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotatePivotTranslationOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotatePivotTranslationOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivotTranslate")); auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotTranslate); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kRotatePivotTranslate); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasRotatePivotTranslate; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotatePivotTranslation(const MVector &vector, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotatePivotTranslation %f %f %f\n", vector.x, vector.y, vector.z); MStatus status = MPxTransformationMatrix::setRotatePivotTranslation(vector, space); if(status) { m_rotatePivotTranslationTweak = MPxTransformationMatrix::rotatePivotTranslationValue - m_rotatePivotTranslationFromUsd; } if(pushToPrimAvailable()) { if(primHasRotatePivotTranslate()) { } else if(!pushPrimToMatrix() && vector != MPoint(0.0, 0.0, 0.0, 1.0)) { insertRotatePivotTranslationOp(); } pushRotatePivotTranslateToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotateOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op; switch(rotationOrder()) { case MTransformationMatrix::kXYZ: op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; case MTransformationMatrix::kXZY: op = m_xform.AddRotateXZYOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; case MTransformationMatrix::kYXZ: op = m_xform.AddRotateYXZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; case MTransformationMatrix::kYZX: op = m_xform.AddRotateYZXOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; case MTransformationMatrix::kZXY: op = m_xform.AddRotateZXYOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; case MTransformationMatrix::kZYX: op = m_xform.AddRotateZYXOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; default: TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateOp - got invalid rotation order; assuming XYZ"); op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotate")); break; } auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotate); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kRotate); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasRotation; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::rotateTo(const MQuaternion &q, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::rotateTo %f %f %f %f\n", q.x, q.y, q.z, q.w); if(isRotateLocked()) return MPxTransformationMatrix::rotateTo(q, space);; MStatus status = MPxTransformationMatrix::rotateTo(q, space); if(status) { m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; } if(pushToPrimAvailable()) { if(primHasRotation()) { } else if(!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) { insertRotateOp(); } pushRotateToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::rotateTo(const MEulerRotation &e, MSpace::Space space) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::rotateTo %f %f %f\n", e.x, e.y, e.z); if(isRotateLocked()) return MPxTransformationMatrix::rotateTo(e, space);; MStatus status = MPxTransformationMatrix::rotateTo(e, space); if(status) { m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; } if(pushToPrimAvailable()) { if(primHasRotation()) { } else if(!pushPrimToMatrix() && e != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) { insertRotateOp(); } pushRotateToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotationOrder(MTransformationMatrix::RotationOrder, bool) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotationOrder\n"); // do not allow people to change the rotation order here. // It's too hard for my feeble brain to figure out how to remap that to the USD data. return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotateAxesOp() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateAxesOp\n"); // generate our translate op, and insert into the correct stack location UsdGeomXformOp op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotateAxis")); auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotateAxis); auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); m_xformops.insert(posInXfm, op); m_orderedOps.insert(posInOps, kRotateAxis); m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); m_flags |= kPrimHasRotateAxes; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotateOrientation(const MQuaternion &q, MSpace::Space space, bool balance) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotateOrientation %f %f %f %f\n", q.x, q.y, q.z, q.w); MStatus status = MPxTransformationMatrix::setRotateOrientation(q, space, balance); if(status) { m_rotateOrientationFromUsd = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); } if(pushToPrimAvailable()) { if(primHasRotateAxes()) { } else if(!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) { insertRotateAxesOp(); } pushRotateAxisToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotateOrientation(const MEulerRotation& euler, MSpace::Space space, bool balance) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotateOrientation %f %f %f\n", euler.x, euler.y, euler.z); MStatus status = MPxTransformationMatrix::setRotateOrientation(euler, space, balance); if(status) { m_rotateOrientationFromUsd = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); } if(pushToPrimAvailable()) { if(primHasRotateAxes()) { } else if(!pushPrimToMatrix() && euler != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) { insertRotateAxesOp(); } pushRotateAxisToPrim(); } return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::notifyProxyShapeOfRedraw() { // Anytime we update the xform, we need to tell the proxy shape that it // needs to redraw itself MObject tn(m_transformNode.object()); if (!tn.isNull()) { MStatus status; MFnDependencyNode mfn(tn, &status); if (status && mfn.typeId() == Transform::kTypeId) { auto xform = static_cast<Transform*>(mfn.userNode()); MObject proxyObj = xform->getProxyShape(); if (!proxyObj.isNull()) { MFnDependencyNode proxyMfn(proxyObj); if (proxyMfn.typeId() == ProxyShape::kTypeId) { GfMatrix4d oldMatrix; bool oldResetsStack; m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); // We check that the matrix actually HAS changed, as this function will be // called when, ie, pushToPrim is toggled, which often happens on node // creation, when nothing has actually changed GfMatrix4d newMatrix; bool newResetsStack; m_xform.GetLocalTransformation(&newMatrix, &newResetsStack, getTimeCode()); if (newMatrix != oldMatrix || newResetsStack != oldResetsStack) { MHWRender::MRenderer::setGeometryDrawDirty(proxyObj); } } } } } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushTranslateToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTranslateToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kTranslate) { UsdGeomXformOp& op = *it; internal_pushVector(MPxTransformationMatrix::translationValue, op); m_translationFromUsd = MPxTransformationMatrix::translationValue; m_translationTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushPivotToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushPivotToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kPivot) { UsdGeomXformOp& op = *it; // is this a bug? internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; m_rotatePivotTweak = MPoint(0, 0, 0); m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; m_scalePivotTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotatePivotToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotatePivotToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kRotatePivot) { UsdGeomXformOp& op = *it; internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; m_rotatePivotTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotatePivotTranslateToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotatePivotTranslateToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kRotatePivotTranslate) { UsdGeomXformOp& op = *it; internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); m_rotatePivotTranslationFromUsd = MPxTransformationMatrix::rotatePivotTranslationValue; m_rotatePivotTranslationTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotateToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kRotate) { UsdGeomXformOp& op = *it; internal_pushRotation(MPxTransformationMatrix::rotationValue, op); m_rotationFromUsd = MPxTransformationMatrix::rotationValue; m_rotationTweak = MEulerRotation(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotateAxisToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateAxisToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kRotateAxis) { UsdGeomXformOp& op = *it; const double radToDeg = 180.0 / 3.141592654; MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); internal_pushVector(vec, op); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScalePivotTranslateToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScalePivotTranslateToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kScalePivotTranslate) { UsdGeomXformOp& op = *it; internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); m_scalePivotTranslationFromUsd = MPxTransformationMatrix::scalePivotTranslationValue; m_scalePivotTranslationTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScalePivotToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScalePivotToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kScalePivot) { UsdGeomXformOp& op = *it; internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; m_scalePivotTweak = MPoint(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScaleToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScaleToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kScale) { UsdGeomXformOp& op = *it; internal_pushVector(MPxTransformationMatrix::scaleValue, op); m_scaleFromUsd = MPxTransformationMatrix::scaleValue; m_scaleTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushShearToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushShearToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kShear) { UsdGeomXformOp& op = *it; internal_pushShear(MPxTransformationMatrix::shearValue, op); m_shearFromUsd = MPxTransformationMatrix::shearValue; m_shearTweak = MVector(0, 0, 0); return; } } // incase not found pushTransformToPrim(); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushTransformToPrim() { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTransformToPrim\n"); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { if(*opIt == kTransform) { UsdGeomXformOp& op = *it; if(pushPrimToMatrix()) { internal_pushMatrix(asMatrix(), op); } return; } } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushToPrim() { // if not yet intiaialised, do not execute this code! (It will crash!). if(!m_prim) return; TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushToPrim\n"); GfMatrix4d oldMatrix; bool oldResetsStack; m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); auto opIt = m_orderedOps.begin(); for(std::vector<UsdGeomXformOp>::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) { UsdGeomXformOp& op = *it; switch(*opIt) { case kTranslate: { internal_pushVector(MPxTransformationMatrix::translationValue, op); m_translationFromUsd = MPxTransformationMatrix::translationValue; m_translationTweak = MVector(0, 0, 0); } break; case kPivot: { // is this a bug? internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; m_rotatePivotTweak = MPoint(0, 0, 0); m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; m_scalePivotTweak = MVector(0, 0, 0); } break; case kRotatePivotTranslate: { internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); m_rotatePivotTranslationFromUsd = MPxTransformationMatrix::rotatePivotTranslationValue; m_rotatePivotTranslationTweak = MVector(0, 0, 0); } break; case kRotatePivot: { internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; m_rotatePivotTweak = MPoint(0, 0, 0); } break; case kRotate: { internal_pushRotation(MPxTransformationMatrix::rotationValue, op); m_rotationFromUsd = MPxTransformationMatrix::rotationValue; m_rotationTweak = MEulerRotation(0, 0, 0); } break; case kRotateAxis: { const double radToDeg = 180.0 / 3.141592654; MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); internal_pushVector(vec, op); } break; case kRotatePivotInv: { } break; case kScalePivotTranslate: { internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); m_scalePivotTranslationFromUsd = MPxTransformationMatrix::scalePivotTranslationValue; m_scalePivotTranslationTweak = MVector(0, 0, 0); } break; case kScalePivot: { internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; m_scalePivotTweak = MPoint(0, 0, 0); } break; case kShear: { internal_pushShear(MPxTransformationMatrix::shearValue, op); m_shearFromUsd = MPxTransformationMatrix::shearValue; m_shearTweak = MVector(0, 0, 0); } break; case kScale: { internal_pushVector(MPxTransformationMatrix::scaleValue, op); m_scaleFromUsd = MPxTransformationMatrix::scaleValue; m_scaleTweak = MVector(0, 0, 0); } break; case kScalePivotInv: { } break; case kPivotInv: { } break; case kTransform: { if(pushPrimToMatrix()) { internal_pushMatrix(asMatrix(), op); } } break; case kUnknownOp: { } break; } } notifyProxyShapeOfRedraw(); } //---------------------------------------------------------------------------------------------------------------------- MMatrix TransformationMatrix::asMatrix() const { MMatrix m = MPxTransformationMatrix::asMatrix(); const double x = m_localTranslateOffset.x; const double y = m_localTranslateOffset.y; const double z = m_localTranslateOffset.z; m[3][0] += m[0][0] * x; m[3][1] += m[0][1] * x; m[3][2] += m[0][2] * x; m[3][0] += m[1][0] * y; m[3][1] += m[1][1] * y; m[3][2] += m[1][2] * y; m[3][0] += m[2][0] * z; m[3][1] += m[2][1] * z; m[3][2] += m[2][2] * z; // Let Maya know what the matrix should be return m; } //---------------------------------------------------------------------------------------------------------------------- MMatrix TransformationMatrix::asMatrix(double percent) const { MMatrix m = MPxTransformationMatrix::asMatrix(percent); const double x = m_localTranslateOffset.x * percent; const double y = m_localTranslateOffset.y * percent; const double z = m_localTranslateOffset.z * percent; m[3][0] += m[0][0] * x; m[3][1] += m[0][1] * x; m[3][2] += m[0][2] * x; m[3][0] += m[1][0] * y; m[3][1] += m[1][1] * y; m[3][2] += m[1][2] * y; m[3][0] += m[2][0] * z; m[3][1] += m[2][1] * z; m[3][2] += m[2][2] * z; return m; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::enableReadAnimatedValues(bool enabled) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enableReadAnimatedValues\n"); if(enabled) m_flags |= kReadAnimatedValues; else m_flags &= ~kReadAnimatedValues; // if not yet intiaialised, do not execute this code! (It will crash!). if(!m_prim) return; // if we are enabling push to prim, we need to see if anything has changed on the transform since the last time // the values were synced. I'm assuming that if a given transform attribute is not the same as the default, or // the prim already has a transform op for that attribute, then just call a method to make a minor adjustment // of nothing. This will call my code that will magically construct the transform ops in the right order. if(enabled) { const MVector nullVec(0, 0, 0); const MVector oneVec(1.0, 1.0, 1.0); const MPoint nullPoint(0, 0, 0); const MQuaternion nullQuat(0, 0, 0, 1.0); if(!pushPrimToMatrix()) { if(primHasTranslation() || translation() != nullVec) translateBy(nullVec); if(primHasScale() || scale() != oneVec) scaleBy(oneVec); if(primHasShear() || shear() != nullVec) shearBy(nullVec); if(primHasScalePivot() || scalePivot() != nullPoint) setScalePivot(scalePivot(), MSpace::kTransform, false); if(primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); if(primHasRotatePivot() || rotatePivot() != nullPoint) setRotatePivot(rotatePivot(), MSpace::kTransform, false); if(primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); if(primHasRotation() || rotation() != nullQuat) rotateBy(nullQuat); if(primHasRotateAxes() || rotateOrientation() != nullQuat) setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); } else if(primHasTransform()) { auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); if (transformIt != m_orderedOps.end() ) { internal_pushMatrix(asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); } } } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::enablePushToPrim(bool enabled) { TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enablePushToPrim\n"); if(enabled) m_flags |= kPushToPrimEnabled; else m_flags &= ~kPushToPrimEnabled; // if not yet intiaialised, do not execute this code! (It will crash!). if(!m_prim) return; // if we are enabling push to prim, we need to see if anything has changed on the transform since the last time // the values were synced. I'm assuming that if a given transform attribute is not the same as the default, or // the prim already has a transform op for that attribute, then just call a method to make a minor adjustment // of nothing. This will call my code that will magically construct the transform ops in the right order. if(enabled && getTimeCode() == UsdTimeCode::Default()) { const MVector nullVec(0, 0, 0); const MVector oneVec(1.0, 1.0, 1.0); const MPoint nullPoint(0, 0, 0); const MQuaternion nullQuat(0, 0, 0, 1.0); if(!pushPrimToMatrix()) { if(primHasTranslation() || translation() != nullVec) translateTo(translation()); if(primHasScale() || scale() != oneVec) scaleTo(scale()); if(primHasShear() || shear() != nullVec) shearTo(shear()); if(primHasScalePivot() || scalePivot() != nullPoint) setScalePivot(scalePivot(), MSpace::kTransform, false); if(primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); if(primHasRotatePivot() || rotatePivot() != nullPoint) setRotatePivot(rotatePivot(), MSpace::kTransform, false); if(primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); if(primHasRotation() || rotation() != nullQuat) rotateTo(rotation()); if(primHasRotateAxes() || rotateOrientation() != nullQuat) setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); } else if(primHasTransform()) { auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); if (transformIt != m_orderedOps.end() ) { internal_pushMatrix(asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); } } } } //---------------------------------------------------------------------------------------------------------------------- } // nodes } // usdmaya } // AL //----------------------------------------------------------------------------------------------------------------------
{ "pile_set_name": "Github" }
--- layout: layout title: Pjax type: page nav: nav class: style-api style-api-detail --- # Pjax ## Typings <a href="https://github.com/falsandtru/pjax-api/blob/master/pjax-api.d.ts" target="_blank">pjax-api.d.ts</a> ## new Pjax(config: Config): Pjax Use pjax. ```ts import Pjax from 'pjax-api'; new Pjax({ areas: [ '#header, #primary', '#container', 'body' ] }); ``` ## Config [Config]({{ site.basepath }}api/pjax/config/) ## #assign(url: string): boolean Go to URL. The return type means the request is accepted or not. In other words, in progress or not. The same shall apply hereinafter. ```ts new Pjax({}).assign('/'); ``` ## #replace(url: string): boolean Go to URL with replacing. ```ts new Pjax({}).replace('/'); ``` ## .assign(url: string, config: Config): boolean Go to URL. ```ts Pjax.assign('/', {}); ``` ## .replace(url: string, config: Config): boolean Go to URL with replacing. ```ts Pjax.replace('/', {}); ``` ## .sync(isPjaxPage?: boolean): void Cancel the current page transition and sync the internal status. You **MUST** call Pjax.sync after calling history.pushState and history.replaceState. ```ts history.pushState(null, 'title', '/path'); Pjax.sync(); ``` ```ts history.replaceState(null, 'title', '/path'); Pjax.sync(true); ``` ## .pushURL(url: string, title: string, state: any = null): void The alias of history.pushState and Pjax.sync. ```ts Pjax.pushURL('/path', 'title'); ``` ## .replaceURL(url: string, title: string, state: any = history.state): void The alias of history.replaceState and Pjax.sync. ```ts Pjax.replaceURL('/path', 'title'); ```
{ "pile_set_name": "Github" }
resolver: lts-14.18
{ "pile_set_name": "Github" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.11 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.badlogic.gdx.physics.bullet.linearmath; public class SWIGTYPE_p_btAlignedObjectArrayT_btPlane_t { private transient long swigCPtr; protected SWIGTYPE_p_btAlignedObjectArrayT_btPlane_t(long cPtr, @SuppressWarnings("unused") boolean futureUse) { swigCPtr = cPtr; } protected SWIGTYPE_p_btAlignedObjectArrayT_btPlane_t() { swigCPtr = 0; } protected static long getCPtr(SWIGTYPE_p_btAlignedObjectArrayT_btPlane_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } }
{ "pile_set_name": "Github" }
# Run-time configuration RedisTimeSeries supports a few run-time configuration options that should be determined when loading the module. In time more options will be added. ## Passing Configuration Options During Loading In general, passing configuration options is done by appending arguments after the `--loadmodule` argument in the command line, `loadmodule` configuration directive in a Redis config file, or the `MODULE LOAD` command. For example: In redis.conf: ``` loadmodule redistimeseries.so OPT1 OPT2 ``` From redis-cli: ``` 127.0.0.6379> MODULE load redistimeseries.so OPT1 OPT2 ``` From command line: ``` $ redis-server --loadmodule ./redistimeseries.so OPT1 OPT2 ``` ## RedisTimeSeries configuration options ### COMPACTION_POLICY {policy} Default compaction/downsampling rules for newly created key with `TS.ADD`. Each rule is separated by a semicolon (`;`), the rule consists of several fields that are separated by a colon (`:`): * aggregation function - avg, sum, min, max, count, first, last * time bucket - number and the time representation (Example for 1 minute: 1M) * m - millisecond * M - minute * s - seconds * d - day * retention time - in milliseconds Example: `max:1M:1h` - Aggregate using max over 1 minute and retain the last 1 hour #### Default <Empty> #### Example ``` $ redis-server --loadmodule ./redistimeseries.so COMPACTION_POLICY max:1m:1h;min:10s:5d:10d;last:5M:10ms;avg:2h:10d;avg:3d:100d ``` ### RETENTION_POLICY Maximum age for samples compared to last event time (in milliseconds) per key, this configuration will set the default retention for newly created keys that do not have a an override. #### Default 0 #### Example ``` $ redis-server --loadmodule ./redistimeseries.so RETENTION_POLICY 20 ``` ### DUPLICATE_POLICY Policy that will define handling of duplicate samples. The following are the possible policies: * `BLOCK` - an error will occur for any out of order sample * `FIRST` - ignore the new value * `LAST` - override with latest value * `MIN` - only override if the value is lower than the existing value * `MAX` - only override if the value is higher than the existing value #### Precedence order Since the duplication policy can be provided at different levels, the actual precedence of the used policy will be: 1. TS.ADD input 2. Key level policy 3. Module configuration (AKA database-wide) #### Default configuration The default policy for database-wide is `BLOCK`, new and pre-existing keys will have no default policy. #### Example ``` $ redis-server --loadmodule ./redistimeseries.so DUPLICATE_POLICY LAST ```
{ "pile_set_name": "Github" }
################################################################################ # # iucode-tool # ################################################################################ IUCODE_TOOL_VERSION = 2.3.1 IUCODE_TOOL_SOURCE = iucode-tool_$(IUCODE_TOOL_VERSION).tar.xz IUCODE_TOOL_SITE = https://gitlab.com/iucode-tool/releases/raw/master ifeq ($(BR2_PACKAGE_ARGP_STANDALONE),y) IUCODE_TOOL_DEPENDENCIES = argp-standalone endif IUCODE_TOOL_LICENSE = GPL-2.0+ IUCODE_TOOL_LICENSE_FILES = COPYING define IUCODE_TOOL_INSTALL_INIT_SYSV $(INSTALL) -D -m 0755 package/iucode-tool/S00iucode-tool \ $(TARGET_DIR)/etc/init.d/S00iucode-tool endef define IUCODE_TOOL_INSTALL_INIT_SYSTEMD $(INSTALL) -D -m 644 package/iucode-tool/iucode.service \ $(TARGET_DIR)/usr/lib/systemd/system/iucode.service mkdir -p $(TARGET_DIR)/etc/systemd/system/multi-user.target.wants ln -sf ../../../../usr/lib/systemd/system/iucode.service \ $(TARGET_DIR)/etc/systemd/system/multi-user.target.wants/iucode.service endef $(eval $(autotools-package))
{ "pile_set_name": "Github" }
/*------------------------------------------------------------------------- * * lockcmds.h * prototypes for lockcmds.c. * * * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/commands/lockcmds.h * *------------------------------------------------------------------------- */ #ifndef LOCKCMDS_H #define LOCKCMDS_H #include "nodes/parsenodes.h" /* * LOCK */ extern void LockTableCommand(LockStmt *lockstmt); #endif /* LOCKCMDS_H */
{ "pile_set_name": "Github" }
{ "name": "CheckMyLinks", "description": "Check My Links is a link checker that crawls through your webpage and looks for broken links.", "author": "PageModified", "version": "3.8.1", "devDependencies": { "jshint": "^2.6.0" }, "scripts": { "test": "jshint --exclude ./node_modules ." } }
{ "pile_set_name": "Github" }
package com.tencent.mm.plugin.appbrand.jsapi.file; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.plugin.appbrand.appstorage.j; import com.tencent.mm.plugin.appbrand.jsapi.c; import com.tencent.mm.plugin.appbrand.jsapi.file.f.a; import org.json.JSONObject; final class am extends d { am() { } /* Access modifiers changed, original: final */ public final a a(c cVar, String str, JSONObject jSONObject) { String str2; AppMethodBeat.i(102815); if (cVar.asE().yd(str) == j.OK) { str2 = "ok"; } else { str2 = String.format("fail no such file or directory \"%s\"", new Object[]{str}); } a aVar = new a(str2, new Object[0]); AppMethodBeat.o(102815); return aVar; } }
{ "pile_set_name": "Github" }
@import (reference) "../../../assets/css/index"; @popover-prefix-cls: ~"@{fishd-prefix}-popover"; .@{popover-prefix-cls} { .reset-component; position: absolute; top: 0; left: 0; z-index: @zindex-popover; cursor: auto; user-select: text; white-space: normal; font-weight: normal; text-align: left; &:after { content: ""; position: absolute; background: rgba(255, 255, 255, 0.01); } &-hidden { display: none; } // Offset the popover to account for the popover arrow &-placement-top, &-placement-topLeft, &-placement-topRight { padding-bottom: @popover-distance; } &-placement-right, &-placement-rightTop, &-placement-rightBottom { padding-left: @popover-distance; } &-placement-bottom, &-placement-bottomLeft, &-placement-bottomRight { padding-top: @popover-distance; } &-placement-left, &-placement-leftTop, &-placement-leftBottom { padding-right: @popover-distance; } &-inner { background-color: @popover-bg; background-clip: padding-box; border-radius: @border-radius-base; box-shadow: @box-shadow-base; } &-title { min-width: @popover-min-width; margin: 0; // reset heading margin padding: 5px @padding-md 4px; min-height: 32px; border-bottom: 1px solid @border-color-split; color: @heading-color; font-weight: 500; } &-inner-content { padding: 12px @padding-md; color: @popover-color; } &-message { padding: 4px 0 12px; font-size: @font-size-base; color: @popover-color; > .@{iconfont-prefix} { color: @warning-color; line-height: @line-height-base + 0.1; position: absolute; } &-title { padding-left: @font-size-base + 8px; } } &-buttons { text-align: right; margin-bottom: 4px; button { margin-left: 8px; } } // Arrows // .popover-arrow is outer, .popover-arrow:after is inner &-arrow { background: @popover-bg; width: sqrt(@popover-arrow-width * @popover-arrow-width * 2); height: sqrt(@popover-arrow-width * @popover-arrow-width * 2); transform: rotate(45deg); position: absolute; display: block; border-color: transparent; border-style: solid; } &-placement-top > &-content > &-arrow, &-placement-topLeft > &-content > &-arrow, &-placement-topRight > &-content > &-arrow { bottom: @popover-distance - @popover-arrow-width + 1.5px; box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07); } &-placement-top > &-content > &-arrow { left: 50%; transform: translateX(-50%) rotate(45deg); } &-placement-topLeft > &-content > &-arrow { left: 16px; } &-placement-topRight > &-content > &-arrow { right: 16px; } &-placement-right > &-content > &-arrow, &-placement-rightTop > &-content > &-arrow, &-placement-rightBottom > &-content > &-arrow { left: @popover-distance - @popover-arrow-width + 2px; box-shadow: -3px 3px 7px rgba(0, 0, 0, 0.07); } &-placement-right > &-content > &-arrow { top: 50%; transform: translateY(-50%) rotate(45deg); } &-placement-rightTop > &-content > &-arrow { top: 12px; } &-placement-rightBottom > &-content > &-arrow { bottom: 12px; } &-placement-bottom > &-content > &-arrow, &-placement-bottomLeft > &-content > &-arrow, &-placement-bottomRight > &-content > &-arrow { top: @popover-distance - @popover-arrow-width + 2px; box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.06); } &-placement-bottom > &-content > &-arrow { left: 50%; transform: translateX(-50%) rotate(45deg); } &-placement-bottomLeft > &-content > &-arrow { left: 16px; } &-placement-bottomRight > &-content > &-arrow { right: 16px; } &-placement-left > &-content > &-arrow, &-placement-leftTop > &-content > &-arrow, &-placement-leftBottom > &-content > &-arrow { right: @popover-distance - @popover-arrow-width + 2px; box-shadow: 3px -3px 7px rgba(0, 0, 0, 0.07); } &-placement-left > &-content > &-arrow { top: 50%; transform: translateY(-50%) rotate(45deg); } &-placement-leftTop > &-content > &-arrow { top: 12px; } &-placement-leftBottom > &-content > &-arrow { bottom: 12px; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleDisplayName</key> <string>GitTouch</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>git_touch</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>$(FLUTTER_BUILD_NAME)</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <string>gittouch</string> </array> </dict> </array> <key>CFBundleVersion</key> <string>$(FLUTTER_BUILD_NUMBER)</string> <key>LSApplicationQueriesSchemes</key> <array> <string>itms</string> </array> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UIViewControllerBasedStatusBarAppearance</key> <false/> </dict> </plist>
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, ООО 1С-Софт // Все права защищены. Эта программа и сопроводительные материалы предоставляются // в соответствии с условиями лицензии Attribution 4.0 International (CC BY 4.0) // Текст лицензии доступен по ссылке: // https://creativecommons.org/licenses/by/4.0/legalcode /////////////////////////////////////////////////////////////////////////////////////////////////////// #Область ОбработчикиСобытийФормы &НаСервере Процедура ПриСозданииНаСервере(Отказ, СтандартнаяОбработка) ОбменДаннымиСервер.ПроверитьВозможностьАдминистрированияОбменов(); ПроверитьВозможностьНастройкиСинхронизацииДанных(Отказ); Если Отказ Тогда Возврат; КонецЕсли; ПараметрыОбработчика = Неопределено; ПриНачалеПолученияВариантовНастроекОбменаДаннымиНаСервере(УникальныйИдентификатор, ПараметрыОбработчика, ДлительнаяОперация); КонецПроцедуры &НаКлиенте Процедура ПриОткрытии(Отказ) ПриНачалеПолученияВариантовНастроекОбменаДанными(Истина); КонецПроцедуры &НаКлиенте Процедура ОбработкаНавигационнойСсылки(НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка) СтрокиКоманды = КомандыСозданияОбмена.НайтиСтроки( Новый Структура("НавигационнаяСсылка", НавигационнаяСсылкаФорматированнойСтроки)); Если СтрокиКоманды.Количество() = 0 Тогда Возврат; КонецЕсли; СтрокаКоманды = СтрокиКоманды[0]; СтандартнаяОбработка = Ложь; ПараметрыПомощника = Новый Структура; ПараметрыПомощника.Вставить("ИмяПланаОбмена", СтрокаКоманды.ИмяПланаОбмена); ПараметрыПомощника.Вставить("ИдентификаторНастройки", СтрокаКоманды.ИдентификаторНастройки); ПараметрыПомощника.Вставить("ОписаниеВариантаНастройки", СтрокаКоманды.ОписаниеВариантаНастройки); ПараметрыПомощника.Вставить("ОбменДаннымиСВнешнейСистемой", СтрокаКоманды.ВнешняяСистема); ПараметрыПомощника.Вставить("ПараметрыПодключенияВнешнейСистемы", СтрокаКоманды.ПараметрыПодключенияВнешнейСистемы); ПараметрыПомощника.Вставить("НастройкаНовойСинхронизации"); КлючУникальностиПомощника = ПараметрыПомощника.ИмяПланаОбмена + "_" + ПараметрыПомощника.ИдентификаторНастройки; ОткрытьФорму("Обработка.ПомощникСозданияОбменаДанными.Форма.НастройкаСинхронизации", ПараметрыПомощника, , КлючУникальностиПомощника); Закрыть(); КонецПроцедуры #КонецОбласти #Область ОбработчикиСобытийЭлементовШапкиФормы &НаКлиенте Процедура ДекорацияНадписьВнешниеСистемыОшибкаОбработкаНавигационнойСсылки(Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка) Если НавигационнаяСсылкаФорматированнойСтроки = "ОткрытьЖурналРегистрации" Тогда СтандартнаяОбработка = Ложь; Если ОбщегоНазначенияКлиент.ПодсистемаСуществует("ИнтернетПоддержкаПользователей.ОбменДаннымиСВнешнимиСистемами") Тогда СобытиеЖурналаРегистрации = Новый Массив; МодульОбменДаннымиСВнешнимиСистемамиКлиент = ОбщегоНазначенияКлиент.ОбщийМодуль("ОбменДаннымиСВнешнимиСистемамиКлиент"); СобытиеЖурналаРегистрации.Добавить(МодульОбменДаннымиСВнешнимиСистемамиКлиент.ИмяСобытияЖурналаРегистрации()); Отбор = Новый Структура; Отбор.Вставить("СобытиеЖурналаРегистрации", СобытиеЖурналаРегистрации); Отбор.Вставить("Уровень", "Ошибка"); Отбор.Вставить("ДатаНачала", ДатаНачалаОтбораЖурналаРегистрации()); ЖурналРегистрацииКлиент.ОткрытьЖурналРегистрации(Отбор, ЭтотОбъект); КонецЕсли; КонецЕсли; КонецПроцедуры #КонецОбласти #Область ОбработчикиКомандФормы &НаКлиенте Процедура ОбновитьСписокНастроек(Команда) ПриНачалеПолученияВариантовНастроекОбменаДанными(); КонецПроцедуры &НаКлиенте Процедура ПодключитьИнтернетПоддержку(Команда) Если ОбщегоНазначенияКлиент.ПодсистемаСуществует("ИнтернетПоддержкаПользователей") Тогда ОповещениеОЗакрытии = Новый ОписаниеОповещения("ПодключитьИнтернетПоддержкуЗавершение", ЭтотОбъект); МодульИнтернетПоддержкаПользователейКлиент = ОбщегоНазначенияКлиент.ОбщийМодуль("ИнтернетПоддержкаПользователейКлиент"); МодульИнтернетПоддержкаПользователейКлиент.ПодключитьИнтернетПоддержкуПользователей(ОповещениеОЗакрытии, ЭтотОбъект); КонецЕсли; КонецПроцедуры #КонецОбласти #Область СлужебныеПроцедурыИФункции &НаСервереБезКонтекста Функция ДатаНачалаОтбораЖурналаРегистрации() Возврат НачалоДня(ТекущаяДатаСеанса()); КонецФункции &НаКлиенте Процедура ПриНачалеПолученияВариантовНастроекОбменаДанными(ПриОткрытии = Ложь) Если Не ПриОткрытии Тогда ПараметрыОбработчика = Неопределено; ПриНачалеПолученияВариантовНастроекОбменаДаннымиНаСервере(УникальныйИдентификатор, ПараметрыОбработчика, ДлительнаяОперация); КонецЕсли; Если ДлительнаяОперация Тогда Элементы.ПанельВариантыНастроек.ТекущаяСтраница = Элементы.СтраницаОжидание; Элементы.ФормаОбновитьСписокНастроек.Доступность = Ложь; ОбменДаннымиКлиент.ИнициализироватьПараметрыОбработчикаОжидания(ПараметрыОбработчикаОжидания); ПодключитьОбработчикОжидания("ПриОжиданииПолученияВариантовНастроекОбменаДанными", ПараметрыОбработчикаОжидания.ТекущийИнтервал, Истина); Иначе ПриЗавершенииПолученияВариантовНастроекОбменаДанными(); КонецЕсли; КонецПроцедуры &НаКлиенте Процедура ПриОжиданииПолученияВариантовНастроекОбменаДанными() ПриОжиданииПолученияВариантовНастроекОбменаДаннымиНаСервере(ПараметрыОбработчика, ДлительнаяОперация); Если ДлительнаяОперация Тогда ОбменДаннымиКлиент.ОбновитьПараметрыОбработчикаОжидания(ПараметрыОбработчикаОжидания); ПодключитьОбработчикОжидания("ПриОжиданииПолученияВариантовНастроекОбменаДанными", ПараметрыОбработчикаОжидания.ТекущийИнтервал, Истина); Иначе ПриЗавершенииПолученияВариантовНастроекОбменаДанными(); КонецЕсли; КонецПроцедуры &НаКлиенте Процедура ПриЗавершенииПолученияВариантовНастроекОбменаДанными() ПриЗавершенииПолученияВариантовНастроекОбменаДаннымиНаСервере(); КонецПроцедуры &НаКлиенте Процедура ПодключитьИнтернетПоддержкуЗавершение(Результат, ДополнительныеПараметры) Экспорт ПриНачалеПолученияВариантовНастроекОбменаДанными(); КонецПроцедуры &НаСервереБезКонтекста Процедура ПриНачалеПолученияВариантовНастроекОбменаДаннымиНаСервере(УникальныйИдентификатор, ПараметрыОбработчика, ПродолжитьОжидание) МодульПомощника = ОбменДаннымиСервер.МодульПомощникСозданияОбменаДанными(); МодульПомощника.ПриНачалеПолученияВариантовНастроекОбменаДанными(УникальныйИдентификатор, ПараметрыОбработчика, ПродолжитьОжидание); КонецПроцедуры &НаСервереБезКонтекста Процедура ПриОжиданииПолученияВариантовНастроекОбменаДаннымиНаСервере(ПараметрыОбработчика, ПродолжитьОжидание) МодульПомощника = ОбменДаннымиСервер.МодульПомощникСозданияОбменаДанными(); МодульПомощника.ПриОжиданииПолученияВариантовНастроекОбменаДанными(ПараметрыОбработчика, ПродолжитьОжидание); КонецПроцедуры &НаСервере Процедура ПриЗавершенииПолученияВариантовНастроекОбменаДаннымиНаСервере() Настройки = Неопределено; МодульПомощника = ОбменДаннымиСервер.МодульПомощникСозданияОбменаДанными(); МодульПомощника.ПриЗавершенииПолученияВариантовНастроекОбменаДанными(ПараметрыОбработчика, Настройки); ОчиститьКомандыСозданияНовогоОбмена(); ДобавитьКомандыСозданияНовогоОбмена(Настройки); Элементы.ПанельВариантыНастроек.ТекущаяСтраница = Элементы.СтраницаВариантыНастроек; Элементы.ФормаОбновитьСписокНастроек.Доступность = Истина; КонецПроцедуры &НаСервере Процедура ОчиститьКомандыСозданияНовогоОбмена() КомандыСозданияОбмена.Очистить(); УдалитьПодчиненныеЭлементыГруппы(Элементы.ГруппаОбменДругиеПрограммы); УдалитьПодчиненныеЭлементыГруппы(Элементы.ГруппаОбменРИБ); УдалитьПодчиненныеЭлементыГруппы(Элементы.СтраницаВнешниеСистемыВариантыНастроек); КонецПроцедуры &НаСервере Процедура УдалитьПодчиненныеЭлементыГруппы(ЭлементГруппа) Пока ЭлементГруппа.ПодчиненныеЭлементы.Количество() > 0 Цикл Элементы.Удалить(ЭлементГруппа.ПодчиненныеЭлементы[0]); КонецЦикла; КонецПроцедуры &НаСервере Процедура ДобавитьКомандыСозданияНовогоОбмена(Настройки) СтандартныеНастройки = Неопределено; Если Настройки.Свойство("СтандартныеНастройки", СтандартныеНастройки) Тогда ТаблицаНастройкиДругиеПрограммы = СтандартныеНастройки.Скопировать(Новый Структура("ЭтоПланОбменаРИБ", Ложь)); ТаблицаНастройкиДругиеПрограммы.Сортировать("ЭтоПланОбменаXDTO"); ДобавитьКомандыСозданияНовогоОбменаСтандартныеНастройки(ТаблицаНастройкиДругиеПрограммы, Элементы.ГруппаОбменДругиеПрограммы); ТаблицаНастройкиРИБ = СтандартныеНастройки.Скопировать(Новый Структура("ЭтоПланОбменаРИБ", Истина)); ДобавитьКомандыСозданияНовогоОбменаСтандартныеНастройки(ТаблицаНастройкиРИБ, Элементы.ГруппаОбменРИБ); КонецЕсли; НастройкиВнешниеСистемы = Неопределено; Если Настройки.Свойство("НастройкиВнешниеСистемы", НастройкиВнешниеСистемы) Тогда Элементы.ГруппаОбменВнешниеСистемы.Видимость = Истина; Если НастройкиВнешниеСистемы.КодОшибки = "" Тогда Если НастройкиВнешниеСистемы.ВариантыНастроек.Количество() > 0 Тогда ДобавитьКомандыСозданияНовогоОбменаНастройкиВнешниеСистемы( НастройкиВнешниеСистемы.ВариантыНастроек, Элементы.СтраницаВнешниеСистемыВариантыНастроек); Элементы.ПанельОбменВнешниеСистемы.ТекущаяСтраница = Элементы.СтраницаВнешниеСистемыВариантыНастроек; Иначе Элементы.ПанельОбменВнешниеСистемы.ТекущаяСтраница = Элементы.СтраницаВнешниеСистемыНетВариантовНастроек; КонецЕсли; ИначеЕсли НастройкиВнешниеСистемы.КодОшибки = "НеверныйЛогинИлиПароль" Тогда Если ОбщегоНазначения.РазделениеВключено() И ОбщегоНазначения.ДоступноИспользованиеРазделенныхДанных() Тогда Элементы.ПанельОбменВнешниеСистемы.ТекущаяСтраница = Элементы.СтраницаВнешниеСистемыНеПодключенаИнтернетПоддержкаВМоделиСервиса; Иначе Элементы.ПанельОбменВнешниеСистемы.ТекущаяСтраница = Элементы.СтраницаВнешниеСистемыНеПодключенаИнтернетПоддержка; КонецЕсли; ИначеЕсли ЗначениеЗаполнено(НастройкиВнешниеСистемы.КодОшибки) Тогда Элементы.ПанельОбменВнешниеСистемы.ТекущаяСтраница = Элементы.СтраницаВнешниеСистемыОшибка; КонецЕсли; Иначе Элементы.ГруппаОбменВнешниеСистемы.Видимость = Ложь; КонецЕсли; КонецПроцедуры &НаСервере Процедура ДобавитьКомандыСозданияНовогоОбменаСтандартныеНастройки(ТаблицаНастройки, РодительскаяГруппа) ТаблицаКонфигурации = ТаблицаНастройки.Скопировать(, "ИмяКонфигурацииКорреспондента"); ТаблицаКонфигурации.Свернуть("ИмяКонфигурацииКорреспондента"); Для Каждого СтрокаКонфигурация Из ТаблицаКонфигурации Цикл СтрокиНастройки = ТаблицаНастройки.НайтиСтроки( Новый Структура("ИмяКонфигурацииКорреспондента", СтрокаКонфигурация.ИмяКонфигурацииКорреспондента)); Для Каждого СтрокаНастройки Из СтрокиНастройки Цикл ОписаниеВариантаНастройки = СтруктураОписанияВариантаНастройки(); ЗаполнитьЗначенияСвойств(ОписаниеВариантаНастройки, СтрокаНастройки); ОписаниеВариантаНастройки.НаименованиеКорреспондента = СтрокаНастройки.НаименованиеКонфигурацииКорреспондента; ДобавитьКомандуСозданияНовогоОбменаДляВариантаНастройки( РодительскаяГруппа, СтрокаНастройки.ИмяПланаОбмена, СтрокаНастройки.ИдентификаторНастройки, ОписаниеВариантаНастройки); КонецЦикла; КонецЦикла; КонецПроцедуры &НаСервере Процедура ДобавитьКомандыСозданияНовогоОбменаНастройкиВнешниеСистемы(ВариантыНастроек, РодительскаяГруппа) Для Каждого ВариантНастроек Из ВариантыНастроек Цикл ОписаниеВариантаНастройки = СтруктураОписанияВариантаНастройки(); ЗаполнитьЗначенияСвойств(ОписаниеВариантаНастройки, ВариантНастроек); ДобавитьКомандуСозданияНовогоОбменаДляВариантаНастройки( РодительскаяГруппа, ВариантНастроек.ИмяПланаОбмена, ВариантНастроек.ИдентификаторНастройки, ОписаниеВариантаНастройки, Истина, ВариантНастроек.ПараметрыПодключения); КонецЦикла; КонецПроцедуры &НаСервере Процедура ДобавитьКомандуСозданияНовогоОбменаДляВариантаНастройки( РодительскаяГруппа, ИмяПланаОбмена, ИдентификаторНастройки, ОписаниеВариантаНастройки, ВнешняяСистема = Ложь, ПараметрыПодключенияВнешнейСистемы = Неопределено) НавигационнаяСсылка = "Настройка" + ИмяПланаОбмена + "Вариант" + ИдентификаторНастройки; ЭлементСсылка = Элементы.Добавить( "ДекорацияНадпись" + НавигационнаяСсылка, Тип("ДекорацияФормы"), РодительскаяГруппа); ЭлементСсылка.Вид = ВидДекорацииФормы.Надпись; ЭлементСсылка.Заголовок = Новый ФорматированнаяСтрока( ОписаниеВариантаНастройки.ЗаголовокКомандыДляСозданияНовогоОбменаДанными, , , , НавигационнаяСсылка); ЭлементСсылка.ОтображениеПодсказки = ОтображениеПодсказки.ОтображатьСнизу; ЭлементСсылка.АвтоМаксимальнаяШирина = Ложь; ЭлементСсылка.РасширеннаяПодсказка.Заголовок = ОписаниеВариантаНастройки.КраткаяИнформацияПоОбмену; ЭлементСсылка.РасширеннаяПодсказка.АвтоМаксимальнаяШирина = Ложь; СтрокаКоманда = КомандыСозданияОбмена.Добавить(); СтрокаКоманда.НавигационнаяСсылка = НавигационнаяСсылка; СтрокаКоманда.ИмяПланаОбмена = ИмяПланаОбмена; СтрокаКоманда.ИдентификаторНастройки = ИдентификаторНастройки; СтрокаКоманда.ОписаниеВариантаНастройки = ОписаниеВариантаНастройки; СтрокаКоманда.ВнешняяСистема = ВнешняяСистема; СтрокаКоманда.ПараметрыПодключенияВнешнейСистемы = ПараметрыПодключенияВнешнейСистемы; КонецПроцедуры &НаСервереБезКонтекста Функция СтруктураОписанияВариантаНастройки() МодульПомощник = ОбменДаннымиСервер.МодульПомощникСозданияОбменаДанными(); Возврат МодульПомощник.СтруктураОписанияВариантаНастройки(); КонецФункции &НаСервере Процедура ПроверитьВозможностьНастройкиСинхронизацииДанных(Отказ = Ложь) ТекстСообщения = ""; Если ОбщегоНазначения.РазделениеВключено() Тогда Если ОбщегоНазначения.ДоступноИспользованиеРазделенныхДанных() Тогда МодульОбменДаннымиВМоделиСервисаПовтИсп = ОбщегоНазначения.ОбщийМодуль("ОбменДаннымиВМоделиСервисаПовтИсп"); Если Не МодульОбменДаннымиВМоделиСервисаПовтИсп.СинхронизацияДанныхПоддерживается() Тогда ТекстСообщения = НСтр("ru = 'Возможность настройки синхронизации данных в данной программе не предусмотрена.'"); Отказ = Истина; КонецЕсли; Иначе ТекстСообщения = НСтр("ru = 'В неразделенном режиме настройка синхронизации данных с другими программами недоступна.'"); Отказ = Истина; КонецЕсли; Иначе СписокПлановОбмена = ОбменДаннымиПовтИсп.ПланыОбменаБСП(); Если СписокПлановОбмена.Количество() = 0 Тогда ТекстСообщения = НСтр("ru = 'Возможность настройки синхронизации данных в данной программе не предусмотрена.'"); Отказ = Истина; КонецЕсли; КонецЕсли; Если Отказ И Не ПустаяСтрока(ТекстСообщения) Тогда ОбщегоНазначения.СообщитьПользователю(ТекстСообщения); КонецЕсли; КонецПроцедуры #КонецОбласти
{ "pile_set_name": "Github" }
package qunar.tc.bistoury.attach.arthas.profiler; import java.util.concurrent.atomic.AtomicBoolean; /** * @author zhenyu.nie created on 2019 2019/12/31 17:35 */ public class GProfilerClients { private static volatile GProfilerClient client; private static AtomicBoolean init = new AtomicBoolean(false); public static GProfilerClient getInstance() { if (client != null) { return client; } else { throw new IllegalStateException("profiler client not available"); } } public static GProfilerClient create() { if (init.compareAndSet(false, true)) { client = new GProfilerClient(); return client; } else { throw new IllegalStateException("profiler client already created"); } } }
{ "pile_set_name": "Github" }
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Controllers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Controllers")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly:ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "pile_set_name": "Github" }
% % Description -- Verilog-AMS interface % % Copyright (C) 2007 Stefan Jahn <stefan@lkcc.org> % % Permission is granted to copy, distribute and/or modify this document % under the terms of the GNU Free Documentation License, Version 1.1 % or any later version published by the Free Software Foundation. % \tutsection{Introduction} Verilog-AMS is a hardware description language. It can be used to specify the analogue behaviour of compact device models. Usually these are C or C++ implementations in analogue simulators. The effort to implement modern compact models in C/C++ is quite high compared to the description in Verilog-AMS. \tutsection{ADMS} The software ADMS (see \url{http://mot-adms.sourceforge.net}) allows Verilog-AMS descriptions to be translated into any other programming language. It generates a structured XML tree representing the compact device model description. \begin{figure}[ht] \begin{center} \includegraphics[width=0.8\linewidth]{admsflow} \end{center} \caption{ADMS data flow} \label{fig:admsflow} \end{figure} \FloatBarrier The internal XML tree is used to generate ready-to-compile C or C++ code which is specific to the simulators API. The code generator is able to produce \begin{itemize} \item evaluation of device equations (current and charge) including their derivatives, \item glue code for the simulator API, \item documentation and \item any other data described by the original Verilog-AMS input file. \end{itemize} \tutsection{XML admst scripts} The language transformation uses a language named \textbf{admst}. It is itself a XML description. The command line in order to run a transformation is \begin{Verbatim}[fontsize=\small] $ admsXml <device.va> -e <interface-1.xml> -e <interface-2.xml> \end{Verbatim} From version 0.0.11 Qucs comes with the following Verilog-AMS transformers \begin{itemize} \item \verb+qucsMODULEcore.xml+\\ creating the actual analogue simulator implementation \item \verb+qucsMODULEdefs.xml+\\ creating the parameter descriptions for the analogue simulator \item \verb+qucsMODULEgui.xml+\\ creating the implementation for the GUI integration \item \verb+qucsVersion.xml+\\ basic admst library \item \verb+analogfunction.xml+\\ creating analogue function code \end{itemize} In order to create \textbf{admst} scripts for a simulator it is necessary to understand both, the simulator specific API and how the ADMS data tree items -- which are based on the Verilog-AMS source file describing the model -- relate to the API. \addvspace{12pt} The command lines for transforming a Verilog-AMS source file into the appropiate Qucs C++ source files are \begin{Verbatim}[fontsize=\small] $ admsXml <device.va> -e qucsVersion.xml -e qucsMODULEcore.xml $ admsXml <device.va> -e qucsVersion.xml -e qucsMODULEgui.xml $ admsXml <device.va> -e qucsVersion.xml -e qucsMODULEdefs.xml $ admsXml <device.va> -e analogfunction.xml \end{Verbatim} each creating an appropriate \verb+*.cpp+ and \verb+*.h+ file. \addvspace{12pt} The \textbf{admst} language is used to traverse the internal tree. The tree's root is defined by the Verilog-AMS module definition. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] module device (node1, node2, ...) // module definitions and code endmodule \end{lstlisting} \tutsubsection{Short introduction into the \textbf{admst} language syntax} Usually the \textbf{admst} language instructions are basically formed as \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:instruction argument=...> ... </admst:instruction> \end{lstlisting} or \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:instruction argument=.../> \end{lstlisting} Any other text outside these instruction is output to the console or into an appropriate file. Some of the most important language construct are listed below. \begin{itemize} \item Traversing a list: The construct allows to traverse all children of the selected branch. \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:for-each select="/module"> ... </admst:for-each> \end{lstlisting} \item Defining and using variables: Values from the data tree can be put into named and typed variables which are then accessible using the \$ operator. \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:value-of select="name"> <admst:variable name="module" select="%s"> \end{lstlisting} \item Opening a file: Printed text (see below) is output into the given file. \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:open file="$module.cpp"> ... </admst:open> \end{lstlisting} \item Output text: Special characters must be encoded (e.g. \verb+"+ $\rightarrow$ \verb+&quot;+ \verb+<+ $\rightarrow$ \verb+&lt;+ \verb+>+ $\rightarrow$ \verb+&gt+; and \verb+\n+ $\rightarrow$ \verb+\\n+). \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:text format="This is a text."/> \end{lstlisting} \item Definition of a function: Functions in \textbf{admst} are called templates. \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:template match="name_of_function"> ... </admst:template> \end{lstlisting} \item Running a function: Templates are applied to parts of the internal data tree. \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <admst:apply-templates select="date_tree_root_for_function" match="name_of_function"/> \end{lstlisting} \item Comments: \begin{lstlisting}[ language=XML, xleftmargin=12pt, morekeywords={admst}] <!-- this is a comment --> \end{lstlisting} \end{itemize} \tutsubsection{Analogue simulator script} The analogue simulator implementation consists of several parts. For each type of simulation appropriate functions must be implemented. \begin{itemize} \item DC simulation\\ \verb+module::initDC (void)+,\\ \verb+module::restartDC (void)+ and\\ \verb+module::calcDC (void)+ \item AC simulation\\ \verb+module::initAC (void)+ and\\ \verb+module::calcAC (nr_double_t)+ \item S-parameter simulation\\ \verb+module::initSP (void)+ and\\ \verb+module::calcSP (nr_double_t)+ \item Transient simulation\\ \verb+module::initTR (void)+ and\\ \verb+module::calcTR (nr_double_t)+ \item AC noise simulation\\ \verb+module::initNoiseAC (void)+ and\\ \verb+module::calcNoiseAC (nr_double_t)+ \item S-parameter noise simulation\\ \verb+module::initNoiseSP (void)+ and\\ \verb+module::calcNoiseSP (nr_double_t)+ \item Harmonic simulation\\ \verb+module::initHB (int)+ and\\ \verb+module::calcHB (int)+ \end{itemize} These functions go into the \verb+module.core.cpp+ file. An appropriate \verb+module.core.h+ header file is also created. \addvspace{12pt} In case the Verilog-AMS source file contains analog functions in the module definition, e.g. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] analog function real name; input x; real x; begin name = x * x; end endfunction \end{lstlisting} the \verb+analogfunction.xml+ script produces the appropriate C/C++ and header files \begin{itemize} \item \verb+module.analogfunction.cpp+ \item \verb+module.analogfunction.h+. \end{itemize} The ADMS language transformer is aware of how analogue simlators solve a network of linear and non-linear devices. The general Newton-Raphson algorithm for a DC simulation used in SPICE-like simulators as well as in Qucs can be expressed as \begin{equation} \begin{split} \label{eq:nonlinearNR} J^{(m)}\cdot V^{(m+1)} &= J^{(m)}\cdot V^{(m)} - f\left(V^{(m)}\right)\\ &= I_{lin}^{(m)} + I_{nl}^{(m)} - J_{nl}^{(m)}\cdot V^{(m)} \end{split} \end{equation} whereas $J$ denotes the Jacobian \begin{equation} J^{(m)} = \left.\dfrac{\partial f\left(V\right)}{\partial V}\right|_{V^{(m)}} \end{equation} There are basically two types of contributions supported by ADMS: currents and charges. The appropiate Jacobian matrices are \begin{equation} J^{(m)} = J_I^{(m)} + J_Q^{(m)} = \underbrace{\left.\dfrac{\partial I\left(V\right)}{\partial V}\right|_{V^{(m)}}}_{\textrm{``static''}} + \underbrace{\left.\dfrac{\partial Q\left(V\right)}{\partial V}\right|_{V^{(m)}}}_{\textrm{``dynamic''}} = G + C \end{equation} consisting of two real valued matrices $G$ (conductance/transconductance matrix) and $C$ (capacitance/transcapacitance matrix). \addvspace{12pt} In the Verilog-AMS desciptions only the current and charge contributions are mentioned. The appropriate derivatives are meant to be automatically formed by the language translator ADMS. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] I(ci,ei) <+ it; // current contribution I(si,ci) <+ ddt(Qjs); // charge contribution \end{lstlisting} The right-hand side of eq.~\eqref{eq:nonlinearNR} consists of the linear and non-linear currents of the network as well as the Jacobian matrix multiplied by the voltage vector. Since devices are usually uncorrelated both parts can be computed directly on a per device basis. \tutsubsection{Current limitations of ADMS} The following section contains some simple examples demonstrating which Verilog-AMS statements can be successfully handled by ADMS and which not. \tutsubsubsection{Example 1} There was a bug in the \textbf{admst} scripts. They failed to place the function calls of analogue functions correctly. This has been fixed. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] module diode(a, c); inout a, c; electrical a, c; analog function real current; input is, v; begin current = is * (exp (v / 26e-3) - 1); end endfunction real Vd; real Id; analog begin Vd = V(a, c); Id = current (1e-15, Vd); I(a, c) <+ Id; end endmodule \end{lstlisting} \tutsubsubsection{Example 2} It is not allowed to mix current and charge contributions in assignments. Mixing both emits wrong C/C++ code. It accounts the current to be a charge in this case. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] module diode(a, c); inout a, c; electrical a, c; real Vd, Id, Is, Cp; analog begin Is = 1e-15; Cp = 1e-12; Vd = V(a, c); Id = Is * (exp (Vd / 26e-3) - 1); // not allowed in ADMS I(a, c) <+ Id + ddt(Cp*V(a,c)); // allowed in ADMS I(a, c) <+ Id; I(a, c) <+ ddt(Cp*V(a,c)); end endmodule \end{lstlisting} \tutsubsubsection{Example 3} The following example is rejected by the \textbf{admst} scripts with this error message. \begin{Verbatim}[fontsize=\small] [info] admsXml-2.2.4 Oct 18 2006 19:50:46 [fatal] qucsVersion.xml:1497:admst:if[lhs]: missing node source/insource \end{Verbatim} An immediate potential on the right hand side is not allowed embedded in a function. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] module diode(a, c); inout a, c; electrical a, c; real Id, Is; analog begin Is = 1e-15; Id = Is * (exp (V(a, c) / 26e-3) - 1); // not allowed in ADMS I(a, c) <+ Is * (exp (V(a, c) / 26e-3) - 1); // allowed in ADMS I(a, c) <+ Id; end endmodule \end{lstlisting} \tutsubsubsection{Example 4} Potentials on the left-hand side of contribution assignments are not allowed. This kind of assignment emits wrong C/C++ code. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] module diode(a, c); inout a, c; electrical a, c; real Id, Is; real Rp; analog begin Rp = 1e9; Is = 1e-15; Id = Is * (exp (V(a, c) / 26e-3) - 1); I(a, c) <+ Id; // allowed in ADMS I(a, c) <+ V(a, c) / Rp; // not allowed in ADMS V(a, c) <+ I(a, c) * Rp; end endmodule \end{lstlisting} \tutsubsection{Code for the GUI integration} The \textbf{admst} script for the GUI creates files according to its API. Basically it produces the list of parameters as well their descriptions (if available) in a property list. Additionally the symbol drawing code is emitted which should be adapted to the devices requirements. \begin{figure}[ht] \begin{center} \includegraphics[width=0.9\linewidth]{componentdialog} \end{center} \caption{component property dialog in the GUI} \label{fig:componentdialog} \end{figure} \FloatBarrier In fig.~\ref{fig:componentdialog} the component property dialog of an implemented device is shown. In the schematic in fig.~\ref{fig:hicumschematic} the symbol for the HICUM model is surrounded with a red circle. The GUI code is also responsible for the icons in the listview on the left hand side of the figure. \begin{figure}[ht] \begin{center} \includegraphics[width=1\linewidth]{hicumschematic} \end{center} \caption{schematic with the HICUM transistor symbol} \label{fig:hicumschematic} \end{figure} \FloatBarrier \tutsection{Adding Verilog-AMS devices to Qucs} The section gives an overview how to add a Verilog-AMS model to Qucs in a step-by-step manner. Be aware that the description is meant for advanced users partly familiar with the usual GNU/Linux build system and C/C++ programming. \tutsubsection{The Verilog-AMS source file} The starting point of a new Verilog-AMS model in Qucs is the Verilog-AMS source file which must be aware of the discussed ADMS limitations. The example we are going to discuss is a simple diode model shown in the following listing contained in the \textbf{diode.va} file. \begin{lstlisting}[ language=Verilog, xleftmargin=12pt] `include "disciplines.vams" `include "constants.vams" // ADMS specific definitions `define attr(txt) (*txt*) module diode(a, c); // device terminals inout a, c; electrical a, c; // internal node electrical ci; // model parameters parameter real Is = 1E-15 from [0:1] `attr(info="saturation current"); parameter real Cp = 1E-12 from [0:1] `attr(info="parallel capacitance"); parameter real Rs = 1.0 from (0:inf) `attr(info="series resistance"); parameter real Temp = 300 from (0:inf) `attr(info="temperature"); real Vd, Id, fourkt, twoq, Qp; analog begin Vd = V(a, ci); Id = Is * (exp (Vd / 26e-3) - 1); Qp = Cp * Vd; I(a, ci) <+ Id; I(a, ci) <+ ddt(Qp); I(ci, c) <+ V(ci, c) / Rs; begin : noise fourkt = 4.0 * `P_K * Temp; twoq = 2.0 * `P_Q; I(ci, c) <+ white_noise(fourkt/Rs, "thermal"); I(a, ci) <+ white_noise(twoq*Id, "shot"); end // noise end // analog endmodule \end{lstlisting} \tutsubsection{Integrating the model into the analogue simulator} The qucs-core tree of Qucs must be configured using the --enable-maintainer-mode option. \begin{Verbatim}[fontsize=\small] $ ./configure --enable-maintainer-mode --prefix=/tmp \end{Verbatim} The source trees of qucs (GUI) as well as qucs-core (simulator) are within the release tarballs available at \url{http://qucs.sourceforge.net/download.html}. During development of new Verilog-A models it is recommended to use CVS. Latest CVS trees of qucs and qucs-core can be obtained using the following command lines. \begin{Verbatim}[fontsize=\small] $ cvs -z3 -d:pserver:anonymous@qucs.cvs.sourceforge.net:/cvsroot/qucs \ co qucs-core $ cvs -z3 -d:pserver:anonymous@qucs.cvs.sourceforge.net:/cvsroot/qucs \ co qucs \end{Verbatim} Also the software \textbf{adms} must be installed. It is available at \url{http://sourceforge.net/projects/mot-adms}. \addvspace{12pt} The file \textbf{diode.va} must be copied into the source tree. \begin{Verbatim}[fontsize=\small] $ cp diode.va qucs-core/src/components/verilog/ \end{Verbatim} In this directory (qucs-core/src/components/verilog/) the Verilog model can be checked if it can be translated successfully using the following command lines. \begin{Verbatim}[fontsize=\small] $ admsXml diode.va -e qucsVersion.xml -e qucsMODULEcore.xml [info] admsXml-2.2.4 Oct 18 2006 19:50:46 [info] diode.core.cpp and diode.core.h: files created [info] elapsed time: 0.0339946 [info] admst iterations: 4146 (4146 freed) $ admsXml diode.va -e analogfunction.xml [info] admsXml-2.2.4 Oct 18 2006 19:50:46 [info] diode.analogfunction.h created [info] diode.analogfunction.cpp created [info] elapsed time: 0.0262961 [info] admst iterations: 3919 (3919 freed) \end{Verbatim} These command lines create the files for the model evaluation code. The file names (diode.*) are due to the name of the module contained in the Verilog-AMS source file. \addvspace{12pt} Additionally the source code must be changed in some more locations. \begin{itemize} \item \Verb+src/components/component.h+\\ In this file it is necessary to add the line \begin{Verbatim}[fontsize=\small] #include "verilog/diode.core.h" \end{Verbatim} \item \Verb+src/components/component_id.h+\\ The file contains unique component identifiers. It is necessary to add the Verilog modules name. \begin{Verbatim}[fontsize=\small] enum circuit_type { CIR_UNKNOWN = -1, ... // verilog devices CIR_diode, ... }; \end{Verbatim} \item \Verb+src/input.cpp+\\ In order to be able to instantiate the new model the file must be modified as follows. \begin{Verbatim}[fontsize=\small] // The function creates components specified by the type of component. circuit * input::createCircuit (char * type) { if (!strcmp (type, "Pac")) return new pac (); ... else if (!strcmp (type, "diode")) return new diode (); logprint (LOG_ERROR, "no such circuit type `%s'\n", type); return NULL; } \end{Verbatim} \item \Verb+src/qucsdefs.h+\\ Finally the properties including their range definitions must be added to this file. The appropiate file can be obtained using the following command line. \begin{Verbatim}[fontsize=\small] $ admsXml diode.va -e qucsVersion.xml -e qucsMODULEdefs.xml [info] admsXml-2.2.4 Oct 18 2006 19:50:46 [info] diode.defs.h: file created [info] elapsed time: 0.0335337 [info] admst iterations: 4294 (4294 freed) \end{Verbatim} The emitted file \textbf{diode.defs.h} looks like \begin{Verbatim}[fontsize=\small] /* diode verilog device */ { "diode", 2, PROP_COMPONENT, PROP_NO_SUBSTRATE, PROP_NONLINEAR, { { "Is", PROP_REAL, { 1E-15, PROP_NO_STR }, { '[', 0, 1, ']' } }, { "Cp", PROP_REAL, { 1E-12, PROP_NO_STR }, { '[', 0, 1, ']' } }, { "Rs", PROP_REAL, { 1.0, PROP_NO_STR }, { ']', 0, 0, '.' } }, { "Temp", PROP_REAL, { 300, PROP_NO_STR }, { ']', 0, 0, '.' } }, PROP_NO_PROP }, { PROP_NO_PROP } }, \end{Verbatim} representing the parameters defined in the original Verilog-AMS file. This excerpt must be included in the \textbf{src/qucsdefs.h} file into this structure: \begin{Verbatim}[fontsize=\small] // List of available components. struct define_t qucs_definition_available[] = { ... /* end of list */ { NULL, 0, 0, 0, 0, { PROP_NO_PROP }, { PROP_NO_PROP } } }; \end{Verbatim} \end{itemize} Finally the \textbf{Makefile.am} in the \textbf{src/components/verilog/} directory must be adjusted to make the build-system aware of the new component. There must be added \begin{Verbatim}[fontsize=\small] libverilog_a_SOURCES = ... \ diode.analogfuncction.cpp diode.core.cpp noinst_HEADERS = ... \ diode.analogfuncction.h diode.core.h VERILOG_FILES = ... diode.va if MAINTAINER_MODE ... diode.analogfunction.cpp: analogfunction.xml diode.analogfunction.cpp: diode.va $(ADMSXML) $< -e analogfunction.xml diode.core.cpp: qucsVersion.xml qucsMODULEcore.xml diode.core.cpp: diode.va $(ADMSXML) $< -e qucsVersion.xml -e qucsMODULEcore.xml diode.defs.h: qucsVersion.xml qucsMODULEdefs.xml diode.defs.h: diode.va $(ADMSXML) $< -e qucsVersion.xml -e qucsMODULEdefs.xml diode.gui.cpp: qucsVersion.xml qucsMODULEgui.xml diode.gui.cpp: diode.va $(ADMSXML) $< -e qucsVersion.xml -e qucsMODULEgui.xml ... else \end{Verbatim} in order to create the correct build rules. \addvspace{12pt} If everything worked fine then the new Verilog-AMS model is now completely integrated into the analogue simulator. \tutsubsection{Integrating the model into the GUI} Very likely as the qucs-core tree in the previous section also the qucs source tree must be configured using the --enable-maintainer-mode option. \begin{Verbatim}[fontsize=\small] $ ./configure --enable-maintainer-mode --prefix=/tmp \end{Verbatim} Still in the \textbf{qucs-core/src/components/verilog} directory it is now necessary to create the C++ code for the GUI using the following command line. \begin{Verbatim}[fontsize=\small] $ admsXml diode.va -e qucsVersion.xml -e qucsMODULEgui.xml [info] admsXml-2.2.4 Oct 18 2006 19:50:46 [info] diode.gui.cpp and diode.gui.h: files created [info] elapsed time: 0.0345217 [info] admst iterations: 4146 (4146 freed) \end{Verbatim} Both the created files \textbf{diode.gui.cpp} and \textbf{diode.gui.h} should be copied to the \textbf{qucs/qucs/components} directory. \addvspace{12pt} Depending on the type of device several changes must be applied to these files. The constructor will basically contain the properties of the device as they are going to occur in the component property dialog as depicted in fig.~\ref{fig:componentdialog}. Check these if they are complete or if some can be left. \begin{lstlisting}[ language=C++, basicstyle=\small, xleftmargin=12pt] diode::diode() { Description = QObject::tr ("diode verilog device"); Props.append (new Property ("Is", "1E-15", false, QObject::tr ("saturation current"))); Props.append (new Property ("Cp", "1E-12", false, QObject::tr ("parallel capacitance"))); Props.append (new Property ("Rs", "1.0", false, QObject::tr ("series resistance"))); Props.append (new Property ("Temp", "300", false, QObject::tr ("temperature"))); ... } \end{lstlisting} The \textbf{diode::info} function should be adapted to meet the devices requirements. The \textbf{BitmapFile} should be changed to represent a correct PNG file in the \textbf{qucs/bitmaps} directory. Both the \textbf{Name} and the bitmap are going to appear in the left-hand component tab as shown in fig.~\ref{fig:hicumschematic}. \begin{lstlisting}[ language=C++, basicstyle=\small, xleftmargin=12pt] Element * diode::info(QString& Name, char * &BitmapFile, bool getNewOne) { Name = QObject::tr("Diode"); BitmapFile = "diode"; if(getNewOne) return new diode(); return 0; } \end{lstlisting} The \textbf{diode::info\_pnp()} method can be completely deleted. It can be necessary for bipolar transistors where two types of devices could be displayed (npn and pnp type). The method must also be deleted from the header file. Also, in this case, the new diode class inherits \textbf{Component} instead of \textbf{MultiViewComponent}. \addvspace{12pt} The \textbf{diode::createSymbol()} method must be adapted to represent a valid schematic symbol. Anyway, the default code can be used as a template. \begin{lstlisting}[ language=C++, basicstyle=\small, xleftmargin=12pt] void diode::createSymbol() { // normal bipolar Lines.append(new Line(-10,-15,-10, 15,QPen(QPen::darkBlue,3))); Lines.append(new Line(-30, 0,-10, 0,QPen(QPen::darkBlue,2))); Lines.append(new Line(-10, -5, 0,-15,QPen(QPen::darkBlue,2))); Lines.append(new Line( 0,-15, 0,-30,QPen(QPen::darkBlue,2))); Lines.append(new Line(-10, 5, 0, 15,QPen(QPen::darkBlue,2))); Lines.append(new Line( 0, 15, 0, 30,QPen(QPen::darkBlue,2))); // substrate node Lines.append(new Line( 9, 0, 30, 0,QPen(QPen::darkBlue,2))); Lines.append(new Line( 9, -7, 9, 7,QPen(QPen::darkBlue,3))); // thermal node Lines.append(new Line(-30, 20,-20, 20,QPen(QPen::darkBlue,2))); Lines.append(new Line(-20, 17,-20, 23,QPen(QPen::darkBlue,2))); // arrow if(Props.getFirst()->Value == "npn") { Lines.append(new Line( -6, 15, 0, 15,QPen(QPen::darkBlue,2))); Lines.append(new Line( 0, 9, 0, 15,QPen(QPen::darkBlue,2))); } else { Lines.append(new Line( -5, 10, -5, 16,QPen(QPen::darkBlue,2))); Lines.append(new Line( -5, 10, 1, 10,QPen(QPen::darkBlue,2))); } // terminal definitions Ports.append(new Port( 0,-30)); // collector Ports.append(new Port(-30, 0)); // base Ports.append(new Port( 0, 30)); // emitter Ports.append(new Port( 30, 0)); // substrate Ports.append(new Port(-30, 20)); // thermal node // relative boundings x1 = -30; y1 = -30; x2 = 30; y2 = 30; } \end{lstlisting} In order to test the component in the GUI it is necessary to modify some more source code files. \begin{itemize} \item \Verb+qucs/qucs.cpp+\\ In this file the new Verilog device will be made available to the component tab. If a new non-linear device is added then place it here: \begin{Verbatim}[fontsize=\small] pInfoFunc nonlinearComps[] = { ... &diode::info, 0}; \end{Verbatim} \item \Verb+qucs/components/component.cpp+\\ The new verilog device must be loadable in the GUI. So in the function \textbf{getComponentFromName()} add this: \begin{Verbatim}[fontsize=\small] Component* getComponentFromName(QString& Line) { ... case 'd' : if(cstr == "iode") c = new diode(); break; ... return c; } \end{Verbatim} \item \Verb+qucs/components/components.h+\\ In the component header file it is necessary to add: \begin{Verbatim}[fontsize=\small] #include "diode.h" \end{Verbatim} \end{itemize} In order to make the build-sytem aware of the new Verilog model the file \textbf{qucs/components/Makefile.am} must be modified in the following way. \begin{Verbatim}[fontsize=\small] libcomponents_a_SOURCES = ... \ diode.gui.cpp noinst_HEADERS = ... \ diode.gui.h \end{Verbatim} With these steps the component is now fully integrated into the GUI. \tutsection{Implemented devices} The following sections presents the models already added in Qucs including some test schematics and simulation results. \tutsubsection{HICUM/L2 v2.11 model} The name HICUM was derived from HIgh-CUrrent Model, indicating that HICUM initially was developed with special emphasis on modelling the operating region at high current densities which is very important for certain high-speed applications. \addvspace{12pt} The Verilog-AMS source code can be obtained from \url{http://www.iee.et.tu-dresden.de/iee/eb/hic_new/hic_source.html}. The model used in Qucs was a bit modified due to some ADMS limitations. \addvspace{12pt} Some schematics have been setup to verify that the model emits basically the correct output values and the source code translations worked properly. \tutsubsubsection{DC simulation} The setup for the forward Gummel plot is depicted in fig.~\ref{fig:fgummel}. The base-emitter voltage is swept ($V_{BE} = 0.2\dots 1.2$) with a constant voltage across the second diode $V_{BC} = 0$. \begin{figure}[ht] \begin{center} \includegraphics[width=0.7\linewidth]{fgummel} \end{center} \caption{forward Gummel plot schematic for HICUM/L2 v2.11 model} \label{fig:fgummel} \end{figure} \FloatBarrier In fig.~\ref{fig:fgummel_dpl} the logarithmic Gummel plot is shown including the ratio between the base current and collector current on the secondary axis. \begin{figure}[ht] \begin{center} \includegraphics[width=0.8\linewidth]{fgummel_dpl} \end{center} \caption{forward Gummel plot for HICUM/L2 v2.11 model} \label{fig:fgummel_dpl} \end{figure} \FloatBarrier \tutsubsubsection{DC simulation} In fig.~\ref{fig:charac_sch} the schematic for the output characteristics of the HICUM model is shown. The 2-dimensional sweep describes the function \begin{equation} I_C = f\left(V_{CE}, V_{BE}\right) \end{equation} \begin{figure}[ht] \begin{center} \includegraphics[width=0.7\linewidth]{charac_sch} \end{center} \caption{output characteristics schematic for HICUM/L2 v2.11 model} \label{fig:charac_sch} \end{figure} \FloatBarrier Figure~\ref{fig:charac_dpl} shows the results of the DC simulations for the output characteristics of the bipolar transistor. \begin{figure}[ht] \begin{center} \includegraphics[width=0.6\linewidth]{charac_dpl} \end{center} \caption{output characteristics plot for HICUM/L2 v2.11 model} \label{fig:charac_dpl} \end{figure} \FloatBarrier \tutsubsubsection{AC simulation} Figures~\ref{fig:acgain_sch} and \ref{fig:acgain_dpl} depict the schematic and diagrams for an AC simulation in a given bias point. The current gains magnitude and phase are shown as well as the characteristics of the small signal base and collector current in the complex plane (polar plot). \begin{figure}[ht] \begin{center} \includegraphics[width=0.7\linewidth]{acgain_sch} \end{center} \caption{AC simulation schematic for HICUM/L2 v2.11 model} \label{fig:acgain_sch} \end{figure} \FloatBarrier \begin{figure}[ht] \begin{center} \includegraphics[width=1\linewidth]{acgain_dpl} \end{center} \caption{AC simulation plot for HICUM/L2 v2.11 model} \label{fig:acgain_dpl} \end{figure} \FloatBarrier \tutsubsubsection{S-parameter simulation} In the figures~\ref{fig:sparam_sch} and \ref{fig:sparam_dpl} a two-port S-parameter simulation schematic (including noise) as well as the results are shown. The four S-parameters are displayed in two Polar-Smith combi diagrams. The noise figure as well as the minimal noise figure are displayed in a logarithmic Cartesian diagram. \begin{figure}[ht] \begin{center} \includegraphics[width=0.7\linewidth]{sparam_sch} \end{center} \caption{S-parameter simulation schematic for HICUM/L2 v2.11 model} \label{fig:sparam_sch} \end{figure} \FloatBarrier \begin{figure}[ht] \begin{center} \includegraphics[width=0.8\linewidth]{sparam_dpl} \end{center} \caption{S-parameter simulation plot for HICUM/L2 v2.11 model} \label{fig:sparam_dpl} \end{figure} \FloatBarrier \tutsubsubsection{Transient simulation} In the schematic in fig.~\ref{fig:transient_sch} a current pulse is fed into the base of the transistor. Varying the input capacitance changes the response in the collector current as shown in fig.~\ref{fig:transient_dpl}. \begin{figure}[ht] \begin{center} \includegraphics[width=0.6\linewidth]{transient_sch} \end{center} \caption{Transient simulation schematic for HICUM/L2 v2.11 model} \label{fig:transient_sch} \end{figure} \FloatBarrier \begin{figure}[ht] \begin{center} \includegraphics[width=0.8\linewidth]{transient_dpl} \end{center} \caption{Transient simulation plot for HICUM/L2 v2.11 model} \label{fig:transient_dpl} \end{figure} \FloatBarrier \tutsubsection{FBH-HBT model version 2.1} The HBT (Hetero Bipolar Transistor) model developed by Matthias Rudolph at the FBH (Ferdinand-Braun-Institut f\"ur Hochfrequenztechnik) is available in the Internet at \url{http://www.designers-guide.org/VerilogAMS}. \tutsubsubsection{DC simulation} Forward Gummel plot. \begin{figure}[ht] \begin{center} \includegraphics[width=0.9\linewidth]{fbh_fgummel} \end{center} \caption{forward Gummel plot schematic for HBT model} \label{fig:fbh_fgummel} \end{figure} \FloatBarrier \tutsubsubsection{DC simulation} Output characteristics. \begin{figure}[ht] \begin{center} \includegraphics[width=0.7\linewidth]{fbh_charac} \end{center} \caption{output characteristics schematic for HBT model} \label{fig:fbh_charac} \end{figure} \FloatBarrier \tutsection{End Note} The preferred way to add a new Verilog model to Qucs is certainly to prepare a model, check if it is accepted by ADMS and finally ask the maintainers to integrate it. Until there is no possibility to load device modules dynamically (which is on the TODO list) too many hand-made changes have to be done to automate this process. The dynamic modules require changes in the simulator API as well in the GUI code. \addvspace{12pt} Furthermore work is going to be continued on ADMS itself as well as on the \textbf{admst} scripts. \addvspace{12pt} The authors would like to thank H\'el\`ene Parruitte for the initial implementation of the Verilog-AMS interface in Qucs. Also thanks go to the company Xmod Technologies (see \url{http://www.xmodtech.com}) allowing her to work on such an interface and finally to share the outcome of her internship under the GPL.
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXBLAS_LEVEL1EXTENSIONS_TRAXPBY_H #define CXXBLAS_LEVEL1EXTENSIONS_TRAXPBY_H 1 #include "xflens/cxxblas/typedefs.h" #define HAVE_CXXBLAS_TRAXPBY 1 namespace cxxblas { // // B = beta*B + alpha*op(A) // // where B is a mxn triangular matrix as specified by upLo // template <typename IndexType, typename ALPHA, typename MA, typename BETA, typename MB> void traxpby(StorageOrder order, StorageUpLo upLo, Transpose trans, Diag diag, IndexType m, IndexType n, const ALPHA &alpha, const MA *A, IndexType ldA, const BETA &beta, MB *B, IndexType ldB); } // namespace cxxblas #endif // CXXBLAS_LEVEL1EXTENSIONS_TRAXPBY_H
{ "pile_set_name": "Github" }
var Bugsnag = require('@bugsnag/browser') var config = require('./lib/config') Bugsnag.start(config) Bugsnag.notify(new Error('bad things'))
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: e29eca76bc2538f46a6da73086448575 timeCreated: 1480605840 licenseType: Pro NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
File: itselfAsUpperBoundLocal.kt - 20656365ce03324f9459f6d9a96f1a89 NL("\n") packageHeader importList topLevelObject declaration functionDeclaration FUN("fun") simpleIdentifier Identifier("bar") functionValueParameters LPAREN("(") RPAREN(")") functionBody block LCURL("{") NL("\n") statements statement declaration functionDeclaration FUN("fun") typeParameters LANGLE("<") typeParameter simpleIdentifier Identifier("T") COLON(":") type nullableType typeReference userType simpleUserType simpleIdentifier Identifier("T") quest QUEST_NO_WS("?") RANGLE(">") simpleIdentifier Identifier("foo") functionValueParameters LPAREN("(") RPAREN(")") functionBody block LCURL("{") statements RCURL("}") semis NL("\n") statement expression disjunction conjunction equality comparison genericCallLikeComparison infixOperation elvisExpression infixFunctionCall rangeExpression additiveExpression multiplicativeExpression asExpression prefixUnaryExpression postfixUnaryExpression primaryExpression simpleIdentifier Identifier("foo") callSuffix valueArguments LPAREN("(") RPAREN(")") semis NL("\n") RCURL("}") semis NL("\n") EOF("<EOF>")
{ "pile_set_name": "Github" }
from ED6ScenarioHelper import * def main(): # 蔡斯 CreateScenaFile( FileName = 'T3233 ._SN', MapName = 'Zeiss', Location = 'T3233.x', MapIndex = 1, MapDefaultBGM = "ed60084", Flags = 0, EntryFunctionIndex = 0xFFFF, Reserved = 0, IncludedScenario = [ '', '', '', '', '', '', '', '' ], ) BuildStringList( '@FileName', # 8 '拜舍尔', # 9 '艾德', # 10 '林', # 11 '莉西亚', # 12 '希利尔', # 13 '艾缇', # 14 '拉克', # 15 '希玛', # 16 '库安', # 17 '西加罗', # 18 '艾德尔', # 19 '艾丝蒂尔的篮子', # 20 '提妲的篮子', # 21 ) DeclEntryPoint( Unknown_00 = 0, Unknown_04 = 0, Unknown_08 = 6000, Unknown_0C = 4, Unknown_0E = 0, Unknown_10 = 0, Unknown_14 = 9500, Unknown_18 = -10000, Unknown_1C = 0, Unknown_20 = 0, Unknown_24 = 0, Unknown_28 = 2800, Unknown_2C = 262, Unknown_30 = 45, Unknown_32 = 0, Unknown_34 = 360, Unknown_36 = 0, Unknown_38 = 0, Unknown_3A = 0, InitScenaIndex = 0, InitFunctionIndex = 0, EntryScenaIndex = 0, EntryFunctionIndex = 1, ) AddCharChip( 'ED6_DT07/CH02300 ._CH', # 00 'ED6_DT07/CH02310 ._CH', # 01 'ED6_DT07/CH02290 ._CH', # 02 'ED6_DT07/CH01040 ._CH', # 03 'ED6_DT07/CH01270 ._CH', # 04 'ED6_DT07/CH01030 ._CH', # 05 'ED6_DT07/CH01150 ._CH', # 06 'ED6_DT07/CH01120 ._CH', # 07 'ED6_DT07/CH01130 ._CH', # 08 'ED6_DT07/CH01160 ._CH', # 09 'ED6_DT07/CH01020 ._CH', # 0A 'ED6_DT07/CH01060 ._CH', # 0B 'ED6_DT07/CH01040 ._CH', # 0C 'ED6_DT07/CH01210 ._CH', # 0D 'ED6_DT06/CH20021 ._CH', # 0E 'ED6_DT06/CH20145 ._CH', # 0F 'ED6_DT06/CH20146 ._CH', # 10 ) AddCharChipPat( 'ED6_DT07/CH02300P._CP', # 00 'ED6_DT07/CH02310P._CP', # 01 'ED6_DT07/CH02290P._CP', # 02 'ED6_DT07/CH01040P._CP', # 03 'ED6_DT07/CH01270P._CP', # 04 'ED6_DT07/CH01030P._CP', # 05 'ED6_DT07/CH01150P._CP', # 06 'ED6_DT07/CH01120P._CP', # 07 'ED6_DT07/CH01130P._CP', # 08 'ED6_DT07/CH01160P._CP', # 09 'ED6_DT07/CH01020P._CP', # 0A 'ED6_DT07/CH01060P._CP', # 0B 'ED6_DT07/CH01040P._CP', # 0C 'ED6_DT07/CH01210P._CP', # 0D 'ED6_DT06/CH20021P._CP', # 0E 'ED6_DT06/CH20145P._CP', # 0F 'ED6_DT06/CH20146P._CP', # 10 ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 3, ChipIndex = 0x3, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 5, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 4, ChipIndex = 0x4, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 6, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 5, ChipIndex = 0x5, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 7, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 6, ChipIndex = 0x6, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 8, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 7, ChipIndex = 0x7, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 9, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 8, ChipIndex = 0x8, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 10, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 9, ChipIndex = 0x9, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 11, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 10, ChipIndex = 0xA, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 12, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 11, ChipIndex = 0xB, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 13, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 12, ChipIndex = 0xC, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 4, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 13, ChipIndex = 0xD, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 3, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 0, Unknown2 = 0, Unknown3 = 1245198, ChipIndex = 0xE, NpcIndex = 0x1E6, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 0, Unknown2 = 0, Unknown3 = 1310734, ChipIndex = 0xE, NpcIndex = 0x1E6, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclActor( TriggerX = -1900, TriggerZ = 0, TriggerY = 5070, TriggerRange = 800, ActorX = -1900, ActorZ = 1000, ActorY = 5070, Flags = 0x7C, TalkScenaIndex = 0, TalkFunctionIndex = 14, Unknown_22 = 0, ) DeclActor( TriggerX = -1890, TriggerZ = 0, TriggerY = -4990, TriggerRange = 800, ActorX = -1890, ActorZ = 1000, ActorY = -4990, Flags = 0x7C, TalkScenaIndex = 0, TalkFunctionIndex = 14, Unknown_22 = 0, ) ScpFunction( "Function_0_31A", # 00, 0 "Function_1_3B4", # 01, 1 "Function_2_3BF", # 02, 2 "Function_3_3D5", # 03, 3 "Function_4_433", # 04, 4 "Function_5_577", # 05, 5 "Function_6_793", # 06, 6 "Function_7_79A", # 07, 7 "Function_8_7A1", # 08, 8 "Function_9_7A8", # 09, 9 "Function_10_7AF", # 0A, 10 "Function_11_7B6", # 0B, 11 "Function_12_7BD", # 0C, 12 "Function_13_7C4", # 0D, 13 "Function_14_7CB", # 0E, 14 "Function_15_1F27", # 0F, 15 "Function_16_1FC7", # 10, 16 ) def Function_0_31A(): pass label("Function_0_31A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_324") Jump("loc_3B3") label("loc_324") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_32E") Jump("loc_3B3") label("loc_32E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_34E") ClearChrFlags(0x11, 0x80) SetChrPos(0x11, -1080, 0, 440, 85) Jump("loc_3B3") label("loc_34E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_36E") ClearChrFlags(0x8, 0x80) SetChrPos(0x8, -1090, 0, -900, 82) Jump("loc_3B3") label("loc_36E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 6)), scpexpr(EXPR_END)), "loc_378") Jump("loc_3B3") label("loc_378") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 2)), scpexpr(EXPR_END)), "loc_382") Jump("loc_3B3") label("loc_382") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 7)), scpexpr(EXPR_END)), "loc_38C") Jump("loc_3B3") label("loc_38C") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_396") Jump("loc_3B3") label("loc_396") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_3B3") ClearChrFlags(0x8, 0x80) SetChrPos(0x8, -1090, 0, -900, 82) label("loc_3B3") Return() # Function_0_31A end def Function_1_3B4(): pass label("Function_1_3B4") OP_72(0x8, 0x10) OP_72(0x9, 0x10) Return() # Function_1_3B4 end def Function_2_3BF(): pass label("Function_2_3BF") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_3D4") OP_99(0xFE, 0x0, 0x7, 0x5DC) Jump("Function_2_3BF") label("loc_3D4") Return() # Function_2_3BF end def Function_3_3D5(): pass label("Function_3_3D5") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_3E2") Jump("loc_42F") label("loc_3E2") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_3EC") Jump("loc_42F") label("loc_3EC") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_3F6") Jump("loc_42F") label("loc_3F6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_400") Jump("loc_42F") label("loc_400") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 6)), scpexpr(EXPR_END)), "loc_40A") Jump("loc_42F") label("loc_40A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 2)), scpexpr(EXPR_END)), "loc_414") Jump("loc_42F") label("loc_414") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 7)), scpexpr(EXPR_END)), "loc_41E") Jump("loc_42F") label("loc_41E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_428") Jump("loc_42F") label("loc_428") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_42F") label("loc_42F") TalkEnd(0xFE) Return() # Function_3_3D5 end def Function_4_433(): pass label("Function_4_433") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_440") Jump("loc_573") label("loc_440") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_44A") Jump("loc_573") label("loc_44A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_4C6") ChrTalk( 0xFE, ( "蔡斯那边\x01", "好像发生了什么大事件呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "呼,\x01", "早早地赶到这里真是明智啊。\x02", ) ) CloseMessageWindow() Jump("loc_573") label("loc_4C6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_4D0") Jump("loc_573") label("loc_4D0") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 6)), scpexpr(EXPR_END)), "loc_54E") ChrTalk( 0xFE, ( "嗯,真是好温泉。\x01", "身体从内到外都感觉很暖和。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "泡温泉的时候\x01", "可以把讨厌的事全都给忘掉呢。\x02", ) ) CloseMessageWindow() Jump("loc_573") label("loc_54E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 2)), scpexpr(EXPR_END)), "loc_558") Jump("loc_573") label("loc_558") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 7)), scpexpr(EXPR_END)), "loc_562") Jump("loc_573") label("loc_562") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_56C") Jump("loc_573") label("loc_56C") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_573") label("loc_573") TalkEnd(0xFE) Return() # Function_4_433 end def Function_5_577(): pass label("Function_5_577") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_584") Jump("loc_78F") label("loc_584") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_58E") Jump("loc_78F") label("loc_58E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 7)), scpexpr(EXPR_END)), "loc_598") Jump("loc_78F") label("loc_598") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_6BF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_608") ChrTalk( 0xFE, "原来如此,池钓吗……\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "回到钓公师团的总部之后\x01", "就立刻去找钓鱼场吧。\x02", ) ) CloseMessageWindow() Jump("loc_6BC") label("loc_608") OP_A2(0x1) ChrTalk( 0xFE, ( "呵呵,一大早就不由自主\x01", "想来露天温泉泡个澡。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这里的浴池果然很大。\x01", "有点像个池塘啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "啊,池塘吗……\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "对了,\x01", "下次试试池钓吧。\x02", ) ) CloseMessageWindow() label("loc_6BC") Jump("loc_78F") label("loc_6BF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 6)), scpexpr(EXPR_END)), "loc_6C9") Jump("loc_78F") label("loc_6C9") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 2)), scpexpr(EXPR_END)), "loc_6D3") Jump("loc_78F") label("loc_6D3") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 7)), scpexpr(EXPR_END)), "loc_6DD") Jump("loc_78F") label("loc_6DD") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_6E7") Jump("loc_78F") label("loc_6E7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_78F") ChrTalk( 0xFE, ( "从大白天开始\x01", "就一直泡澡,\x01", "这可是温泉的绝妙之处啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "哎呀,从温泉出来的时候\x01", "迎面吹来的风真是清爽啊。\x02", ) ) CloseMessageWindow() label("loc_78F") TalkEnd(0xFE) Return() # Function_5_577 end def Function_6_793(): pass label("Function_6_793") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_6_793 end def Function_7_79A(): pass label("Function_7_79A") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_7_79A end def Function_8_7A1(): pass label("Function_8_7A1") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_8_7A1 end def Function_9_7A8(): pass label("Function_9_7A8") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_9_7A8 end def Function_10_7AF(): pass label("Function_10_7AF") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_10_7AF end def Function_11_7B6(): pass label("Function_11_7B6") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_11_7B6 end def Function_12_7BD(): pass label("Function_12_7BD") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_12_7BD end def Function_13_7C4(): pass label("Function_13_7C4") TalkBegin(0xFE) TalkEnd(0xFE) Return() # Function_13_7C4 end def Function_14_7CB(): pass label("Function_14_7CB") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA4, 7)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1F26") EventBegin(0x0) OP_A2(0x528) Jc((scpexpr(EXPR_GET_CHR_WORK, 0x0, 0x3), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_GTR), scpexpr(EXPR_END)), "loc_8B3") Fade(1000) OP_6D(-1360, 0, 5070, 0) SetChrPos(0x101, -150, 0, 4200, 270) SetChrPos(0x102, -800, 0, 3380, 0) SetChrPos(0x107, -580, 0, 5360, 270) OP_0D() ChrTalk( 0x101, ( "#000F嗯……\x01", "这里就是澡堂的入口吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#060F嗯,这里是女浴室,\x01", "那边的是男浴室。\x02", ) ) CloseMessageWindow() Jump("loc_99F") label("loc_8B3") Fade(1000) OP_6D(-1360, 0, -4840, 0) SetChrPos(0x101, -150, 0, -5600, 270) SetChrPos(0x102, -800, 0, -6530, 0) SetChrPos(0x107, -580, 0, -4450, 270) OP_0D() ChrTalk( 0x101, ( "#000F嗯……\x01", "这里就是澡堂的入口吧。\x02", ) ) CloseMessageWindow() OP_62(0x107, 0x0, 1700, 0x28, 0x2B, 0x64, 0x3) ChrTalk( 0x107, ( "#065F艾、艾丝蒂尔姐姐。\x01", "这边是男浴室。\x02\x03", "前面那个才是女浴室呢。\x02", ) ) CloseMessageWindow() label("loc_99F") ChrTalk( 0x101, ( "#004F啊,原来是这样啊。\x01", "男女分开的啊。\x02\x03", "#001F哈哈,不过那也是当然的。\x01", "因为要换衣服嘛。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#015F咳咳……\x02\x03", "#010F那样的话,\x01", "我们要暂时分开一会儿了。\x02", ) ) CloseMessageWindow() TurnDirection(0x107, 0x102, 400) TurnDirection(0x101, 0x102, 400) ChrTalk( 0x101, "#001F嗯,待会见⊙\x02", ) CloseMessageWindow() ChrTalk( 0x107, "#560F失陪了~\x02", ) CloseMessageWindow() FadeToDark(1000, 0, -1) OP_0D() Sleep(1000) OP_6D(-32439, 0, 28640, 0) ClearChrFlags(0x13, 0x80) ClearChrFlags(0x14, 0x80) SetChrPos(0x13, -31500, 1300, 29300, 0) SetChrPos(0x14, -30300, 1300, 29300, 0) FadeToBright(1500, 0) OP_0D() Sleep(1500) Fade(1000) OP_6D(-63400, -750, 28960, 0) SetChrPos(0x107, -65290, -550, 25260, 90) SetChrPos(0x101, -64140, -550, 26490, 180) SetChrFlags(0x101, 0x20) SetChrFlags(0x101, 0x20) SetChrFlags(0x101, 0x2) SetChrFlags(0x107, 0x2) SetChrFlags(0x101, 0x4) SetChrFlags(0x107, 0x4) SetChrChipByIndex(0x101, 15) SetChrChipByIndex(0x107, 16) SetChrSubChip(0x101, 0) SetChrSubChip(0x107, 0) OP_22(0xA2, 0x0, 0x64) OP_22(0x1C7, 0x1, 0x64) OP_6D(-65690, -750, 27830, 3000) Sleep(400) OP_99(0x101, 0x0, 0x2, 0x320) OP_99(0x101, 0x2, 0x1, 0x320) Sleep(400) ChrTalk( 0x101, ( "#378F#2P呼~真是享受啊,享受。\x02\x03", "这还是我第一次泡温泉呢,\x01", "真是出乎意料的舒服。\x02\x03", "#443F虽然没到朵洛希那样痴迷的程度,\x01", "但还真是挺容易上瘾的哦。\x02", ) ) CloseMessageWindow() SetChrSubChip(0x107, 7) Sleep(400) ChrTalk( 0x107, ( "#391F#5P呵呵……\x01", "其实我的瘾也挺大的哦。\x02\x03", "从我还小的时候开始,\x01", "爷爷就经常带我来这里泡温泉呢。\x02", ) ) CloseMessageWindow() SetChrSubChip(0x101, 3) Sleep(400) ChrTalk( 0x101, "#370F#2P是这样啊……\x02", ) CloseMessageWindow() OP_62(0x101, 0xC8, 1600, 0x26, 0x26, 0xFA, 0x1) Sleep(1000) OP_99(0x101, 0x3, 0x5, 0x320) Sleep(400) ChrTalk( 0x101, "#374F#4P咦,那个门是做什么用的?\x02", ) CloseMessageWindow() SetChrSubChip(0x107, 1) Sleep(400) ChrTalk( 0x107, ( "#390F#6P啊,刚才不是说过吗,\x01", "那扇门是连着露天温泉的。\x02\x03", "里面可是很大的,\x01", "大概可以十个人一起泡哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#370F#4P哎~是这样啊~……\x02", ) CloseMessageWindow() OP_99(0x101, 0x5, 0x3, 0x320) Sleep(100) SetChrSubChip(0x101, 6) Sleep(400) ChrTalk( 0x101, ( "#377F#2P呼~这样泡一下,\x01", "感觉之前旅行的疲劳都释放了出来~\x02", ) ) CloseMessageWindow() SetChrSubChip(0x107, 7) Sleep(400) ChrTalk( 0x107, ( "#390F#5P艾丝蒂尔姐姐,\x01", "你们是徒步旅行的吗?\x02\x03", "为什么不搭乘定期船呢?\x02", ) ) CloseMessageWindow() OP_99(0x101, 0x3, 0x2, 0x320) Sleep(400) ChrTalk( 0x101, ( "#442F#2P嗯……算是为了修行吧。\x02\x03", "#442F#2P还有……\x01", "用老爸的话来说,\x01", "是为了获得在各地修行时的阅历吧。\x02", ) ) CloseMessageWindow() OP_99(0x107, 0x7, 0x9, 0x4B0) OP_99(0x107, 0x9, 0x7, 0x4B0) OP_99(0x107, 0x7, 0x9, 0x4B0) OP_99(0x107, 0x9, 0x7, 0x4B0) Sleep(400) ChrTalk( 0x107, "#393F#5P卡西乌斯叔叔……?\x02", ) CloseMessageWindow() OP_99(0x101, 0x2, 0x4, 0x320) Sleep(400) ChrTalk( 0x101, ( "#376F#2P老爸的徒弟雪拉扎德\x01", "这样对我和约修亚说的。\x02\x03", "因为老爸以前劝导雪拉姐\x01", "在修行的时候一定要徒步旅行。\x02\x03", "要守护一片土地,\x01", "首先就要自己脚踏实地去看一看……\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, "#396F#5P哇,好帅呢……\x02", ) CloseMessageWindow() ChrTalk( 0x101, ( "#378F#2P虽然老爸平时总是爱开玩笑,\x01", "不过关键时刻还是挺靠得住的。\x02", ) ) CloseMessageWindow() OP_99(0x101, 0x4, 0x3, 0x320) Sleep(100) SetChrSubChip(0x101, 6) Sleep(400) ChrTalk( 0x101, ( "#377F#2P唉……\x01", "不知他现在又跑到哪里去了呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, "#392F#5P……艾丝蒂尔姐姐……\x02", ) CloseMessageWindow() OP_99(0x101, 0x3, 0x4, 0x320) Sleep(400) ChrTalk( 0x101, ( "#443F#2P啊哈哈,不好意思,\x01", "这话题好像沉重了点。\x02\x03", "#376F#2P不过,游击士为了修行,\x01", "总不能担心这个那个的而停滞不前吧。\x02", ) ) CloseMessageWindow() OP_99(0x101, 0x4, 0x0, 0x3E8) Sleep(400) ChrTalk( 0x101, ( "#440F#2P现在能做到的……\x01", "嗯……只有相信老爸他了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#393F#5P相信……\x02\x03", "…………………………\x02", ) ) CloseMessageWindow() OP_62(0x101, 0xC8, 1600, 0x26, 0x26, 0xFA, 0x1) Sleep(1000) OP_99(0x101, 0x0, 0x4, 0x3E8) Sleep(400) ChrTalk( 0x101, "#370F#2P咦,怎么了?\x02", ) CloseMessageWindow() SetChrSubChip(0x107, 2) Sleep(80) SetChrSubChip(0x107, 3) Sleep(80) SetChrSubChip(0x107, 2) Sleep(80) SetChrSubChip(0x107, 4) Sleep(80) SetChrSubChip(0x107, 2) Sleep(80) SetChrSubChip(0x107, 3) Sleep(80) SetChrSubChip(0x107, 2) Sleep(80) SetChrSubChip(0x107, 4) Sleep(80) SetChrSubChip(0x107, 2) Sleep(400) ChrTalk( 0x107, "#390F#5P不,没什么。\x02", ) CloseMessageWindow() OP_99(0x107, 0x9, 0x7, 0x320) Sleep(400) ChrTalk( 0x107, ( "#396F#5P啊……对了!\x02\x03", "我有一个问题\x01", "想问艾丝蒂尔姐姐呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#370F#2P有问题要问我?\x02\x03", "什么什么?\x01", "问什么都可以哦~\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#395F#5P嗯嗯,就是~~那个……\x02\x03", "艾丝蒂尔姐姐和约修亚哥哥\x01", "是不是已经结婚了?\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#371F#2P………………………………\x02", ) CloseMessageWindow() ChrTalk( 0x107, "#396F#5P……(紧张紧张)\x02", ) CloseMessageWindow() Fade(250) SetChrSubChip(0x101, 9) OP_0D() OP_99(0x101, 0x9, 0x7, 0x320) Sleep(400) ChrTalk( 0x101, ( "#370F#2P哎,不好意思。\x01", "刚才没听清楚你说的那句话。\x02\x03", "我和约修亚怎么了?\x02", ) ) CloseMessageWindow() OP_99(0x107, 0x7, 0x5, 0x320) Sleep(400) ChrTalk( 0x107, ( "#397F#5P啊~嗯,人家是说……\x01", "你们俩是不是已经结婚了~\x02", ) ) CloseMessageWindow() OP_9E(0x101, 0xF, 0x0, 0x12C, 0xFA0) ChrTalk( 0x101, "#374F#2P怎、怎、怎……\x02", ) CloseMessageWindow() Sleep(400) ChrTalk( 0x101, "#372F#2P#3S怎么会有这种想法!?\x02", ) SetChrSubChip(0x101, 10) OP_7C(0x0, 0xC8, 0xBB8, 0x64) CloseMessageWindow() OP_62(0x107, 0x0, 1700, 0x28, 0x2B, 0x64, 0x3) OP_99(0x107, 0x7, 0x9, 0x514) OP_99(0x107, 0x9, 0x7, 0x514) OP_99(0x107, 0x7, 0x9, 0x514) OP_99(0x107, 0x9, 0x7, 0x514) Sleep(400) ChrTalk( 0x107, ( "#394F#5P因、因为你们用同一个姓氏啊……\x02\x03", "而且你们的长相又不像兄妹,\x01", "我还以为一定是……\x02", ) ) CloseMessageWindow() SetChrSubChip(0x101, 11) Sleep(400) ChrTalk( 0x101, ( "#444F#2P长、长相不像是因为\x01", "我们没有血缘关系啦!\x02\x03", "姓氏相同是因为\x01", "约修亚是老爸的养子啦!\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#393F#5P啊,原来是这样啊……\x02\x03", "#395F嘿嘿,对不起。\x01", "我之前一直误会你们俩是……\x02", ) ) CloseMessageWindow() SetChrSubChip(0x101, 12) Sleep(400) ChrTalk( 0x101, ( "#377F#2P根、根本就是天大的误会……\x02\x03", "而且……\x01", "我和约修亚都只有16岁。\x02\x03", "结婚什么的还早得很呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#395F#5P说、说的也是啊。\x02\x03", "无论两人怎样喜欢对方,\x01", "都不能这么早就结婚的呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#377F#2P……(晕倒)\x02", ) SetChrSubChip(0x101, 13) CloseMessageWindow() Sleep(400) ChrTalk( 0x101, ( "#375F#2P#3S都、都说了嘛!\x01", "我和约修亚根本\x01", "就不是什么恋人啦!\x02", ) ) SetChrSubChip(0x101, 14) OP_7C(0x0, 0xC8, 0xBB8, 0x64) CloseMessageWindow() ChrTalk( 0x101, "#375F#2P#3S只是家人啦,家人!\x02", ) OP_7C(0x0, 0xC8, 0xBB8, 0x64) CloseMessageWindow() OP_99(0x107, 0xA, 0xC, 0x3E8) OP_99(0x107, 0xC, 0xA, 0x3E8) Sleep(400) ChrTalk( 0x107, "#394F#5P是、是这样吗!?\x02", ) CloseMessageWindow() OP_99(0x101, 0xE, 0x10, 0x3E8) Sleep(400) ChrTalk( 0x101, ( "#377F#2P当然是这样啦……\x02\x03", "………………………………\x02", ) ) CloseMessageWindow() SetChrSubChip(0x101, 11) Sleep(400) ChrTalk( 0x101, ( "#444F#2P那个,提妲。\x02\x03", "我和约修亚之间……\x01", "看起来像那样的关系吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, "#393F#5P那样的关系?\x02", ) CloseMessageWindow() SetChrSubChip(0x101, 17) Sleep(400) ChrTalk( 0x101, ( "#441F#2P就、就是说……\x01", "恋、恋人那样的……关系啦。\x02\x03", "爱意浓浓、情意绵绵……\x01", "如胶似漆、难舍难分……之类的啦。\x02", ) ) CloseMessageWindow() OP_99(0x107, 0xB, 0xC, 0x320) Sleep(400) ChrTalk( 0x107, ( "#395F#5P啊……\x01", "倒没那样的感觉呢。\x02\x03", "可是可是,你们总是在一起,\x01", "相处得又那么自然、那么温馨,\x01", "感觉两人好像彼此都互通心意似的……\x02", ) ) CloseMessageWindow() SetChrSubChip(0x101, 10) Sleep(400) ChrTalk( 0x101, ( "#442F#2P唔,如果是你说的那样,\x01", "倒是可能有那么的一点……\x02\x03", "可是这种……\x01", "不是家人或亲友间的关系吗?\x02\x03", "也许,我和约修亚之间\x01", "真的一直都是那样的关系……\x02", ) ) CloseMessageWindow() OP_AD(0x40029, 0x0, 0x0, 0x1F4) Sleep(1200) OP_77(0x0, 0x0, 0x0, 0x0, 0x0) OP_AD(0x40027, 0x0, 0x0, 0x1F4) Sleep(1200) OP_AD(0x4002A, 0x0, 0x0, 0x1F4) Sleep(1200) OP_AD(0x40028, 0x0, 0x0, 0x1F4) Sleep(1200) OP_AD(0x4002B, 0x0, 0x0, 0x1F4) Sleep(1200) OP_77(0xFF, 0xFF, 0xFF, 0x0, 0x0) OP_AE(0x1F4) Sleep(500) OP_62(0x101, 0xC8, 1600, 0x10, 0x13, 0xFA, 0x1) Sleep(1500) ChrTalk( 0x101, "#375F#2P#3S(呀!我在想什么呀~!)\x02", ) SetChrSubChip(0x101, 19) OP_7C(0x0, 0xC8, 0xBB8, 0x64) CloseMessageWindow() SetChrSubChip(0x101, 18) Sleep(400) ChrTalk( 0x101, ( "#441F#2P(这么说,到现在为止,\x01", " 我竟然连那样令人害羞的事都坦然地……)\x02", ) ) CloseMessageWindow() OP_99(0x107, 0xB, 0xA, 0x320) Sleep(400) ChrTalk( 0x107, ( "#393F#5P???\x02\x03", "艾丝蒂尔姐姐?\x01", "你的脸……好红呢……\x02", ) ) CloseMessageWindow() OP_99(0x101, 0xC, 0xA, 0x3E8) Sleep(400) ChrTalk( 0x101, ( "#378F#2P咦咦咦咦……\x01", "没什么啦,什么都没有!\x02\x03", "哎呀~话说回来,\x01", "这里的温泉真的很舒服不是吗!?\x02\x03", "不过对血液循环的促进过于有效了吧。\x01", "头开始有点晕乎乎的了!\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, "#393F#5P是、是吗……\x02", ) CloseMessageWindow() ChrTalk( 0x101, ( "#371F#2P说、说起来,\x01", "外面就是露天澡堂是吧?\x02\x03", "头有点晕了,\x01", "我稍微出去散步一下哦!\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, "#393F#5P啊,好……\x02", ) CloseMessageWindow() OP_43(0x101, 0x1, 0x0, 0xF) SetChrSubChip(0x107, 1) Sleep(500) ChrTalk( 0x107, ( "#393F#3P啊,对了……\x01", "艾丝蒂尔姐姐,露天澡堂是……\x02\x03", "#394F#3P男女混浴……的啊……\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x0)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1E85") OP_31(0x0, 0xFB, 0x0) label("loc_1E85") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x1)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1E98") OP_31(0x1, 0xFB, 0x0) label("loc_1E98") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x2)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1EAB") OP_31(0x2, 0xFB, 0x0) label("loc_1EAB") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x3)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1EBE") OP_31(0x3, 0xFB, 0x0) label("loc_1EBE") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x5)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1ED1") OP_31(0x5, 0xFB, 0x0) label("loc_1ED1") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x4)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1EE4") OP_31(0x4, 0xFB, 0x0) label("loc_1EE4") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x6)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1EF7") OP_31(0x6, 0xFB, 0x0) label("loc_1EF7") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x7)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_1F0A") OP_31(0x7, 0xFB, 0x0) label("loc_1F0A") FadeToDark(1000, 0, -1) OP_0D() SetMapFlags(0x10000000) OP_A2(0x3FA) NewScene("ED6_DT01/T3201 ._SN", 100, 0, 0) IdleLoop() label("loc_1F26") Return() # Function_14_7CB end def Function_15_1F27(): pass label("Function_15_1F27") OP_62(0xFE, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3) ClearChrFlags(0x101, 0x20) ClearChrFlags(0x101, 0x2) ClearChrFlags(0x101, 0x4) SetChrFlags(0x101, 0x1000) SetChrChipByIndex(0x101, 0) SetChrSubChip(0x101, 0) OP_96(0xFE, 0xFFFF0736, 0x0, 0x6C7A, 0x4B0, 0x1770) OP_8E(0xFE, 0xFFFEFE80, 0xFA, 0x7134, 0x1388, 0x0) OP_8C(0xFE, 270, 800) OP_70(0x6, 0x3C) Sleep(60) OP_8E(0x101, 0xFFFEF7A0, 0x0, 0x72CE, 0x1388, 0x0) Sleep(500) OP_72(0x6, 0x800) OP_22(0x7, 0x0, 0x64) OP_6F(0x6, 60) OP_70(0x6, 0x0) Return() # Function_15_1F27 end def Function_16_1FC7(): pass label("Function_16_1FC7") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_1FE5") OP_99(0xFE, 0xE, 0x10, 0x514) OP_99(0xFE, 0x10, 0xF, 0x514) Jump("Function_16_1FC7") label("loc_1FE5") Return() # Function_16_1FC7 end SaveToFile() Try(main)
{ "pile_set_name": "Github" }
Prism.languages.prolog = { // Syntax depends on the implementation 'comment': [ /%.+/, /\/\*[\s\S]*?\*\// ], // Depending on the implementation, strings may allow escaped newlines and quote-escape 'string': /(["'])(?:\1\1|\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, 'builtin': /\b(?:fx|fy|xf[xy]?|yfx?)\b/, 'variable': /\b[A-Z_]\w*/, // FIXME: Should we list all null-ary predicates (not followed by a parenthesis) like halt, trace, etc.? 'function': /\b[a-z]\w*(?:(?=\()|\/\d+)/, 'number': /\b\d+\.?\d*/, // Custom operators are allowed 'operator': /[:\\=><\-?*@\/;+^|!$.]+|\b(?:is|mod|not|xor)\b/, 'punctuation': /[(){}\[\],]/ };
{ "pile_set_name": "Github" }
var parset = require('parse-messy-time') var nums1to4 = '(1st|2nd|3rd|4th|first|second|third|fourth)' var numNames = { first: '1st', second: '2nd', third: '3rd', fourth: '4th' } var re = {} re.time = /(\d+:\d+|\d+(?::\d+)?\s*(?:pm|am))/ re.every = RegExp( '(?:' + re.time.source + '\\s+)?' + '(every|each)?\\s+(?:(other)\\s+|' + nums1to4 + '(?:(?:\\s*,\\s*|\\s+(and|through)\\s+)' + nums1to4 + ')?' + '\\s+)?' + '(?:((?:mon|tues?|wed(?:nes)?|thurs?|fri|sat(?:ur)?|sun)(?:days?)?' + '|tomorrow|day)\\b)' + '(?:\\s+(.+?))?' + '\\s*$', 'i' ) re.months = RegExp('(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)' + '|may|june?|july?|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?' + '|nov(?:ember)|dec(?:ember)?)', 'i' ) var months = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'july', 'aug', 'sep', 'oct', 'nov', 'dec' ] re.evmonth = RegExp( '(?:(every|each)\\s+)?(' + '(\\d+)(?:st|nd|rd|th)?\\s+' + re.months.source + '|' + re.months.source + '\\s+(\\d+)(?:st|nd|rd|th)?\\b)' ) re.nth = RegExp('(\\d+)\\s*(?:st|nd|rd|th)\\b') re.titleBreak = RegExp( '\\b(each|every|tomorrow|' + '(?:mon|tues?|wed(?:nes)?|thurs?|fri|sat(?:ur)?|sun)(?:days?)?' + ')\\b', 'i' ) re.starting = /\b(?:starting|from)\s+(.+)/ re.until = /\b(?:until|to)\s+(.+)/ function nthf (s) { var m = re.nth.exec(s) if (m) return { n: m[1], time: s.replace(re.nth, '').trim() } } function monthf (s) { var m = re.evmonth.exec(s) if (m) return { date: fix(Number(m[3] || m[6])), month: months.indexOf(String(m[4] || m[5]).slice(0,3).toLowerCase()), time: s.replace(re.evmonth, '').trim() } function fix (n) { return isNaN(n) ? undefined : n } } function everyf (s, now) { if (!now) now = new Date var m = re.every.exec(s) if (!m) return m var time = m[1] || m[8] || null if (time) time = time.replace(/\s+(starting|until).*/, '') var ut = time && !re.time.test(m[10]) ? ' ' + time : '' if (ut) ut = ut.replace(/\b(starting|until).*/, '') var mst = re.starting.exec(s) if (mst) mst = mst[1].split(/\buntil\b/i)[0] var ust = re.until.exec(s) if (ust) ust = ust[1].split(/\bstarting\b/i)[0] return { every: Boolean(m[2] || /days$/i.test(m[7])), other: Boolean(m[3]), numbered: m[4] ? normNum( m[4] && m[5] === 'through' && m[6] ? thru(m[4], m[6]) : m[6] ? [ m[4], m[6] ] : [ m[4] ] ) : null, time: time, day: String(m[7]).toLowerCase(), starting: mst ? parset(mst + ut, { now: now }) : null, until: ust ? parset(ust + ut, { now: now }) : null, index: m.index } } function normNum (xs) { return xs.map(function (x) { x = (x || '').toLowerCase() return numNames[x] || x }) } function thru (a, b) { var m = normNum([ a, b ]) var ns = Object.keys(numNames) .map(function (n) { return numNames[n] }) .sort() ns.forEach(function (n) { if (n > m[m.length-2] && n < m[m.length-1]) { m.splice(m.length-1, 0, n) } }) return m } function countWeeks (a, b) { return Math.round((b.getTime() - a.getTime()) / 1000 / 60 / 60 / 24 / 7) } module.exports = Mess function Mess (str, opts) { if (!(this instanceof Mess)) return new Mess(str, opts) if (!opts) opts = {} this._every = everyf(str, opts.created) this._nth = nthf(str) this._month = monthf(str) this._created = opts.created this.title = this._every ? str.slice(0, this._every.index).trim().replace(/"/g, '') : null if (this.title) { var esp = str.split(re.titleBreak) var mstr = esp.slice(0,-4).join('').trim() if (mstr.length > this.title.length) { this.title = mstr var m = /(['"])([^\1]+)\1/.exec(this.title) if (m) this.title = m[2] } } this.oneTime = Boolean(!(this._every && this._every.every)) this.range = [ new Date(-864e13), new Date(864e13) ] if (this.oneTime) { var t = this.next(this._created) if (!t) t = this.prev(this._created) if (!t) { t = parset(str) } this.range[0] = t this.range[1] = t } if (this._every && this._every.starting) { this.range[0] = this._every.starting } if (this._every && this._every.until) { this.range[1] = this._every.until } if (this.range[0] > this.range[1] && this.range[0].getFullYear()-1 === this.range[1].getFullYear()) { this.range[0].setYear(this.range[0].getFullYear()-1) } } Mess.prototype.next = function (base) { return this._advance(1, base) } Mess.prototype.prev = function (base) { return this._advance(-1, base) } Mess.prototype._advance = function (dir, base) { if (!base) base = new Date if (typeof base === 'string') base = parset(base, { now: this._created }) if (this._every && this._every.numbered) { //... } else if (this._every && this._every.every) { var tt = this._every.time ? ' at ' + this._every.time : '' var t = base if (this._every.starting && t < this._every.starting) { t = this._every.starting } else if (this._every.until && t > this._every.until) { t = this._every.until } else if (this._every.day === 'day') { t = parset(tt, { now: base }) } else if (!this._every.time || this._every.time.split(/\s+/).length <= 4) { t = parset('this ' + this._every.day + tt, { now: base }) } if (((dir > 0 && t <= base) || (dir < 0 && t >= base)) && this._every.day === 'day') { t.setDate(t.getDate() + 1 * dir) } else if ((dir > 0 && t <= base) || (dir < 0 && t >= base)) { t.setDate(t.getDate() + 7 * dir) } if ((this._every.starting || this._created) && this._every.other) { var x = this._every.starting || this._created var w = ((countWeeks(x, t) % 2) + 2) % 2 if (w % 2 !== 0) t.setDate(t.getDate() + 7 * dir) } if (this._every.until && tgt(t, this._every.until)) return null if (this._every.starting && tlt(t, this._every.starting)) return null return t } else if (this._every && (this._created || this._every.starting)) { var x = this._every.starting || this._created var tt = this._every.time ? ' at ' + this._every.time : '' var t = parset('this ' + this._every.day + tt, { now: x }) if (dir > 0 && t <= base) return null else if (dir < 0 && t >= base) return null return t } else if (this._month) { var t = this._month.time ? parset(this._month.time, { now: base }) : base if ((this._month.month < base.getMonth() || (this._month.month === base.getMonth() && this._month.date <= base.getDate()))) { t.setFullYear(t.getFullYear() + dir) } t.setMonth(this._month.month) t.setDate(this._month.date) return t } else if (this._nth) { var t = this._nth.time ? parset(this._nth.time, { now: base }) : base t.setDate(this._nth.n) if (dir > 0 && base.getDate() >= t.getDate()) { t.setMonth(t.getMonth() + 1) } else if (dir < 0 && base.getDate() <= t.getDate()) { t.setMonth(t.getMonth() - 1) } return t } } function tlt (a, b) { return a.getTime() + 1000 < b.getTime() } function tgt (a, b) { return a.getTime() - 1000 > b.getTime() }
{ "pile_set_name": "Github" }